<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Order;
use App\Models\Invoice;
use Carbon\carbon;
use DateTime;
use Illuminate\Support\Facades\Http;

class GeneralController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    
    public function getPrice($id)
    {
       $price = \DB::table('final_productions')->where('FinalProductionID', $id)->first();
       
       return $data = collect([
           'price' => $price->UnitPrice,
           'category' => $price->production_category
       ]);
    }


    public function index()
    {   
        
        return view('product.product-list', [
            'items' => \DB::table('final_productions')
            ->where('store_category', 0)
            ->get()
        ]);
    }

    public function indexBarItems()
    {   
        
        return view('product.product-list', [
            'items' => \DB::table('final_productions')
            ->where('store_category', 1)
            ->get()
        ]);
    }


    public function getUserName($id)
    {
        $user = User::findOrfail($id);
        return $user->name;
    }

    public function getPriceLocation($id)
    {   
       $price = \DB::table('dispatch_items')->where('id', $id)->first();
       return $results = $price -> location_price;
    }


    public function search(Request $request)
    {
        
        $results = Invoice::Where('invoice_number', 'like', '%' . $request->search . '%')->get();
        $customer = Order::where('order_id', $request->search)->first();
        
        if (empty($customer)) {
            return back()->with('status', "Receipt not Available");
        }

        return view('inc.search-results', [
            'orders' => $results,
            'customer_id' => $customer -> customer_id
        ]);
    }

    public function itemSummary($id)
    {   
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $user_details = User::findOrfail($id);
        $items = \DB::table('invoices')
        ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
        ->where('user_id', $id)
                ->groupBy('invoice_product_name')
        ->where('invoice_category', '!=', "TRANSPORT")
        ->groupBy('invoice_unit_price')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();


        $itemsQuantity = \DB::table('invoices')
        ->where('user_id', $id)
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
        ->where('user_id', $id)
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_total_price');

        return view('item-summary', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
            'user_details' => $user_details
        ]);
    }


    public function itemSummaryAdmin()
    {
        // getDay close
        $getDayClose = \DB::table('close_days')->first();
        $items = \DB::table('invoices')
        ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->groupBy('invoice_product_name')
        ->groupBy('invoice_unit_price')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();

        $itemsQuantity = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_total_price');

        return view('item-summary-admin', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice
        ]);
    }



    public function itemSummaryBranch($branch)
    {   
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $items = \DB::table('invoices')
        ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->where('branch', $branch)
        ->groupBy('invoice_product_name')
        ->groupBy('invoice_unit_price')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();

        $itemsQuantity = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->where('branch', $branch)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->where('branch', $branch)
        ->sum('invoice_total_price');

        return view('item-summary-branch', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
            'branch' => $branch
        ]);
    }


    public function itemSummarySalesType($branch, $category)
    {
        // getDay close
        $getDayClose = \DB::table('close_days')->first();
        $items = \DB::table('invoices')
        ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->where('invoice_sales_person_category', $category)
        ->where('branch', $branch)
        ->groupBy('invoice_product_name')
        ->groupBy('invoice_unit_price')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();

        $itemsQuantity = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->where('invoice_sales_person_category', $category)
        ->where('branch', $branch)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->where('invoice_sales_person_category', $category)
        ->where('branch', $branch)
        ->sum('invoice_total_price');

        return view('item-summary-branch-sales-person', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
            'branch' => $branch,
            'category' => $category
        ]);
    }



    public function itemSummarySalesTypeProduct($branch, $category)
    {   
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $items = \DB::table('invoices')
        ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->where('invoice_sales_person_category', $category)
        ->where('branch', $branch)
        ->groupBy('invoice_category')
        ->groupBy('invoice_unit_price')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();

        $itemsQuantity = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->where('invoice_sales_person_category', $category)
        ->where('branch', $branch)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->where('invoice_sales_person_category', $category)
        ->where('branch', $branch)
        ->sum('invoice_total_price');

        return view('item-summary-branch-sales-person', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
            'branch' => $branch,
            'category' => $category
        ]);
    }


    public function departmentSummarybyDate(Request $request)
    {   
        $value = explode(' - ', $request->date);
         
        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');

        $user_details = User::findOrfail($request->user_id);

        if ($from == $to) {
            $items = \DB::table('invoices')
            ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
            ->where('user_id', $request->user_id)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->groupBy('invoice_category')
            ->whereDate('created_at', $from)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
            ->where('user_id', $request->user_id)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
            ->where('user_id', $request->user_id)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_total_price');
    
            return view('department-summary-admin', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
                'user_details' => $user_details
            ]);
        }else {
            $items = \DB::table('invoices')
                ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                ->where('user_id', $request->user_id)
                                ->groupBy('invoice_category')
                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
                ->WhereDate('created_at','<=', $to)
                ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                ->where('user_id', $request->user_id)
                                ->where('invoice_category', '!=', "TRANSPORT")
                                ->WhereDate('created_at','>=', $from)
                                ->WhereDate('created_at','<=', $to)
                ->sum('invoice_quantity');
        
            $itemsPrice = \DB::table('invoices')
                ->where('user_id', $request->user_id)
                                ->where('invoice_category', '!=', "TRANSPORT")
                                ->WhereDate('created_at','>=', $from)
                                ->WhereDate('created_at','<=', $to)
                ->sum('invoice_total_price');
        
            return view('department-summary-admin', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
                'user_details' => $user_details
            ]);
        }

    }



    public function departmentSummaryDate(Request $request)
    {
        $value = explode(' - ', $request->date);
         

        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');


        if ($from == $to) {
            $items = \DB::table('invoices')
            ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->groupBy('invoice_category')
            ->whereDate('created_at', $from)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_total_price');
    
            return view('department-summary-admin', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }else {
            $items = \DB::table('invoices')
                ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                ->where('invoice_sales_person_category', $request -> category)
                ->where('branch', $request -> branch)
                                ->groupBy('invoice_category')
                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
                ->WhereDate('created_at','<=', $to)
                ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                ->where('invoice_sales_person_category', $request -> category)
                ->where('branch', $request -> branch)
                                ->where('invoice_category', '!=', "TRANSPORT")
                                ->WhereDate('created_at','>=', $from)
                                ->WhereDate('created_at','<=', $to)
                ->sum('invoice_quantity');
        
            $itemsPrice = \DB::table('invoices')
                ->where('invoice_sales_person_category', $request -> category)
                ->where('branch', $request -> branch)
                                ->where('invoice_category', '!=', "TRANSPORT")
                                ->WhereDate('created_at','>=', $from)
                                ->WhereDate('created_at','<=', $to)
                ->sum('invoice_total_price');
        
            return view('department-summary-admin', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }
    }




    public function itemSummaryDate(Request $request)
    {
        $value = explode(' - ', $request->date);
         

        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');


        if ($from == $to) {
            $items = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_sales_person_category',$request -> category)
            ->where('branch', $request -> branch)
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->whereDate('created_at', $from)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_total_price');
    
            return view('item-summary-branch-sales-person', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
                'branch' => $request -> branch,
                'category' => $request -> category
            ]);
        }else {
           $items = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
            ->where('invoice_sales_person_category', $request -> category)
            ->where('branch', $request -> branch)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->sum('invoice_total_price');
    
            return view('item-summary-branch-sales-person', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
                'branch' => $request->branch,
                'category' => $request->category
            ]);
        }
    }


    public function itemSummarybyDate(Request $request)
    {
        $value = explode(' - ', $request->date);
         

        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');

        $user_details = User::findOrfail($request->user_id);

        if ($from == $to) {
            $items = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
            ->where('user_id', $request->user_id)
                        ->groupBy('invoice_product_name')
            ->where('invoice_category', '!=', "TRANSPORT")
            ->groupBy('invoice_unit_price')
            ->whereDate('created_at', $from)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
            ->where('user_id', $request->user_id)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
            ->where('user_id', $request->user_id)
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_total_price');
    
            return view('item-summary', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice
            ]);
        }else {
            $items = \DB::table('invoices')
                ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                ->where('user_id', $request->user_id)
                                ->groupBy('invoice_product_name')
                ->where('invoice_category', '!=', "TRANSPORT")
                ->groupBy('invoice_unit_price')
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                ->where('user_id', $request->user_id)
                                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->sum('invoice_quantity');
        
            $itemsPrice = \DB::table('invoices')
                ->where('user_id', $request->user_id)
                                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->sum('invoice_total_price');
        
            return view('item-summary', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice
            ]);
        }

    }
    

    public function departmentSummary($id)
    {
        
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $items = \DB::table('invoices')
        ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
        ->where('user_id', $id)
                ->where('invoice_category', '!=', "TRANSPORT")
        ->groupBy('invoice_category')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();


        $itemsQuantity = \DB::table('invoices')
        ->where('user_id', $id)
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
        ->where('user_id', $id)
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_total_price');

        return view('inc.department-summary', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
        ]);
    }


    public function departmentSummaryAdmin()
    {   
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $items = \DB::table('invoices')
        ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->groupBy('invoice_category')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();


        $itemsQuantity = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_total_price');

        return view('department-summary-admin', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
        ]);
    }

    public function departmentSummaryBranch($branch)
    {   
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $items = \DB::table('invoices')
        ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                ->where('branch', $branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->groupBy('invoice_category')
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();


        $itemsQuantity = \DB::table('invoices')
                ->where('branch', $branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('branch', $branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_total_price');

        return view('department-summary-branch', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
            'branch' => $branch
        ]);
    }



    public function AcceptPayment(Request $request)
    {   

        $this->validate($request, [
            'amount' => 'required',
            'phone' => 'required|numeric',
            'network' => 'required'
        ]);

        if (auth()->user()->sales_person_category == "Delivery" || auth()->user()->sales_person_category == "Drive Thru") {
            $branch = \DB::table('branches')->where('branch_name', auth()->user()->branch)->first();
            if ($branch->tingg_delivery == null) {
                return back()->with('status', "No Counter Code Assigned to Branch");
            }
            $tingg_code = $branch->tingg_delivery;
        }elseif (auth()->user()->sales_person_category == "Counter") {
            $branch = \DB::table('branches')->where('branch_name', auth()->user()->branch)->first();
            if ($branch->tingg_counter == null) {
                return back()->with('status', "No Counter Code Assigned to Branch");
            }
            $tingg_code = $branch->tingg_counter;
        }
        
        $response = Http::post('https://accounts.tingg.africa/api/v1/oauth/token?scope=*&grant_type=password&client_id=instore&username=pizzaman_api_user&password=_f.6e8%3BBt%269kZ%5B%3EwpJ%2AIVW%29J64%2CJuAoS');
        $token = $response->collect();
        $access = $token->toArray();

        $number = "233" . substr($request->phone, 1);

        $curl = curl_init();

            curl_setopt_array($curl, array(
            CURLOPT_URL => "https://payments.instore.tingg.africa/initiateMerchantPayment",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\n\t\"payerClientCode\": \"$request->network\",\n\t\"amount\": \"$request->amount\",\n\t\"msisdn\": \"$number\",\n\t\"counterCode\": \"$tingg_code\"\n}",
            CURLOPT_HTTPHEADER => array(
                "Authorization: Bearer " . $access['access_token'],
                "cache-control: no-cache",
                "content-type: application/json",
                "currency-code: GHS",
                "postman-token: 291165e9-ca00-23fd-d7f3-905737d28b51",
                "request-origin: TINGG_INSTORE_usSD",
                "x-country-code: GHA"
            ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
            echo "cURL Error #:" . $err;
            } else {
            $decoded = json_decode($response);
            }
                $curl = curl_init();

                curl_setopt_array($curl, array(
                CURLOPT_URL => "https://payments.instore.tingg.africa/payment/?merchantTransactionID=" . $decoded->data->merchantTransactionID,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_HTTPHEADER => array(
                    "Authorization: Bearer " . $access['access_token'],
                    "cache-control: no-cache",
                    "postman-token: decc9e11-4688-f388-ec4e-7a5b00f3b238"
                ),
                ));

                $response = curl_exec($curl);
                $err = curl_error($curl);

                curl_close($curl);

                if ($err) {
                echo "cURL Error #:" . $err;
                } else {
                $response . '</br>' . $decoded->data->merchantTransactionID;
                
                }


            return back()->with('status', '<center>'.'Payment Initiated Successfully, Waiting Approval From Customer'.'</center>');

        
    }


    public function checkPaymentStatus()
    {

        $response = Http::post('https://accounts.tingg.africa/api/v1/oauth/token?scope=*&grant_type=password&client_id=instore&username=pizzaman_api_user&password=_f.6e8%3BBt%269kZ%5B%3EwpJ%2AIVW%29J64%2CJuAoS');
        $token = $response->collect();
        $access = $token->toArray();

        $curl = curl_init();

                curl_setopt_array($curl, array(
                CURLOPT_URL => "https://payments.instore.tingg.africa/payment/?merchantTransactionID=12135",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_HTTPHEADER => array(
                    "Authorization: Bearer " . $access['access_token'],
                    "cache-control: no-cache",
                    "postman-token: decc9e11-4688-f388-ec4e-7a5b00f3b238"
                ),
                ));

                $response = curl_exec($curl);
                $err = curl_error($curl);

                curl_close($curl);

                if ($err) {
                echo "cURL Error #:" . $err;
                } else {
                echo $response;
                
                }
    }



    public function ProcessingTransactions(Request $request)
    {   
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        if (auth()->user()->role == "Call Center") {
            $process = \DB::table('dispatches')
            ->select('dispatches.order_number', 'dispatches.ordered_at', 'dispatches.customer_phone','dispatches.amount', 'dispatches.deliveryamount', 'dispatches.order_number', 'dispatches.dispatched_at', 'dispatches.dispatch_branch', 'riders.rd_name','riders.rd_phone')
            ->join('riders', 'dispatches.rider_id','riders.id')
            ->where('dispatches.status', 1)
            ->where('dispatches.dispatch_status', 0)
            ->whereDate('dispatches.created_at', $getDayClose->day_close)
            ->get();
        }else {
            $process = \DB::table('dispatches')
            ->select('dispatches.order_number', 'dispatches.ordered_at', 'dispatches.customer_phone','dispatches.amount', 'dispatches.deliveryamount', 'dispatches.order_number', 'dispatches.dispatched_at', 'dispatches.dispatch_branch', 'riders.rd_name','riders.rd_phone')
            ->join('riders', 'dispatches.rider_id','riders.id')
            ->where('dispatches.status', 1)
            ->where('dispatches.dispatch_status', 0)
            ->whereDate('dispatches.created_at', $getDayClose->day_close)
            ->where('dispatches.dispatch_branch', auth()->user()->branch)
            ->get();
        }

        return view('processing', [
            'process' => $process
        ]);
    }



    public function showDepartmentItem($department)
    {   
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $items_category = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_category', $department)
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->whereDate('created_at', $getDayClose->day_close)
            ->get();

        return view('inc/show-items', [
            'department' => $department,
            'items_category' => $items_category,
            'date' => $getDayClose->day_close
        ]);
    }


    public function showDepartmentItemWithDate()
    {   
        $value = explode(' - ', request('date'));
        
        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');

        if ($from == $to) {
        $items_category = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_category', request('category'))
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->whereDate('created_at', $from)
            ->where('user_id', request('userID'))
            ->get();
        }else {
            $items_category = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_category', request('category'))
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->where('user_id', request('userID'))
            ->get();
        }

        return view('inc/show-items', [
            'department' => request('category'),
            'items_category' => $items_category,
            'date' => request('date')
        ]);
    }


    

    public function productSummary($id)
    {   // getDay close
        $getDayClose = \DB::table('close_days')->first();

        $items = \DB::table('invoices')
        ->where('user_id', $id)
                ->whereDate('created_at', $getDayClose->day_close)
        ->get();

        $grouped = $items->groupBy('invoice_product_name');
        return view('inc.department-summary', [
            'group' => $grouped->all()
        ]);
    }



    public function allDepartmentSummary(Request $request)
    {
        $value = explode(' - ', $request->date);
        
        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');

        if ($from == $to) {
            $items = \DB::table('invoices')
            ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->groupBy('invoice_category')
            ->whereDate('created_at', $from)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_total_price');
    
            return view('department-summary-all-using-date', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }else {
            $items = \DB::table('invoices')
                ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                                ->groupBy('invoice_category')
                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->sum('invoice_quantity');
        
            $itemsPrice = \DB::table('invoices')
                                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->sum('invoice_total_price');
        
            return view('department-summary-all-using-date', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }
    }



    public function allDepartmentSummaryBranch(Request $request)
    {
        $value = explode(' - ', $request->date);
        
        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');

        if ($from == $to) {
            $items = \DB::table('invoices')
            ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                        ->where('branch', $request->branch)
            ->where('invoice_category', '!=', "TRANSPORT")
            ->groupBy('invoice_category')
            ->whereDate('created_at', $from)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('branch', $request->branch)
            ->whereDate('created_at', $from)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
                        ->where('branch', $request->branch)
            ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_total_price');
    
            return view('department-summary-all-using-date', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }else {
            $items = \DB::table('invoices')
                ->selectRaw('invoice_category as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity')
                                ->where('branch', $request->branch)
                ->groupBy('invoice_category')
                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                                ->where('branch', $request->branch)
                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->sum('invoice_quantity');
        
            $itemsPrice = \DB::table('invoices')
                ->where('branch', $request->branch)
                                ->where('invoice_category', '!=', "TRANSPORT")
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
                ->sum('invoice_total_price');
        
            return view('department-summary-all-using-date', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }
    }



    public function showDepartmentItemDate(Request $request)
    {   

        $value = explode(' - ', $request->date);
         

        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');
        
    if ($request->branch == null) {
    
        if ($from == $to) {

        $itemlist = \DB::table('invoices')
        ->where('invoice_category', $request->name)
                ->whereDate('created_at', $from)
        ->get();

        $cash = \DB::table('invoices')
            ->where('invoice_category', $request->name)
                        ->whereDate('created_at', $from)
            ->sum('invoice_total_price');

        $items_category = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_category', $request->name)
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->whereDate('created_at', $from)
            ->get();

        return view('inc/show-items', [
            'items' => $itemlist,
            'department' => $request->name,
            'cash' => $cash,
            'items_category' => $items_category 
        ]);
    }else {
        $itemlist = \DB::table('invoices')
        ->where('invoice_category', $request->name)
                ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
        ->get();

        $cash = \DB::table('invoices')
            ->where('invoice_category', $request->name)
                        ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->sum('invoice_total_price');

        $items_category = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_category', $request->name)
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->get();

        return view('inc/show-items', [
            'items' => $itemlist,
            'department' => $request->name,
            'cash' => $cash,
            'items_category' => $items_category 
        ]);
    }
}

else {
    if ($from == $to) {

        $itemlist = \DB::table('invoices')
        ->where('invoice_category', $request->name)
        ->where('branch', $request->branch)
                ->whereDate('created_at', $from)
        ->get();

        $cash = \DB::table('invoices')
            ->where('invoice_category', $request->name)
            ->where('branch', $request->branch)
                        ->whereDate('created_at', $from)
            ->sum('invoice_total_price');

        $items_category = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('branch', $request->branch)
            ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_category', $request->name)
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->whereDate('created_at', $from)
            ->get();

        return view('inc/show-items', [
            'items' => $itemlist,
            'department' => $request->name,
            'cash' => $cash,
            'items_category' => $items_category 
        ]);
    }else {
        $itemlist = \DB::table('invoices')
        ->where('invoice_category', $request->name)
                ->where('branch', $request->branch)
        ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
        ->get();

        $cash = \DB::table('invoices')
            ->where('invoice_category', $request->name)
                        ->where('branch', $request->branch)
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->sum('invoice_total_price');

        $items_category = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('branch', $request->branch)
            ->where('invoice_category', '!=', "TRANSPORT")
            ->where('invoice_category', $request->name)
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->get();

        return view('inc/show-items', [
            'items' => $itemlist,
            'department' => $request->name,
            'cash' => $cash,
            'items_category' => $items_category 
        ]);
    }
}
    }



    public function allItemSummary(Request $request)
    {
        $value = explode(' - ', $request->date);
         

        $source1 = $value[0];
        $date1 = new DateTime($source1);
        $from = $date1->format('Y-m-d');

        $source2 = $value[1];
        $date2 = new DateTime($source2);
        $to = $date2->format('Y-m-d');


        if ($from == $to) {
            $items = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->whereDate('created_at', $from)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->whereDate('created_at', $from)
            ->sum('invoice_total_price');
    
            return view('item-summary-all', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }else {
           $items = \DB::table('invoices')
            ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->groupBy('invoice_product_name')
            ->groupBy('invoice_unit_price')
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->get();
    
    
            $itemsQuantity = \DB::table('invoices')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->sum('invoice_quantity');
    
            $itemsPrice = \DB::table('invoices')
                        ->where('invoice_category', '!=', "TRANSPORT")
            ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
            ->sum('invoice_total_price');
    
            return view('item-summary-all', [
                'items' => $items,
                'itemsQuantity' => $itemsQuantity,
                'itemsPrice' => $itemsPrice,
            ]);
        }
    }





    
public function allItemSummaryBranches(Request $request)
{
    $value = explode(' - ', $request->date);
     

    $source1 = $value[0];
    $date1 = new DateTime($source1);
    $from = $date1->format('Y-m-d');

    $source2 = $value[1];
    $date2 = new DateTime($source2);
    $to = $date2->format('Y-m-d');


    if ($from == $to) {
        $items = \DB::table('invoices')
        ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                ->where('branch', $request->branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->groupBy('invoice_product_name')
        ->groupBy('invoice_unit_price')
        ->whereDate('created_at', $from)
        ->get();


        $itemsQuantity = \DB::table('invoices')
                ->where('branch', $request->branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $from)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('branch', $request->branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->whereDate('created_at', $from)
        ->sum('invoice_total_price');

        return view('item-summary-all', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
        ]);
    }else {
       $items = \DB::table('invoices')
        ->selectRaw('invoice_product_name as name, sum(invoice_total_price) as total, sum(invoice_quantity) as quantity, invoice_unit_price as price')
                ->where('branch', $request->branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->groupBy('invoice_product_name')
        ->groupBy('invoice_unit_price')
        ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
        ->get();


        $itemsQuantity = \DB::table('invoices')
                ->where('branch', $request->branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
        ->sum('invoice_quantity');

        $itemsPrice = \DB::table('invoices')
                ->where('branch', $request->branch)
        ->where('invoice_category', '!=', "TRANSPORT")
        ->WhereDate('created_at','>=', $from)
            ->WhereDate('created_at','<=', $to)
        ->sum('invoice_total_price');

        return view('item-summary-all', [
            'items' => $items,
            'itemsQuantity' => $itemsQuantity,
            'itemsPrice' => $itemsPrice,
        ]);
        }
    }



    public function DirectDelivery(Request $request)
    {
        if (auth()->user()->role == "Call Center") {
            $this->validate($request, [
                'branch' => ['required'],
                'type' => ['required'],
            ]);
        }

        try {
            // Perform DB Transaction
            \DB::beginTransaction();
            if (auth()->user()->role == "Call Center") {
                User::where('id', auth()->user()->id)->update(
                    [
                        'branch' => $request->branch
                    ]
                    );
            }
            \DB::commit();
            if ($request->type == "GENERAL DELIVERY") {
                return redirect('/ceqa-dashboard/create-invoice');
            }else {
                return redirect('/ceqa-dashboard/create-invoice/delivery-agency-service/' . $request->type);
            }
        
        } catch (\Throwable $th) {
            return response([
                'status' => "Error",
                'Message' => $th
            ]);
        }
    }


    public function RejectItem()
    {
        $product = \DB::table('invoices')->where('id', session()->get('rejectInvoice'))->first();
        $bom = \DB::table('material_product_compositons')->where('product_id', $product->product_id)->get();

        return view('inc.rejected-order-bom', [
            'p_comp'=> $bom,
            'product' => $product
        ]);
    }
}


