<?php

namespace App\Http\Controllers;

use App\Models\InvoiceDump;
use Illuminate\Http\Request;
use App\Models\OnlineCustomer;
use Session;

class InvoiceDumpController extends Controller
{


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

    public function store(Request $request)
    {   
        $this->validate($request, [
            'invoice_quantity' => ['required']
        ]);
        // get name of Item from ID
        $item = \DB::table('final_productions')->where('FinalProductionID', $request -> invoice_product_name)->first();
        
        // validate the cost
        $new_item = $item->UnitPrice;
        $total = $item->UnitPrice*$request -> invoice_quantity;
        $agency_tota1 = round((1.1 * $item->UnitPrice)) * $request -> invoice_quantity;
        $id = $request -> invoice_product_name;
        // End Validate
          
        $cart = $request->session()->get('cart', []);
        if(isset($cart[$id])) {
            $cart[$id]['invoice_quantity'] = $cart[$id]['invoice_quantity'] + $request -> invoice_quantity;
            $cart[$id]['invoice_total_price'] = $cart[$id]['invoice_quantity']*$cart[$id]['invoice_unit_price'];
        } else {
            $cart[$id] = [
                'id' => $id,
                'user_id' => auth()->user()->id,
                "branch" => auth()->user()->branch,
                "customer_id" => empty($request -> customer_id) ? 1 : $request -> customer_id,
                "invoice_product_name" => $item -> Name,
                "invoice_status" => $request -> status,
                "invoice_sales_person_category" => auth()->user()->sales_person_category,
                "invoice_quantity"=>$request -> invoice_quantity,
                "invoice_unit_price" =>!empty($request ->agency) ?  round((1.1 * $item->UnitPrice)) : $item->UnitPrice,
                "agency"=> $request ->agency,
                "invoice_total_price"=> !empty($request ->agency) ? $agency_tota1 : $total,
                "item_category"=> $item->production_category,
                ];
        }
          
        $request->session()->put('cart', $cart);
        return response([
            'status'=> 1000,
            'Message'=> 'Item Added Successfully'
        ]);

    }


    public function storeCall(Request $request)
    {   
        $this->validate($request, [
            'invoice_quantity' => ['required']
        ]);
        // get name of Item from ID
        $item = \DB::table('final_productions')->where('FinalProductionID', $request -> invoice_product_name)->first();
        
        // validate the cost
        $new_item = $item->UnitPrice;
        $total = $item->UnitPrice*$request -> invoice_quantity;
        $agency_tota1 = round((1.1 * $item->UnitPrice)) * $request -> invoice_quantity;
        $id = $request -> invoice_product_name;
        // End Validate
          
        $cart = $request->session()->get('cart', []);
        $cartcall = $request->session()->get('cartcall', []);
        if(isset($cart[$id])) {
            $cart[$id]['invoice_quantity'] = $cart[$id]['invoice_quantity'] + $request -> invoice_quantity;
            $cart[$id]['invoice_total_price'] = $cart[$id]['invoice_quantity']*$cart[$id]['invoice_unit_price'];
        } else {
            $cart[$id] = [
                'id' => $id,
                'user_id' => auth()->user()->id,
                "branch" => auth()->user()->branch,
                "customer_id" => empty($request -> customer_id) ? 1 : $request -> customer_id,
                "invoice_product_name" => $item -> Name,
                "invoice_status" => $request -> status,
                "invoice_sales_person_category" => auth()->user()->sales_person_category,
                "invoice_quantity"=> $request -> invoice_quantity,
                "invoice_unit_price" =>!empty($request ->agency) ?  round((1.1 * $item->UnitPrice)) : $item->UnitPrice,
                "agency"=> $request ->agency,
                "invoice_total_price"=> !empty($request ->agency) ? $agency_tota1 : $total,
                "item_category"=> $item->production_category,
                ];


                $cartcall[] = [
                    'quantity'=> $request -> invoice_quantity,
                    'product_code' => $item -> product_code
                ];
                
        }


        
          
        $request->session()->put('cart', $cart);
        $request->session()->put('cartcall', $cartcall);
        return response([
            'status'=> 1000,
            'Message'=> 'Item Added Successfully at CallCenter'
        ]);

    }

    public function barcodeAddCart(Request $request, $barcode)
    {
         // get name of Item from ID
         $item = \DB::table('final_productions')->where('barcode', 'like', '%' . $barcode . '%')
         ->orWhere('product_code', 'like', '%' . $barcode . '%')
         ->first();

         if (empty($item)) {
             return "empty";
         }
        
         // validate the cost
         $new_item = (float)$item->UnitPrice;
         $total = $item->UnitPrice*1;
         $agency_tota1 = round((1.1 * $item->UnitPrice)) * 1;
         $id = $item->FinalProductionID;
         // End Validate
           
         $cart = $request->session()->get('cart', []);
         if(isset($cart[$id])) {
             $cart[$id]['invoice_quantity']++;
             $cart[$id]['invoice_total_price'] = ($cart[$id]['invoice_quantity'])*$cart[$id]['invoice_unit_price'];
         } else {
             $cart[$id] = [
                 'id' => $id,
                 'user_id' => auth()->user()->id,
                 "branch" => auth()->user()->branch,
                 "customer_id" =>  empty($request -> customer_id) ? 1 :$request -> customer_id,
                 "invoice_product_name" => $item -> Name,
                 "invoice_status" => 1,
                 "invoice_sales_person_category" => auth()->user()->sales_person_category,
                 "invoice_quantity"=> 1,
                 "invoice_unit_price" =>!empty($request ->agency) ?  round((1.1 * $item->UnitPrice)) : $item->UnitPrice,
                 "agency"=> $request ->agency,
                 "invoice_total_price"=> !empty($request ->agency) ? (float)$agency_tota1 : (float)$total,
                 "item_category"=> $item->production_category,
                 ];
         }
           
         $request->session()->put('cart', $cart);
         return response([
            'status'=> 1000,
            'Message'=> 'Item Added Successfully'
        ]);
    }


    public function IncreaseCart(Request $request, $id, $quantity)
    {

    // $product = \DB::table('final_productions')->where('FinalProductionID', $id)->first();
    // When Add to cart is clicked
    // Get appropriate values and set
    $cart = $request->session()->get('cart', []);
    if(isset($cart[$id])) {
        $cart[$id]['invoice_quantity']++;
        $cart[$id]['invoice_total_price'] = $cart[$id]['invoice_quantity']*$cart[$id]['invoice_unit_price'];
    }

    $request->session()->put('cart', $cart);

        return response([
            'status' => 200,
            'message' => "success"
            ]);


    }


    public function DecreaseCart(Request $request, $id, $quantity)
    {
    
    if ($quantity <= 0) {
        abort(419, "Quantity cannot be less than 1");
    }
    // When Add to cart is clicked
    // Get appropriate values and set
    $cart = $request->session()->get('cart', []);
    if(isset($cart[$id])) {
        if ($cart[$id]['invoice_quantity'] <= 1) {
            abort(419, "Quantity cannot be less than 1");
        }
        $cart[$id]['invoice_quantity'] =  $cart[$id]['invoice_quantity']-1;
        $cart[$id]['invoice_total_price'] = $cart[$id]['invoice_quantity']*$cart[$id]['invoice_unit_price'];
    }

    $request->session()->put('cart', $cart);

        return response([
            'status' => 200,
            'message' => "success"
            ]);


    }


    public function locationPrice(Request $request)
    {
        // get name of location from ID
        $item = \DB::table('dispatch_items')->where('id',$request -> location_name)->first();
        $id = $item->id;

        $cart = $request->session()->get('cart', []);
        if(isset($cart[$id])) {
            abort(419, "Cannot be Incremented");
        } else {
            $cart[$id] = [
                    'id' => $id,
                    'user_id' => auth()->user()->id,
                    "branch" => auth()->user()->branch,
                    "customer_id" => $request -> id,
                    "invoice_product_name" => $item -> location_name,
                    "invoice_status" => "General",
                    "invoice_sales_person_category" => auth()->user()->sales_person_category,
                    "invoice_quantity"=> 1,
                    "invoice_unit_price" => $item -> location_price,
                    "agency"=> $request ->agency,
                    "invoice_total_price"=> $item -> location_price,
                    "item_category"=> "TRANSPORT",
                ];
        }
          
        $request->session()->put('cart', $cart);
        return response([
            'status'=> 1000,
            'Message'=> 'Item Added Successfully'
        ]);
    }

    public function destroy(Request $request)
    {   
        $request->session()->forget([
            'cart','invoice_number', 'discount','customer_name','customer_address','customer_contact', 'cartcall'
        ]);
        return back();
    }


    public function InvoiceDumpDestroy($id)
    {   
        $cart = session()->get('cart');
        unset($cart[$id]);
        session()->put('cart', $cart);
        return response([
            'status' => 200,
            'Message' => "Successfully Removed from Cart"
        ]);
    }


    public function PlaceOrderCallCenter(Request $request)
    {
        if (empty($request->session()->get('customer_name')) || empty($request->session()->get('customer_contact')) || empty($request->session()->get('cart'))) {
            return back()->with('statuspass', "Oops! something went wrong, Kindly check customer details.. cannot be empty");
        }

        $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);
        }

        $data = new onlineCustomer;
        $data -> customer_fname = $request->session()->get('customer_name');
        $data -> customer_lname = null;
        $data -> delivery_location = $request->session()->get('customer_address');
        $data -> customer_eamil = null;
        $data -> customer_phone = $request->session()->get('customer_contact');
        $data -> order_branch = auth()->user()->branch;
        $data -> date = $getDayClose->day_close;
        $data -> comment = $request->session()->get('customer_note');
        $data -> discount_code = null;
        $data -> agency = "CAL2022202047";
        $data ->agency_trans_number = session()->get('invoice_number');
        $data -> invoice_number = session()->get('invoice_number');
        $data -> agency_orders = json_encode(session()->get('cartcall'));
        $data -> save();


        $request->session()->forget([
            'cart','invoice_number', 'discount','customer_name','customer_address','customer_contact','customer_note','cartcall'
        ]);

        return back()->with('status', 'Order placed successfully');

    }
}
