<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Item;
use App\Models\ItemCategory;
use App\Models\Payment;
use App\Models\StockIn;
use App\Models\Purchase;
use App\Models\Supplier;
use App\Models\PurchaseItem;
use App\Models\SerialNumber;
use App\Models\Banking;
use App\Models\BankTransfar;
use App\Models\Expense;
use App\Models\ExpenseHead;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;


class PurchaseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function stock()
    {
        //$list = StockIn::groupBy('item_id')->get();

        // $list = StockIn::with('item.category','item.serialNumbers')->orderBy('id','DESC')->groupBy('item_id')->paginate('100');

        $list = Item::with('category','stockIn','stockOut','itemReturn','itemAdjustment')->get();

        $grandTotal = 0;
        foreach ($list as $item) {
            $grandTotal += $item->stockIn->sum('quantity') - $item->stockOut->sum('quantity') + $item->itemReturn->sum('qty') - $item->itemAdjustment->sum('quantity');
        }

        return view('purchase.stock',[
            'page_title' => 'Stock List',
            'list' => $list,
            'url' => route('purchase.create'),
            'add_button' => 'true',
            'class' => 'btn btn-primary',
            'value' => 'Add New Purchase',
            'grandTotal' => $grandTotal
             ]);


        //new
        // $data=[

        //     'list'=> Item::with('category','stockIn','stockOut','itemReturn','itemAdjustment')->get(),
        // ];

        // return view('purchase.stock',$data);
    }
    public function index()
    {
        $list = Purchase::get();
        return view('purchase.index',[
            'page_title' => 'Purchase List',
            'list' => $list,
            'url' => route('purchase.create'),
            'add_button' => 'true',
            'class' => 'btn btn-primary',
            'value' => 'Add New Purchase'
             ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        return view('purchase.create',[
            'suppliers' => Supplier::all(),
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'bank_accounts' => Banking::where('status', 1)->get(),
            'page_title'=> 'Add New Purchase'
        ]);

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //  dd($request->all());
         $request->validate([
            'products' => 'array|required',
            'supplier_id' => 'required',
            'voucher_no' => 'required',
            'payment_method' => 'required',
            'remark' => 'nullable',
        ]);

        // Validate cheque fields if payment method is Cheque
        if ($request->payment_method == "Cheque") {
            $request->validate([
                'cheque_number' => 'required',
                'bank_account_id' => 'nullable',
                'account_number' => 'required',
                'branch_name' => 'required',
                'bank_name' => 'required',
            ]);
        }

        DB::beginTransaction();
        try{


        $purchase = new Purchase();
        $purchase->invoice_number = "INV-" . \App\Classes\InvoiceNumber::serial_number();
        $purchase->remark = $request->remark;
        $purchase->supplier_id = $request->supplier_id;
        $purchase->branch_id = $request->branch_id;
        $purchase->subtotal = $request->subtotal;
        $purchase->paid = $request->paid;
        $purchase->payment_method = $request->payment_method;
        $purchase->voucher_no = $request->voucher_no;
        $purchase->due = $request->due;
        $purchase->creator_user_id = Auth::id();
        $purchase->save();
        $products = $request->get('products');

        foreach ($products as $key => $product) {
            $item = new PurchaseItem();
            $item->purchase_id = $purchase->id;
            $item->item_id = $product['item_id'];
            $item->quantity = $product['quantity'];
            $item->buying_price = $product['price'];
            $item->save();

        }

        // Handle cheque payment - only save payment information, expense and withdrawal will be created on approval
        if ($request->payment_method == "Cheque") {
            // Save payment information
            Payment::create([
                "purchase_id" => $purchase->id,
                "amount" => $request->paid,
                "cheque_number" => $request->cheque_number,
                "account_number" => $request->account_number,
                "branch_name" => $request->branch_name,
                "bank_name" => $request->bank_name,
                "bank_account_id" => !empty($request->bank_account_id) ? $request->bank_account_id : null,
            ]);
        }

        foreach ($products as $key => $product) {
            $stock = new StockIn();
            $stock->purchase_id =  $purchase->id;
            $stock->item_id = $product['item_id'];
            $stock->quantity = $product['quantity'];
            $stock->save();

        }

        DB::commit();
        Toastr::success("Purchase Added Successfully");
        return back();
    }catch (\Exception $ex)
    {
        DB::rollback();
        Toastr::error("Some Problem Happened");
        return back();
    }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function show(Purchase $purchase)
    {
        return view('purchase.show',[
            'purchase' => $purchase,
            'page_title'=> 'Purchase Details'
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data=[
            'purchase'=> Purchase::with('items.item.category','items.item.unit','payment_new')->find($id),
            'suppliers' => Supplier::all(),
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'bank_accounts' => Banking::where('status', 1)->get(),
        ];
        // dd($data);
        return view('purchase.edit',$data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Purchase $purchase)
    {
        // dd($request->all());
        DB::beginTransaction();
        try{

            if($request->payment_method_id=="Cheque"){

                 if($request->cheque_number==null || $request->account_number==null ||  $request->brance_number==null || $request->bank_name==null)
                 {
                    Toastr::error("Please Add All Cheque Information");
                    return back();
                 }
            }

            $serialNumbers=SerialNumber::where('purchase_id',$request->id)->where('status',"used")->first();
            if($serialNumbers){
                Toastr::info("Allready Use Serial Number Of this Purhase");
                return back();
            }
            if($request->productId==null){

                Toastr::info("Please Add Atleast One Item");
                return back();
            }


            $purchase = Purchase::find($request->id);

            $privious_paymentMethod= $purchase->payment_method;

            $purchase->remark = $request->remark;
            $purchase->supplier_id = $request->supplier_id;
            $purchase->branch_id = $request->branch_id;
            $purchase->subtotal = $request->payable;
            $purchase->paid = $request->paid;
            $purchase->payment_method = $request->payment_method_id;
            $purchase->voucher_no = $request->voucher_no;
            $purchase->due = $request->due;
            $purchase->updator_user_id  = Auth::id();
            $purchase->save();
            PurchaseItem::where('purchase_id',$request->id)->delete();

            $len= sizeof($request->productId);

            for($i=0;$i<$len;$i++) {
                $item = new PurchaseItem();
                $item->purchase_id = $purchase->id;
                $item->item_id = $request->productId[$i];
                $item->quantity = $request->quantity[$i];
                $item->buying_price =$request->price[$i];
                $item->save();

            }

            StockIn::where('purchase_id',$request->id)->delete();
            for($i=0;$i<$len;$i++) {
                $stock = new StockIn();
                $stock->purchase_id =  $purchase->id;
                $stock->item_id = $request->productId[$i];
                $stock->quantity =$request->quantity[$i];
                $stock->save();

            }

            Payment::where('purchase_id',$request->id)->delete();
            SerialNumber::where('purchase_id',$request->id)->delete();

            // Handle cheque payment - only save payment information, expense and withdrawal will be created on approval
            if ($request->payment_method_id == "Cheque") {
                // Save payment information
                Payment::create([
                    "purchase_id" => $purchase->id,
                    "amount" => $request->paid,
                    "cheque_number" => $request->cheque_number,
                    "account_number" => $request->account_number,
                    "branch_name" => $request->brance_number,
                    "bank_name" => $request->bank_name,
                    "bank_account_id" => !empty($request->bank_account_id) ? $request->bank_account_id : null,
                ]);
            } else {
                // If payment method changed from Cheque to Cash, delete existing expense and bank withdrawal if purchase was already approved
                // Only delete if purchase is already approved (has expense)
                if ($purchase->approve_status == "yes") {
                    $expense = Expense::where('invoice_number', $purchase->invoice_number)->first();
                    if ($expense) {
                        $expense->delete();
                    }

                    $existingWithdrawal = BankTransfar::where('description', 'like', '%Purchase [ID:' . $purchase->id . ']%')
                        ->whereNotNull('withdraw_amount')
                        ->first();
                    if ($existingWithdrawal) {
                        $existingWithdrawal->delete();
                    }
                }
            }

            // dd('comes');
            DB::commit();
            Toastr::success("Purchase Update Successfull");
            return redirect()->route('purchase.index');
        }catch (\Exception $e){
            DB::rollBack();
            Toastr::error("Some Problem happen");
            return back();
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Purchase  $purchase
     * @return \Illuminate\Http\Response
     */
    public function destroy(Purchase $purchase)
    {
        //
    }


    public function getItemBySearchKeyword($keyword)
    {

        $items = Item::where('name', 'LIKE', $keyword . '%')
            ->orWhere('code', 'LIKE', $keyword . '%')
            ->get();

        return response()->json($items);

    }
    public function getItemByCategoryId($category_id)
    {

        $items = Item::where('category_id', $category_id)
            ->get();

        return response()->json($items);

    }
    public function getItemById($id)
    {

        $item = Item::with('unit', 'category')->where('id', $id)
            ->first();
        return response()->json($item);

    }

    public function serialNoAdd($purchase_id)
    {
        // dd('comes');
        $data=[
            'items'=>Purchase::with('items.itemWithSerialNumber')->find($purchase_id),
            'url'=>"serial-no-add/{$purchase_id}",
        ];
        //  dd($data);
        return view('purchase.serial_no_add',$data);
    }

    public function showSerialNo($id)
    {
        // dd('comess');
        $data=[
            'serial_no'=>SerialNumber::where('item_id',$id)->where('status','notused')->paginate('100'),
        ];
        return view('purchase.show_serial_no',$data);
    }

    public function addItemCard(Request $request)
    {
        $data= [
            'item'=> Item::with('category','unit')->find($request->id),
        ];
        return $data;
    }

    public function getBankAccountById($id)
    {
        $bankAccount = Banking::where('id', $id)->first();
        if ($bankAccount) {
            return response()->json([
                'account_no' => $bankAccount->account_no,
                'bank_name' => $bankAccount->bank_name,
                'branch_name' => $bankAccount->branch_name,
            ]);
        }
        return response()->json(['error' => 'Bank account not found'], 404);
    }
}
