<?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,
    AccountDebitNote,
    AccountDebitNoteItem,
    AccountInvoice,
    AccountPurchaseBill,
    AccountExpense,
    AccountExpenseDetail,
    AccountExpenseDetailItem
};
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Exports\ExpenseDetailExport;
use Maatwebsite\Excel\Facades\Excel;
use Validator;

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

     // Display all employees
     public function index()
     {
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'expense';
        $data['superadminSubMenu'] = 'expense';

        $search = isset($_GET["search"]) ? $_GET["search"] : null;
        $date = isset($_GET["date"]) ? $_GET["date"] : null;
        $vendor_name = isset($_GET["vendor_name"]) ? $_GET["vendor_name"] : null;
        
        
        $start_date = isset($_GET["start_date"]) ? $_GET["start_date"] : null;
        $end_date = isset($_GET["end_date"]) ? $_GET["end_date"] : null;
       
       
        $query = AccountExpenseDetail::where('account_expense_details.admin_id',$this->admin_id)
        ->leftJoin("account_customers as customer","customer.id","=","account_expense_details.customer_id")
        ->leftJoin("account_customers as vendor","vendor.id","=","account_expense_details.vendor_id");
                

        if($search)
        {
            $query->where('account_expense_details.expense_number', 'LIKE', '%' . $search . '%');
            
        }
        if($date)
        {
            $query->whereDate('account_expense_details.date', $date);
            
        }
        if($vendor_name)
        {
            $query->where('vendor.name','LIKE', '%'.$vendor_name.'%');
            
        }
        
        if($start_date && $end_date)
        {
            $query->whereDate('account_expense_details.created_at','>=', $start_date);
            $query->whereDate('account_expense_details.created_at','<=', $end_date);
            
        }

        

        $data['expenses'] = $query->select(
            "account_expense_details.*",
            "customer.name as customer_name",
            "vendor.name as vendor_name"
        )->orderBy('account_expense_details.created_at','desc')->paginate(10);
       

        return view('accounting.expenses.list',$data);
     }
 
     // Show the form to create a new product
     public function create()
     {
       
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'expense';
        $data['superadminSubMenu'] = 'expense';

        
        $expense_number = 1;
        
        $res = AccountExpenseDetail::latest()->select("expense_number")->first();

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

        $data["expense_number"] = $expense_number;

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


        $data['clients'] = AccountCustomer::where("admin_id",$this->admin_id)->where("type","debitor")->get();

        return view('accounting.expenses.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(),[
            "vendor_id"=>"required",
            "expense_number"=>"required",
            "date"=>"required",
            "payment_method"=>"required"
            
        ]);

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

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

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

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

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

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

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

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

        if($this->res)
        {
             
                if (isset($request->item_id) && is_array($request->item_id)) 
                {
                    foreach ($request->item_id as $i=>$id) {
                        AccountExpenseDetailItem::create([
                            'admin_id' => $this->admin_id,
                            'expense_id' => $this->res->id,
                            'item_id' => $id,
                            'unit_id' => $request->unit_id[$i] ?? null,
                            'item_quantity' => $request->item_quantity[$i] ?? null,
                            'item_price' => $request->item_price[$i] ?? null,
                            'item_igst' => $request->item_igst[$i] ?? null,
                            'item_total' => $request->item_total[$i] ?? null
                        ]);
                    }
                }
                
            return back()->with("success","Expense details store successfully !");
        }
        return back()->with("success","failed !");
      
        
     }
 
     // Show the form to edit an existing product
     public function edit($id)
     {        
        
        $data['pagetitle'] = "account";
        $data['mainSuperAdminMenu'] = 'expense';
        $data['superadminSubMenu'] = 'expense';

        $data['invoice'] = AccountExpenseDetail::where("id",$id)->first();
        $data['invoice_items'] = AccountExpenseDetailItem::where("expense_id",$id)->get();
        $data['categories'] = AccountItemCategory::where("admin_id",$this->admin_id)->get();
        $data['units'] = AccountItemUnit::where("admin_id",$this->admin_id)->get();
        $data['items'] = AccountExpense::where("admin_id",$this->admin_id)->get();
        $data['vendors'] = AccountCustomer::where("admin_id",$this->admin_id)->where("type","creditor")->get();
        $data["taxes"] = DB::table("account_tax_slabs")->get();


        $data['clients'] = AccountCustomer::where("admin_id",$this->admin_id)->where("type","debitor")->get();

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

         $this->res = AccountExpenseDetail::where('id',$request->id)->delete();
         if($this->res)
         {
            AccountExpenseDetailItem::where('expense_id',$request->id)->delete();

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

     public function deleteMultiple(Request $request)
     {
        
        $this->res = AccountExpenseDetail::whereIn('id',$request->ids)->delete();
        if($this->res)
        {
            AccountExpenseDetailItem::whereIn('expense_id',$request->ids)->delete();

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

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

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

     
     // expenses account

     public function addAccountExpense(Request $request)
     {
        
        $this->allData = $request->all();       
       
        $this->allData;
        $this->validate = Validator::make($request->all(),[
            "name"=>"required",
            "type"=>"required"
            
        ]);

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

        if(isset($request->expense_id) && !empty($request->expense_id))
        {
            unset($this->allData["expense_id"]);
            unset($this->allData["_token"]);

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

            if($this->res)
            {

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

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


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

        if($this->res)
        {
            
            return back()->with("success","Expense created successfully !");
        }
        return back()->with("success","failed !");
     }
     

     

}
