<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\InvoiceDump;
use App\Models\User;
use App\Models\Customer;
use App\Models\Waiting;
use App\Models\Order;
use App\Models\Discount;
use Illuminate\Http\Request;
use Carbon\carbon;
use Illuminate\Support\Facades\Http;
use DateTime;
use App\Models\CompositionRecord;
use App\Models\CostOfSaleAnalysis;
use App\Models\InventoryReport;
use App\Models\TargetAnalysis;
use App\Models\BomReportOnSale;
use App\Models\BarTable;
use Session;
use Illuminate\Support\Facades\Cache;

class InvoiceController extends Controller
{
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
       $this->middleware('auth');
    }
    
    public function index()
    {   
        
        Cache::put('products', \DB::table('final_productions')
        ->where('store_category', 0)
        ->get());
       
        if (auth()->user()->role == "Dispatch Manager" || auth()->user()->role == "Branch Officer" || auth()->user()->role == "Administrator" || auth()->user()->role == "Retention Officer") {
        abort(403, "Sorry!, You are not authorized");
    }else {
        if (auth()->user()->sales_person_category == "Delivery") {
            return view('invoice.customer-details');
            // if (auth()->user()->role == "Call Center") {
            //     return redirect()->route('callcenterInvoice');
            // }else {
            //     return view('invoice.customer-details');
            // }
        }elseif (auth()->user()->sales_person_category == "Driver Thru") {
            return view('invoice.create-invoice-drive-thru');
        }
        else{

        // load Products
        if (empty(Cache::get('products'))) {
            Cache::put('products', \DB::table('final_productions')
            ->where('store_category', 0)
            ->get());
        }

        $products = Cache::get('products'); 

        // $products = \DB::table('final_productions')->where('store_category', 0)->get();

        $confirmIfBar = \DB::table('branches')->where('branch_name', auth()->user()->branch)->first();
        if ($confirmIfBar->store_type == 1) {
             // load Products
        if (empty(Cache::get('products2'))) {
            Cache::put('products2', \DB::table('final_productions')->where('store_category', 1)->get());
        }

        $products = Cache::get('products2'); 
            return view('invoice.create-invoice-bar', [
                'products' => $products,
            ]);
        }
       
        return view('invoice.create-invoice', [
            'products' => $products
            ]);
         }
        }
    }

    public function callcenterInvoice()
    {

        // load Products
        if (empty(Cache::get('products'))) {
            Cache::put('products', \DB::table('final_productions')
            ->where('store_category', 0)
            ->get());
        }

        return view('invoice.create-invoice-grid', [
            'products' =>  Cache::get('products')
            ]);
    }


    public function generateInvoiceBar()
    {   
        $check = session()->get('cart');
        if (empty($check)) {
            return back()->with('statuspass',"Cart is Empty");
        }

        $this->validate(request(), [
            'table_name' => 'required'
        ]);
        
        // getDay close
        $getDayClose = \DB::table('close_days')->first();

        if (empty(session()->get('invoice_number'))) {
            $generateInvoice = substr(auth()->user()->branch, 0,3) . rand(5034580,10034580)+rand(5034580,10034580) . date("Yd") . date('Hi');
            session()->put('invoice_number', $generateInvoice);
        }

        $data = [
            'user_id' => auth()->id(),
            'table_name' => request('table_name'),
            'table_served_by' => request('table_served_by'),
            'invoice_number' => session()->get('invoice_number'),
            'branch' => auth()->user()->branch,
            'date' => $getDayClose -> day_close,
            'table_settlement' => empty(request('table_settlement')) ? 0 : 1,
        ];

        BarTable::create($data);

        return redirect()->to('/generate-invoice');
    }

    
    

    public function generateInvoice($id = null)
    {   
        if (empty(session()->get('cart'))) {
            return back()->with('status', 'No Item Added to Cart');
        }
        try {
            // Perform DB Transaction
            \DB::beginTransaction();
            // Create Invoice Transaction, Move From  Dump to Main Invoice Table
            $this -> make_transaction( $id );
            \DB::commit(); 
            return redirect()->to('/ceqa-dashboard/print-invoice/' .  session()->get('invoice_number'));
            } catch (\Throwable $th) {
                \DB::rollback();
                $res = response([
                    'status' => 501,
                    "message" => $th
                ]);
                return back()->with('statuspass', "Oops Something Happend, Transaction unsuccessufull");
                
            } 
    }

    

    public function generateInvoiceDelivery($id)
    {   
        if (empty(session()->get('cart'))) {
            return back()->with('status', 'No Item Added to Cart');
        }
        try {
            // Perform DB Transaction
            \DB::beginTransaction();
            // Create Invoice Transaction, Move From  Dump to Main Invoice Table
            $this -> make_transaction($id);
            \DB::commit();  
            return redirect()->to('/ceqa-dashboard/print-invoice/delivery/' .  session()->get('invoice_number') . "/" . $id);

        } catch (\Throwable $th) {
            \DB::rollback();
            return response([
                'status' => 501,
                "Message" => $th
            ]);
        }
    }


    public function salesToday()
    {   
        $this->authorize('viewAny', App\Models\Invoice::class);

        return view('sales.sales-today', [
            'branches' => \DB::table('branches')->get(),
            'branch_officer' => \DB::table('branches')->where('branch_name', auth()->user()->branch)->first(),
            'branch_user' => \DB::table('users')->where('branch', '!=', "")->where('branch', auth()->user()->branch)->get()
        ]);
    }

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

        if (auth()->user()->role == "Sales Person" || auth()->user()->role == "Dispatch Manager" ) {
            abort(403, "NOT AUTHORIZED");
        }else {
            $user_details = User::findOrfail($user);
            if ($user_details->sales_person_category == "Delivery") {
                
                $deliveriesToday = \DB::table('invoices')
                ->where('user_id', $user_details->id)
                ->where('invoice_status', 1)
                ->where('invoice_category', "TRANSPORT")
                ->whereDate('created_at', $getDayClose->day_close)
                ->sum('invoice_total_price');
                
                // general
                 $sales_today_branch = \DB::table('invoices')
                 ->where('user_id', $user_details->id)
                 ->where('invoice_status', 1)
                 ->whereDate('created_at', $getDayClose->day_close)
                 ->get();
 
                 // general
                 $sales_today_branch_all = \DB::table('orders')
                 ->where('user_id', $user_details->id)
                 ->where('status', 1)
                 ->where('dispatch_status', 1)
                 ->whereDate('created_at', $getDayClose->day_close)
                 ->sum('total_cost_order');
                 
                 // On the House
                 $branch_total_house_sum = \DB::table('invoices')
                 ->where('user_id', $user_details->id)
                 ->where('invoice_status', 2)
                 ->whereDate('created_at', $getDayClose->day_close)
                 ->sum('invoice_total_price');
 
                 $branch_total_house_list = \DB::table('invoices')
                 ->where('user_id', $user_details->id)
                 ->where('invoice_status', 2)
                 ->whereDate('created_at', $getDayClose->day_close)
                 ->get();
 
                 // Rejected Orders
                 $branch_total_reject_sum = \DB::table('invoices')
                 ->where('user_id', $user_details->id)
                 ->where('invoice_status', 0)
                 ->whereDate('created_at', $getDayClose->day_close)
                 ->sum('invoice_total_price');
 
                 $branch_total_reject_list = \DB::table('invoices')
                 ->where('user_id', $user_details->id)
                 ->where('invoice_status', 0)
                 ->whereDate('created_at', $getDayClose->day_close)
                 ->get();
 
 
                 $orderDiscounted =  \DB::table('orders')
                 ->join('discounts', 'orders.id','discounts.order_number')
                 ->where('orders.user_id', $user_details->id)
                 ->whereDate('orders.created_at', $getDayClose->day_close)
                 ->get();
 
                 $discounts = \DB::table('discounts')
                     ->where('user_id', $user_details->id)
                     ->whereDate('created_at', $getDayClose->day_close)
                     ->sum('amount_deducted');
 
                 $orders = \DB::table('invoices')
                     ->where('user_id', $user_details->id)
                     ->where('invoice_status', 1)
                     ->whereDate('created_at', $getDayClose->day_close)
                     ->sum('invoice_total_price');
 
                 $deliveryfee = \DB::table('dispatches')
                     ->whereDate('created_at', $getDayClose->day_close)
                     ->where('dispatch_status', 1)
                     ->where('dispatch_branch', auth()->user()->branch)
                     ->sum('deliveryamount');
 
                 $order =  \DB::table('orders')
                     ->where('user_id', $user_details->id)
                     ->whereDate('created_at', $getDayClose->day_close)
                     ->get();
 
                $branch_total_general = $sales_today_branch_all-($discounts);
 
                return view('sales.view-user-sale', [
                 'sales_today_branch' => $sales_today_branch,
                 'user_data' => $user_details,
                 'branch_total_general' => $branch_total_general,
                 'branch_total_house_sum' => $branch_total_house_sum,
                 'branch_total_reject_sum' => $branch_total_reject_sum,
                 'branch_total_reject_list' => $branch_total_reject_list,
                 'branch_total_house_list' => $branch_total_house_list,
                 'order' => $order,
                 'orders' => $orders,
                 'discounts' => $discounts,
                 'deliveries'=> $deliveryfee,
                 'discounted_coupon' => $orderDiscounted,
                 'deliveriesToday' => $deliveriesToday
             ]);
            }elseif ($user_details->sales_person_category == "Counter") {
                // general
                $sales_today_branch = \DB::table('invoices')
                ->where('user_id', $user_details->id)
                ->where('invoice_status', 1)
                ->whereDate('created_at', $getDayClose->day_close)
                ->get();

                // general
                $sales_today_branch_all = \DB::table('invoices')
                ->where('user_id', $user_details->id)
                ->where('invoice_status', 1)
                ->whereDate('created_at', $getDayClose->day_close)
                ->sum('invoice_total_price');
                
                // On the House
                $branch_total_house_sum = \DB::table('invoices')
                ->where('user_id', $user_details->id)
                ->where('invoice_status', 2)
                ->whereDate('created_at', $getDayClose->day_close)
                ->sum('invoice_total_price');

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

                // Rejected Orders
                $branch_total_reject_sum = \DB::table('invoices')
                ->where('user_id', $user_details->id)
                ->where('invoice_status', 0)
                ->whereDate('created_at', $getDayClose->day_close)
                ->sum('invoice_total_price');

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


                $orderDiscounted =  \DB::table('orders')
                ->join('discounts', 'orders.id','discounts.order_number')
                ->where('orders.user_id', $user_details->id)
                ->whereDate('orders.created_at', $getDayClose->day_close)
                ->get();

                $discounts = \DB::table('discounts')
                    ->where('user_id', $user_details->id)
                    ->whereDate('created_at', $getDayClose->day_close)
                    ->sum('amount_deducted');

                $orders = \DB::table('invoices')
                    ->where('user_id', $user_details->id)
                    ->where('invoice_status', 1)
                    ->whereDate('created_at', $getDayClose->day_close)
                    ->sum('invoice_total_price');

                $deliveryfee = \DB::table('dispatches')
                    ->whereDate('created_at', $getDayClose->day_close)
                    ->where('dispatch_status', 1)
                    ->where('dispatch_branch', auth()->user()->branch)
                    ->sum('deliveryamount');

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

               $branch_total_general = $sales_today_branch_all-($discounts);

               return view('sales.view-user-sale', [
                'sales_today_branch' => $sales_today_branch,
                'user_data' => $user_details,
                'branch_total_general' => $branch_total_general,
                'branch_total_house_sum' => $branch_total_house_sum,
                'branch_total_reject_sum' => $branch_total_reject_sum,
                'branch_total_reject_list' => $branch_total_reject_list,
                'branch_total_house_list' => $branch_total_house_list,
                'order' => $order,
                'orders' => $orders,
                'discounts' => $discounts,
                'deliveries'=> $deliveryfee,
                'discounted_coupon' => $orderDiscounted
            ]);
            }
        }
    }





    public function salesReport()
    {   
        
        $this->authorize('create', App\Models\User::class);
         // general Sales

         if (auth()->user()->role == "Branch Officer") {
            $delivery = \DB::table('orders')
                ->where( 'created_at', '>', Carbon::now()->subDays(30))
                ->where('status', 1)
                ->where('dispatch_status', 1)
                ->where('category', "Delivery")
                ->where('branch', auth()->user()->branch)
                ->sum('total_cost_order');
        

                $counter = \DB::table('orders')
                ->where( 'created_at', '>', Carbon::now()->subDays(30))
                ->where('category', "Counter")
                ->where('branch', auth()->user()->branch)
                ->sum('total_cost_order');

                $deliveryfee = \DB::table('dispatches')
                    ->where( 'created_at', '>', Carbon::now()->subDays(30))
                    ->where('dispatch_status', 1)
                    ->where('dispatch_branch', auth()->user()->branch)
                    ->sum('deliveryamount');

                // Rejected Orders
                $general_total_reject = \DB::table('invoices')
                ->where('invoice_status', 0)
                ->where( 'created_at', '>', Carbon::now()->subDays(30))
                ->where('branch', auth()->user()->branch)
                ->sum('invoice_total_price');

                // On the House
                $general_total_house = \DB::table('invoices')
                ->where('invoice_status', 2)
                ->where( 'created_at', '>', Carbon::now()->subDays(30))
                ->where('branch', auth()->user()->branch)
                ->sum('invoice_total_price');

                $discounts = \DB::table('discounts')
                        ->where( 'created_at', '>', Carbon::now()->subDays(30))
                        ->where('branch', auth()->user()->branch)
                        ->sum('amount_deducted');

                $all_sales = ($delivery + $counter) - ($discounts+$general_total_reject+$general_total_house);

                $all_orders = \DB::table('orders')->where('branch', auth()->user()->branch)
                ->get();

                $all_product = \DB::table('final_productions')->get();

                $users = \DB::table('users')->where('branch', auth()->user()->branch)
                ->get();


                $branch = \DB::table('branches')->where('branch_name', auth()->user()->branch)->get();

                return view('sales.sales-head-report', [
                    'all_sales' => $all_sales,
                    'all_orders' => $all_orders->count(),
                    'all_product' => $all_product->count(),
                    'all_user_show' => $users,
                    'branches' => $branch
                ]);
        }

        $delivery = \DB::table('orders')
        ->where( 'created_at', '>', Carbon::now()->subDays(30))
        ->where('status', 1)
        ->where('dispatch_status', 1)
        ->where('category', "Delivery")
        ->sum('total_cost_order');
 

        $counter = \DB::table('orders')
        ->where( 'created_at', '>', Carbon::now()->subDays(30))
        ->where('category', "Counter")
        ->sum('total_cost_order');

        $deliveryfee = \DB::table('dispatches')
            ->where( 'created_at', '>', Carbon::now()->subDays(30))
            ->where('dispatch_status', 1)
            ->sum('deliveryamount');

        // Rejected Orders
        $general_total_reject = \DB::table('invoices')
        ->where('invoice_status', 0)
        ->where( 'created_at', '>', Carbon::now()->subDays(30))
        ->sum('invoice_total_price');

        // On the House
        $general_total_house = \DB::table('invoices')
        ->where('invoice_status', 2)
        ->where( 'created_at', '>', Carbon::now()->subDays(30))
        ->sum('invoice_total_price');

        $discounts = \DB::table('discounts')
                ->where( 'created_at', '>', Carbon::now()->subDays(30))
                ->sum('amount_deducted');

        $all_sales = ($delivery + $counter) - ($discounts+$general_total_reject+$general_total_house);

        $all_orders = \DB::table('orders')->get();

        $all_product = \DB::table('final_productions')->get();

        $users = \DB::table('users')
        ->get();


        $branch = \DB::table('branches')->get();

        return view('sales.sales-report', [
            'all_sales' => $all_sales,
            'all_orders' => $all_orders->count(),
            'all_product' => $all_product->count(),
            'all_user_show' => $users,
            'branches' => $branch
        ]);
    }



    public function showPrintDesign(Request $request,$inv)
    {     
        // invoice details
        $inv_details = Invoice::where('invoice_number', $inv)->first();
        // Search for Order In waiting Table
            $check_waiting = Waiting::where('order_id',$inv)->first();
            if ($check_waiting == null) {
                $useDiscount = Waiting::Create(
                    [   
                        'order_id' => $inv,
                        'waiting_number' => rand(100, 5000),
                        'branch' => $inv_details->branch ,
                        'category' => $inv_details  -> invoice_sales_person_category,
                        'status' => 0
                    ]);
                    $display_waiting = Waiting::where('order_id',$inv)->first();
            }else {
                $display_waiting = Waiting::where('order_id',$inv)->first();
            }

            if (auth()->user()->role == "Cashier") {
                $accept_payment = Invoice::where('invoice_number', $inv)->update([
                    'payment_status' => 1,
                    'payment_accepted_by' => auth()->id()
                ]);
        
                Order::where('order_id',$inv)->update([
                    'payment_status' => 1,
                    'payment_accepted_by' => auth()->id()
                ]);
            }
    

        $salesperson = Order::where('order_id', $inv)->first();
        $name = $salesperson->user->name;
        $branch = $salesperson->user->branch;
        $request->session()->forget([
            'cart','invoice_number', 'discount'
        ]);
        


        return view('print-invoice', [
            'invoice_generate' => \DB::table('invoices')->where('invoice_number', $inv)->get(),
            'number' => $inv,
            'total' => Invoice::where('invoice_number', $inv)->sum('invoice_total_price'),
            'branch_details' => \DB::table('branches')->where('branch_name',$salesperson->branch)->first(),
            'discount' => \DB::table('discounts')->where('order_id', $inv)->first(),
            'display_waiting' => $display_waiting->waiting_number,
            'sales_person_name' => $name,
            'sales_person_branch' => $branch,
            'time' => $salesperson -> created_at,
            'agency_' => Invoice::where('invoice_number', $inv)->first(),
        ]);
    }

    public function showPrintDesignDelivery(Request $request, $inv , $id)
    {   
        
        $salesperson = Order::where('order_id',$inv)->first();
        $name = $salesperson->user->name;
        $branch = $salesperson->user->branch;

        if (auth()->user()->role == "Cashier") {
            $accept_payment = Invoice::where('invoice_number', $inv)->update([
                'payment_status' => 1,
                'payment_accepted_by' => auth()->id()
            ]);
    
            Order::where('order_id',$inv)->update([
                'payment_status' => 1,
                'payment_accepted_by' => auth()->id()
            ]);
        }

        $request->session()->forget([
            'cart','invoice_number', 'discount'
        ]);

        return view('print-invoice-delivery', [
            'customer' => \DB::table('customers')->where('id', $id)->first(),
            'invoice_generate' => Invoice::where('invoice_number', $inv)->get(),
            'number' => $inv,
            'total' => Invoice::where('invoice_number', $inv)->sum('invoice_total_price'),
            'branch_details' => \DB::table('branches')->where('branch_name',$salesperson->branch)->first(),
            'discount' => \DB::table('discounts')->where('order_id', $inv)->first(),
            'sales_person_name' => $name,
            'sales_person_branch' => $branch,
            'time' => $salesperson -> created_at,
            'agency_' => Invoice::where('invoice_number', $inv)->first(),
        ]);
    }


    public function changeInvoiceStatus(Request $request)
    {   
        $item = Invoice::findOrfail($request->invoice_id);
        session()->put('rejectInvoice', $request->invoice_id);
        // check for Order and Remove discount
        $discount = Discount::where('order_id', $item->invoice_number)->first();
        if ($discount != null) {
            if ($request->status == "On The House" || $request->status == 2) {
                $item -> invoice_status = 2;
                Discount::where('order_id', $item->invoice_number)->delete();
            }elseif ($request->status == "Rejected" || $request->status == 0) {
                $item -> invoice_status = 0;
                Discount::where('order_id', $item->invoice_number)->delete();
            }elseif ($request->status == "General" || $request->status == 1) {
                $item -> invoice_status = 1;
            }
            $item -> comment = $request -> comment;
            $item->save();
            return $item -> invoice_status;
        }else {
            if ($request->status == "On The House" || $request->status == 2) {
                $item -> invoice_status = 2;
            }elseif ($request->status == "Rejected" || $request->status == 0) {
                $item -> invoice_status = 0;
            }elseif ($request->status == "General"  || $request->status == 1) {
                $item -> invoice_status = 1;
            }
            $item -> comment = $request -> comment;
            $item -> status_changed_by = auth()->id();
            $item -> status_change_date = \Carbon\carbon::now();
            $item->save();
            return $item -> invoice_status ;
        }
       
    }



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

        if (auth()->user()->role == "Administrator") {
            $transaction = \DB::table('orders')
            ->select('customers.customer_name','customers.customer_phone','orders.id','orders.order_id','orders.user_id','orders.branch', 'orders.created_at', 'orders.dispatch_status', 'orders.customer_id','orders.total_cost_order')
            ->join('customers','orders.customer_id','customers.id')
            ->where('orders.customer_id', '!=', null)
            ->where('orders.status', 0)
            ->whereDate('orders.created_at', $getDayClose->day_close)
            ->get();
        }else {
            $transaction = \DB::table('orders')
            ->select('customers.customer_name','customers.customer_phone','orders.id','orders.order_id','orders.user_id','orders.branch', 'orders.created_at', 'orders.dispatch_status', 'orders.customer_id','orders.total_cost_order')
            ->join('customers','orders.customer_id','customers.id')
            ->where('orders.customer_id', '!=', null)
            ->where('orders.status', 0)
            ->where('orders.user_id', auth()->id())
            ->whereDate('orders.created_at', $getDayClose->day_close)
            ->get();
        }

        return view('dispatch.transfer-order', [
            'transactions' => $transaction,
            'branch_list' => \DB::table('branches')->pluck('branch_name')
        ]);
    }



    // public function FromComposition($name)
    // {
    //     return view('composition-details', [
    //         'list' => \DB::table('invoices')->where('')
    //     ]);
    // }


    public function DeliveryAgency($agency)
    {
        $generateInvoice = $agency.substr(auth()->user()->branch, 0,3) . rand(5034580,10034580)+rand(5034580,10034580) . date("Yd") . date('Hi');
        session()->put('invoice_number', $generateInvoice);
        return view('inc.delivery-agency', [
            'agencys' => $agency
        ]);
    }


    public function make_transaction($id)
    {   
        
        $getDayClose = \DB::table('close_days')->first(); // getDay close
        $time = date('H:i:s'); // current time 

        if (empty(session()->get('invoice_number'))) {
            $generateInvoice = substr(auth()->user()->branch, 0,3) . rand(5034580,10034580)+rand(5034580,10034580) . date("Yd") . date('Hi');
            session()->put('invoice_number', $generateInvoice);
        }
    
        $transfer = session()->get('cart'); //transfer from Dump Invoice Table

        $totalCart = 0;
            if (!empty($transfer) || null) {
                foreach ($transfer as $item) {
                $result = (float)$item['invoice_quantity'] * (float)$item['invoice_unit_price'];
                $totalCart+=$result;
                }
            }

        if (empty($transfer) || null) {
            return back()->with('status', 'No Item Added to Cart');
        }else{

        // SUM ORDER
        $tatalCart = 0;
        foreach ($transfer as $inv) {
            $new_invoice = new Invoice;
            $new_invoice->user_id = auth()->id();
            $new_invoice->customer_id = $inv['customer_id'];
            $new_invoice->product_id = $inv['id'];
            $new_invoice->branch = auth()->user()->branch;
            $new_invoice->invoice_product_name = $inv['invoice_product_name'];
            if ($inv['invoice_status'] == "General" || $inv['invoice_status'] == 1) {
                $new_invoice->invoice_status = 1;
            }elseif ($inv['invoice_status'] == "On The House" || $inv['invoice_status'] == 2) {
                $new_invoice->invoice_status = 2;
            }else{
                $new_invoice->invoice_status = 0;
            }
            $new_invoice->invoice_sales_person_category = $inv['invoice_sales_person_category'];
            $new_invoice->invoice_quantity = $inv['invoice_quantity'];
            $new_invoice->invoice_unit_price = $inv['invoice_unit_price'];
            $new_invoice->invoice_total_price = $inv['invoice_total_price'];
            $new_invoice->invoice_number = session()->get('invoice_number');
            $new_invoice->agency =  $inv['agency'];
            $new_invoice->role_status =  auth()->user()->role == "Call Center" ? 1 : 0;
            $new_invoice->invoice_category = $inv['item_category'];
            $new_invoice->created_at = date('Y-m-d H:i:s', strtotime("$getDayClose->day_close $time"));
            $new_invoice->save();

            // RECORD ITEM TRANSACTION AS ORDER
            $checkOrder = \DB::table('orders')->where('order_id', session()->get('invoice_number'))->first();
            if (empty($checkOrder)  || null) {
                $order_ = new Order;
                $order_ -> order_id = session()->get('invoice_number');
                $order_ -> user_id = auth()->id();
                $order_ -> customer_id = $id;
                $order_ -> branch =  auth()->user()->branch;
                $order_ -> status = $id == null ? 1 : 0;
                if (!empty(session()->get('discount'))) {
                    if (session()->get('discount')['type'] == "Percentage") {
                        $order_ -> discount = $totalCart * session()->get('discount')['discount']/100;
                    }elseif (session()->get('discount')['type'] == "Cash") {
                        $order_ -> discount = $totalCart - session()->get('discount')['discount'];
                    }
                }else {
                    $order_ -> discount = 0;
                }
                $order_ -> category = auth()->user()->sales_person_category;
                $order_ -> total_cost_order = $totalCart;
                $order_ -> created_at = date('Y-m-d H:i:s', strtotime("$getDayClose->day_close $time"));
                $order_ ->save();
            }

           //    Discount
            if (!empty(session()->get('discount')) || NULL) {
                if (session()->get('discount')['type'] == "Percentage") {
                    $useDiscount = Discount::updateOrCreate(
                        ['order_id' => session()->get('invoice_number')],
                        [
                            'user_id' => auth()->user()->id,
                            'order_number' => $order_->id,
                            'type' => session()->get('discount')['type'],
                            'order_id' => session()->get('invoice_number'),
                            'discount' =>  session()->get('discount')['discount'],
                            'category' => auth()->user()->sales_person_category,
                            'branch' => auth()->user()->branch,
                            'amount_paid' => $totalCart * ((100 - session()->get('discount')['discount'])/100),
                            'amount_deducted' => $totalCart * session()->get('discount')['discount']/100,
                            'created_at'=> date('Y-m-d H:i:s', strtotime("$getDayClose->day_close $time"))
                        ]);
                }else {
                    $useDiscount = Discount::updateOrCreate(
                        ['order_id' => session()->get('invoice_number')],
                        [
                            'user_id' => auth()->user()->id,
                            'type' => session()->get('discount')['type'],
                            'order_id' => session()->get('invoice_number'),
                            'discount' =>  session()->get('discount')['discount'],
                            'category' => auth()->user()->sales_person_category,
                            'branch' => auth()->user()->branch,
                            'amount_paid' => $totalCart - session()->get('discount')['discount'],
                            'amount_deducted' => session()->get('discount')['discount'],
                            'created_at'=> date('Y-m-d H:i:s', strtotime("$getDayClose->day_close $time"))
                        ]);
                }
                
            }

            // Discount
            $discount = \DB::table('discounts')->where('order_id', session()->get('invoice_number'))->first();
            if (empty($discount)) {
                $discounted_amount = 0;
            }else {
                if ($discount->type == "Percentage") {
                    $discounted_amount = ($discount->discount)/100;
                }else {
                    $discounted_amount = (($discount->discount/($discount->amount_paid + $discount->amount_deducted))*100)/100;
                }
            }

            // $new_invoice->amount_deducted = (($inv['invoice_quantity'] * $inv['invoice_unit_price']) * (1-$discounted_amount));
            

            

            $app = \DB::table('settings')->first();

            if ($app->inventory_mgt ==  1) {
               // Getting Branch Code
                $branch_code = \DB::table('branches')->where('branch_name', auth()->user()->branch)->first();
                $saleliite = \DB::table('kitchens')->where('kitchen_code', $branch_code->branch_code)->first();

                // $materials = \DB::table('material_product_compositons')->where('product_id', $new_invoice->product_id)->get();

                // tax
                $taxes = \DB::table('taxes')->first();
                $generalTax = $taxes->covid+$taxes->nhil+$taxes->getfund;
                // Records for Cost of Salels
                CostOfSaleAnalysis::Insert([
                    'item_name' => $inv['invoice_product_name'],
                    'item_id' => $inv['id'],
                    'invoice_number' => session()->get('invoice_number'),
                    'branch' => auth()->user()->branch,
                    'user_id' => auth()->id(),
                    'category' => $inv['item_category'],
                    'quantity' => $inv['invoice_quantity'],
                    'gross_amount' => $inv['invoice_quantity'] * $inv['invoice_unit_price'],
                    'net_amount' => (($inv['invoice_quantity'] * $inv['invoice_unit_price'] * (1-$discounted_amount)))/ (1 + ($generalTax) + ($taxes->vat) + (($generalTax)*($taxes->vat))),
                    'cost' => \DB::table('material_product_compositons')->where('product_id', $inv['id'])->pluck('cost')->sum() * $inv['invoice_quantity'],
                    'adjusted_cost' => \DB::table('material_product_compositons')->where('product_id', $inv['id'])->pluck('adjusted_cost')->sum() * $inv['invoice_quantity'],
                    'date' => $getDayClose->day_close
            ]);

            $materials = \DB::table('material_product_compositons')->where('product_id', $inv['id'])->get();

        //     foreach ($materials as $key => $stock) {
        //     CompositionRecord::create([
        //         'user_id' => auth()->id(),
        //         'final_product_id' => $inv['id'],
        //         'comp_name' => $stock->product_name,
        //         'comp_id' =>  $stock-> composition_id,
        //         'unit_measure' =>  $stock->unit_measure,
        //         'comp_quantity' => $inv['invoice_quantity'] ,
        //         'unit_total' => $stock->unit_measure * $inv['invoice_quantity'],
        //         'branch' => auth()->user()->branch
        //     ]);  
        // }

         // Getting Branch Code
         $branch_code = \DB::table('branches')->where('branch_name', auth()->user()->branch)->first();
         $saleliite = \DB::table('kitchens')->where('kitchen_code', $branch_code->branch_code)->first();
 
 
         foreach ($materials as $key => $stock) {
 
             if ($stock == null) {
                 continue;
             }
            $existing = \DB::table('item_stock_ledgers')->where('item_id', $stock->composition_id)
            ->where('station', $saleliite->kitchen_name)
            ->where('date', $getDayClose->day_close)
            ->get();
            
             foreach ($existing as $key => $existing) {
 
             \DB::table('item_stock_ledgers')
                 ->where('item_id', $stock->composition_id)
                 ->where('station', $saleliite->kitchen_name)
                 ->where('date', $getDayClose->day_close)
                 ->update([
                     'item_sales' => $existing->item_sales + ($stock->unit_measure * $inv['invoice_quantity']),
                     'item_closing_stock' => ($existing->item_opening_stock +$existing->item_manufacturing + $existing->item_recieved + $existing->item_purchases)- ($existing->item_sales + $existing->item_issue + ($inv['invoice_quantity']*$stock->unit_measure)+ $existing->item_wastage + $existing->item_cons_manufacturing)
                 ]);
         }
 
       }

        $data = [
            'product_id' => $new_invoice->product_id,
            'branch' => auth()->user()->branch,
            'date' => $getDayClose->day_close,
            'invoice_number' => session()->get('invoice_number'),
            'quantity_sold' => $inv['invoice_quantity'],
            'data' => json_encode( \DB::table('material_product_compositons')->where('product_id', $new_invoice->product_id)->get() )
        ];
        BomReportOnSale::create($data); 
        }
       }   

    //  SEARCH ONLINE TRANSACTION TABLE
        $accept_transaction =  \DB::table('online_customers')->where('invoice_number', session()->get('invoice_number'))->first();
        if (!empty($accept_transaction)) {
            \DB::table('online_customers')->where('invoice_number', session()->get('invoice_number'))->update(
                ['order_state' => 1, 'accepted_by' => auth()->id()]);

                \DB::table('invoices')->where('invoice_number', session()->get('invoice_number'))->update([
                    'drive_thru_status' => 1
                ]);
        }

       if ($app->sales_target == 1) {
           
            $target_main = \DB::table('month_targets')->where('target_month', (int)date('m', strtotime("$getDayClose->day_close $time")))
            ->where('target_branch', auth()->user()->branch)
            ->first();
    
            $target = new TargetAnalysis;
            $target -> branch = auth()->user()->branch;
            $target -> total_cost = InvoiceDump::where('user_id', auth()->id())->where('invoice_category', '!=',  "TRANSPORT")->sum('invoice_total_price');
            $target -> actual_target = empty($target_main) || null ? 0 : $target_main->target_amount;
            $target -> daily_target = (empty($target_main) || null ? 0 : $target_main->target_amount)/(empty($target_main) || null ? 1 : $target_main->target_month_days);
            $target ->created_at = date('Y-m-d H:i:s', strtotime("$getDayClose->day_close $time"));
            $target->save();
       }
        

        }
         
        
    }

    

}
