<?php
namespace App\Http\Controllers\Admin\accounting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\LogActivity;
use App\Models\{
    User,
    Role,
    School,
    Plan
};
use App\Models\accounting\{
    AccountLedger,
    AccountLedgerGroup,
    AccountBank,
    AccountItem,
    AccountItemUnit,
    AccountItemCategory,
    AccountCustomer,
    AccountDeliveryChallan,
    AccountDeliveryChallanItem
};
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Exports\DeliveryChallanExport;
use Maatwebsite\Excel\Facades\Excel;
use Validator;

class DeliveryChallanController extends Controller
{
    protected $admin_id;
    protected $school_id, $res,$allData,$data,$validate;
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            // fetch session and use it in entire class with constructor
            if (session()->get('loggedIn')['user_type'] == 'admin') {
                $this->admin_id = session()->get('loggedIn')['id'];
                $this->school_id = School::where("admin_id",$this->admin_id)->pluck("id")->first();
            } else {
                $this->admin_id = session()->get('loggedIn')['admin_id'];
                $this->school_id = School::where("admin_id",$this->admin_id)->pluck("id")->first();
            }
         
            return $next($request);
        });
    }

    public function export()
    {        
        $filename = "delivery_challan.xlsx";
        return Excel::download(new DeliveryChallanExport($this->admin_id),$filename);
        
    }

     // Display all employees
     public function index()
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'account';
        $data['superadminSubMenu'] = 'delivery-challan';
        $search = isset($_GET["search"]) ? $_GET["search"] : null;
        $quotes_date = isset($_GET["quotation_date"]) ? $_GET["quotation_date"] : null;
        $po_number = isset($_GET["po_number"]) ? $_GET["po_number"] : null;
        
        
        $start_date = isset($_GET["start_date"]) ? $_GET["start_date"] : null;
        $end_date = isset($_GET["end_date"]) ? $_GET["end_date"] : null;
       
       
        $query = AccountDeliveryChallan::where('account_delivery_challans.admin_id',$this->admin_id)
        ->leftJoin("account_customers","account_customers.id","=","account_delivery_challans.customer_id");
        
        

        if($search)
        {
            $query->where('account_delivery_challans.challan_number', 'LIKE', '%' . $search . '%');
            
        }
        if($quotes_date)
        {
            $query->whereDate('accaccount_delivery_challans.ount_quotes.challan_date', $quotes_date);
            
        }
        if($po_number)
        {
            $query->where('account_delivery_challans.po_number', $po_number);
            
        }
        
        if($start_date && $end_date)
        {
            $query->whereDate('account_delivery_challans.created_at','>=', $start_date);
            $query->whereDate('account_delivery_challans.created_at','<=', $end_date);
            
        }

       
        $data['challans'] = $query->select(
            "account_delivery_challans.*",
            "account_customers.name as customer_name"
        )->orderBy('account_delivery_challans.created_at','desc')->paginate(10);
       

        return view('accounting.delivery_challan.list',$data);
     }
 
     // Show the form to create a new product
     public function create()
     {
       

        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'delivery-challan';
        $data['superadminSubMenu'] = 'delivery-challan';

        
        $challan_no = 1;
        
        $res = AccountDeliveryChallan::latest()->select("challan_number")->first();

        if($res)
        {
            $challan_no = $res->challan_number + 1;
            
        }
        

        $data["challan_number"] = $challan_no;

        $data['categories'] = AccountItemCategory::where("admin_id",$this->admin_id)->get();
        $data['units'] = AccountItemUnit::where("admin_id",$this->admin_id)->get();
        $data['items'] = AccountItem::where("admin_id",$this->admin_id)->get();
        $data['customers'] = AccountCustomer::where("admin_id",$this->admin_id)->where("type","debitor")->get();
        $data["taxes"] = DB::table("account_tax_slabs")->get();
             

        return view('accounting.delivery_challan.add',$data);
     }
 
     
     // Store a new product in the database
     public function store(Request $request)
     {
       
        $this->allData = $request->all();       
       
        //return $this->allData;
        $this->validate = Validator::make($request->all(),[
            "customer_id"=>"required",
            "challan_number"=>"required",
            "challan_date"=>"required",
            "shipping_date"=>"required",
            "po_number"=>"required"
            
        ]);

        if($this->validate->fails())
        {
            return back()->withErrors($this->validate)->withInput();
        }

        if(isset($request->challan_id) && !empty($request->challan_id))
        {
            unset($this->allData["challan_id"]);
            unset($this->allData["_token"]);
            unset($this->allData["item_id"]);
            unset($this->allData["item_quantity"]);
            unset($this->allData["item_price"]);
            unset($this->allData["item_discount"]);
            unset($this->allData["item_cgst"]);
            unset($this->allData["item_sgst"]);
            unset($this->allData["item_igst"]);
            unset($this->allData["item_total"]);

            $this->res = AccountDeliveryChallan::where("id",$request->challan_id)->update($this->allData);

            if($this->res)
            {
                AccountDeliveryChallanItem::where("challan_id",$request->challan_id)->delete();
                if (isset($request->item_id) && is_array($request->item_id)) 
                {
                    foreach ($request->item_id as $i=>$id) {
                        AccountDeliveryChallanItem::create([
                            'admin_id' => $this->admin_id,
                            'challan_id' => $request->challan_id,
                            'item_id' => $id,
                            'item_quantity' => $request->item_quantity[$i] ?? null,
                            'item_price' => $request->item_price[$i] ?? null,
                            'item_discount' => $request->item_discount[$i] ?? null,
                            'item_cgst' => $request->item_cgst[$i] ?? null,
                            'item_sgst' => $request->item_sgst[$i] ?? null,
                            'item_igst' => $request->item_igst[$i] ?? null,
                            'item_total' => $request->item_total[$i] ?? null
                        ]);
                    }
                }

                return back()->with("success","Delivery Challan update successfully !");
            }
            return back()->with("error","failed !");
        }

        $this->allData["admin_id"] = $this->admin_id;

        unset($this->allData["item_id"]);
        unset($this->allData["item_quantity"]);
        unset($this->allData["item_price"]);
        unset($this->allData["item_discount"]);
        unset($this->allData["item_cgst"]);
        unset($this->allData["item_sgst"]);
        unset($this->allData["item_igst"]);
        unset($this->allData["item_total"]);

        $this->res = AccountDeliveryChallan::create($this->allData);

        if($this->res)
        {
            
                if (isset($request->item_id) && is_array($request->item_id)) 
                {
                    foreach ($request->item_id as $i=>$id) {
                        AccountDeliveryChallanItem::create([
                            'admin_id' => $this->admin_id,
                            'challan_id' => $this->res->id,
                            'item_id' => $id,
                            'item_quantity' => $request->item_quantity[$i] ?? null,
                            'item_price' => $request->item_price[$i] ?? null,
                            'item_discount' => $request->item_discount[$i] ?? null,
                            'item_cgst' => $request->item_cgst[$i] ?? null,
                            'item_sgst' => $request->item_sgst[$i] ?? null,
                            'item_igst' => $request->item_igst[$i] ?? null,
                            'item_total' => $request->item_total[$i] ?? null
                        ]);
                    }
                }
            return back()->with("success","Delivery Challan generate successfully !");
        }
        return back()->with("success","failed !");
      
        
     }
 
     // Show the form to edit an existing product
     public function edit($id)
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'delivery-challan';
        $data['superadminSubMenu'] = 'delivery-challan';

        $data['invoice'] = AccountDeliveryChallan::where("id",$id)->first(); 
        
        $data['invoice_items'] = AccountDeliveryChallanItem::where("challan_id",$id)->get();
        $data['customers'] = AccountCustomer::where("admin_id",$this->admin_id)->where("type","debitor")->get();
        $data['categories'] = AccountItemCategory::where("admin_id",$this->admin_id)->get();
        $data['units'] = AccountItemUnit::where("admin_id",$this->admin_id)->get();
        $data['items'] = AccountItem::where("admin_id",$this->admin_id)->get();
        $data["taxes"] = DB::table("account_tax_slabs")->get();

        return view('accounting.delivery_challan.edit',$data); 
     }
 
     
     
     // Delete a product
     public function delete(Request $request)
     {
        //return $request->id;

         $this->res = AccountDeliveryChallan::where('id',$request->id)->delete();
         if($this->res)
         {
            AccountDeliveryChallanItem::where('challan_id',$request->id)->delete();

            $logMessage = $request->rolename . ' Challan delete successfully!';
			    LogActivity::addToLog($logMessage);
                
            
            return response()->json(["message"=>"success"],200);
         }
         
            return response()->json(["message"=>"failed"],424);
         
     }

     public function deleteMultiple(Request $request)
     {
        
        $this->res = AccountDeliveryChallan::whereIn('id',$request->ids)->delete();
        if($this->res)
        {
            AccountDeliveryChallanItem::whereIn('quotes_id',$request->ids)->delete();

           $logMessage = $request->rolename . ' challan delete successfully!';
               LogActivity::addToLog($logMessage);
               
           
           return response()->json(["message"=>"success"],200);
        }
        
           return response()->json(["message"=>"failed"],424);
     }

     public function statusChange(Request $request)
     {
        $this->res = AccountQuote::where("id",$request->id)->update(["status"=>$request->status]);

        if($this->res)
        {
            return response()->json(["message"=>"success"],200);
        }
        return response()->json(["message"=>"failed"],424);
     }
     

     

}
