<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use Illuminate\Http\Request;
use Carbon\carbon;

class BranchController extends Controller
{   

    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $this->authorize('viewAny' , Branch::class);
        
        return view('branch', [
            'branches' => Branch::all()
        ]);
    }


    public function branchSale(Request $request)
    {   
        $this->validate(request(), [
            'branch' => 'required'
        ]);
        $getDayClose = \DB::table('close_days')->first();
        
        $branch = $request->branch;
        if (auth()->user()->role == "Sales Person" || auth()->user()->role == "Dispatch Manager") {
            abort(403, 'Unauthorized action.');  
        }else{
        $sales_today_branch = \DB::table('invoices')
        ->where('branch', $branch)
        ->where('invoice_status', 1)
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();

            
        $total_cash = \DB::table('invoices')
            ->where('branch', $branch)
            ->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_branch', $branch)
            ->where('dispatch_status', 1)
            ->sum('deliveryamount');

        $rejected = \DB::table('invoices')
        ->where('invoice_status', 0)
        ->whereDate('created_at', $getDayClose->day_close)
        ->where('branch', $branch)
        ->sum('invoice_total_price');

        $onthehouse = \DB::table('invoices')
        ->where('invoice_status', 2)
        ->where('branch', $branch)
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_total_price');

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

        // general Sales
        $branch_total_general = $total_cash-($discounts);
        
        // On the House
        $branch_total_house = \DB::table('invoices')
        ->where('branch', $branch)
        ->where('invoice_status', 2)
        ->whereDate('created_at', $getDayClose->day_close)
        ->sum('invoice_total_price');

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

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

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

        $ordersfromBranch = \DB::table('orders')
        ->where('branch', $branch)
        ->whereDate('created_at', $getDayClose->day_close)
        ->get();

         $ordersfromBranchcost = \DB::table('invoices')
         ->where('branch', $branch)
         ->where('invoice_status', 1)
         ->whereDate('created_at', $getDayClose->day_close)
         ->sum('invoice_total_price');


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


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

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


        return view('sales.view-branch-sales', [
            'sales_today_branch' => $sales_today_branch,
            'branch' => $branch,
            'branch_total_general' => $branch_total_general,
            'branch_total_house' => $branch_total_house,
            'branch_total_reject' => $branch_total_reject,
            'branch_total_reject_list' => $branch_total_reject_list,
            'branch_total_house_list' => $branch_total_house_list,
            'ordersfromBranch' => $ordersfromBranch,
            'discounted_coupon' => $orderDiscounted,
            'discounts' => $discounts,
            'orders' => $ordersfromBranchcost,
            'deliveries'=> $deliveriesToday 

        ]);
    }
    }
   
    public function store(Request $request)
    {   
        $this->authorize('create' , Branch::class);
        $this->validate($request, [
            'branch_name' => ['required', 'string', 'max:255'],
            'branch_location' => ['required', 'string', 'max:255'],
            'branch_contact' => ['required', 'string', 'max:255'],
        ]);
        $app = \DB::table('settings')->first();
        $branch = new Branch;
        if($file = $request->hasFile('image')) {
            $file = $request->file('image') ;
            $fileName = $file->getClientOriginalName() ;
            $destinationPath = 'uploads/' ;
            $file->move($destinationPath,$fileName);
            $branch-> branch_image = ''.$fileName ;
         }

        
        $branch->user_id = auth()->user()->id;
        $branch->branch_name = $request->branch_name;
        $branch->branch_location = $request->branch_location;
        $branch->branch_contact = $request->branch_contact;
        $branch->branch_code = $request->branch_code;
        $branch->branch_momo = $request->branch_momo;
        $branch->tingg_delivery = $request->tingg_delivery;
        $branch->tingg_counter = $request->tingg_counter;
        $branch->tin_number = !empty($app->app_tin) ? $app->app_tin : "";
        $branch->store_type = empty($request->store_type) ? 0 : 1;
        $branch->save();
        return back()->with('status', 'Branch Saved SUccessfully');

    }

    
    public function edit(Branch $branch)
    {   
        $this->authorize('viewAny' , Branch::class);

        return view('edit-branch', [
            'branching' => $branch,
            'branches' => Branch::all()
        ]);
    }

   
    public function update(Request $request, Branch $branch)
    {   
        $app = \DB::table('settings')->first();
        if($file = $request->hasFile('image')) {
            $file = $request->file('image') ;
            $fileName = $file->getClientOriginalName() ;
            $destinationPath = 'uploads/' ;
            $file->move($destinationPath,$fileName);
            $branch -> branch_image = ''.$fileName ;
         }

        $branch->branch_name = $request->branch_name;
        $branch->branch_location = $request->branch_location;
        $branch->branch_contact = $request->branch_contact;
        $branch->branch_code = $request->branch_code;
        $branch->branch_momo = $request->branch_momo;
        $branch->tingg_delivery = $request->tingg_delivery;
        $branch->tingg_counter = $request->tingg_counter;
        $branch->store_type = empty($request->store_type) ? 0 : 1;
        $branch->tin_number = !empty($app->app_tin) ? $app->app_tin : "";
        $branch->save();
        return back()->with('status', 'Branch information updated Successfully');
    }

  
    public function destroy(Branch $branch)
    {
        $branch->delete();
        return 123;
    }
}
