<?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,
    AccountQuote,
    AccountQuoteItem
};
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Exports\QuotationExport;
use Maatwebsite\Excel\Facades\Excel;
use Validator;

class QuotesController 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 = "quotation.xlsx";
        return Excel::download(new QuotationExport($this->admin_id),$filename);
        
    }

     // Display all employees
     public function index()
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'account';
        $data['superadminSubMenu'] = 'quotes';
        $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 = AccountQuote::where('account_quotes.admin_id',$this->admin_id)
        ->leftJoin("account_customers","account_customers.id","=","account_quotes.customer_id");
        
        

        if($search)
        {
            $query->where('account_quotes.quotation_number', 'LIKE', '%' . $search . '%');
            
        }
        if($quotes_date)
        {
            $query->whereDate('account_quotes.quotation_date', $quotes_date);
            
        }
        if($po_number)
        {
            $query->where('account_quotes.po_number', $po_number);
            
        }
        
        if($start_date && $end_date)
        {
            $query->whereDate('account_quotes.created_at','>=', $start_date);
            $query->whereDate('account_quotes.created_at','<=', $end_date);
            
        }

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

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

        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'account';
        $data['superadminSubMenu'] = 'quotes';

        
        $quotation_number = 1;
        
        $res = AccountQuote::latest()->select("quotation_number")->first();

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

        $data["quotation_number"] = $quotation_number;

        $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.quotes.add',$data);
     }
 
     
     // Store a new product in the database
     public function storeQuotes(Request $request)
     {
       
        $this->allData = $request->all();       
       
        //return $this->allData;
        $this->validate = Validator::make($request->all(),[
            "customer_id"=>"required",
            "quotation_number"=>"required",
            "quotation_date"=>"required",
            "valid_date"=>"required",
            "po_number"=>"required"
            
        ]);

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

        if(isset($request->quotes_id) && !empty($request->quotes_id))
        {
            unset($this->allData["quotes_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 = AccountQuote::where("id",$request->quotes_id)->update($this->allData);

            if($this->res)
            {
                AccountQuoteItem::where("quotes_id",$request->quotes_id)->delete();
                if (isset($request->item_id) && is_array($request->item_id)) 
                {
                    foreach ($request->item_id as $i=>$id) {
                        AccountQuoteItem::create([
                            'admin_id' => $this->admin_id,
                            'quotes_id' => $request->quotes_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","Quotes 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 = AccountQuote::create($this->allData);

        if($this->res)
        {
            AccountQuoteItem::where("quotes_id",$request->quotes_id)->delete();
                if (isset($request->item_id) && is_array($request->item_id)) 
                {
                    foreach ($request->item_id as $i=>$id) {
                        AccountQuoteItem::create([
                            'admin_id' => $this->admin_id,
                            'quotes_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","Quotes generate successfully !");
        }
        return back()->with("success","failed !");
      
        
     }
 
     // Show the form to edit an existing product
     public function editQuotes($id)
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'account';
        $data['superadminSubMenu'] = 'quotes';

        $data['invoice'] = AccountQuote::where("id",$id)->first(); 
        
        $data['invoice_items'] = AccountQuoteItem::where("quotes_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.quotes.edit',$data); 
     }
 
     
     
     // Delete a product
     public function deleteQuotes(Request $request)
     {
        //return $request->id;

         $this->res = AccountQuote::where('id',$request->id)->delete();
         if($this->res)
         {
            AccountQuoteItem::where('quotes_id',$request->id)->delete();

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

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

           $logMessage = $request->rolename . ' Invoice 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);
     }
     

     

}
