<?php

namespace App\Http\Controllers;

use App\Models\Accesories;
use App\Models\Stockin;  // Assuming you have a StockIn model
use App\Models\Stockindetails;
use App\Models\stockinsummary;
use App\Models\StockSummary;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

use App\Models\AccountTransaction;
use App\Models\Branch;
use App\Models\ChartOfAccount;
use App\Models\Supplier;
use Illuminate\Http\Request;

class StockInController extends Controller
{
    // List all stock-in entries
    public function index()
    {
        $title = 'Stock In List';
        $auth = Auth::user();

        $userRole = $auth->role_id;
        if ($userRole > 1) {
            $stockIn = Stockin::where('branch_id', $auth->branch_id)->OrderBy('id','desc')->get();
        } else {
            $stockIn = Stockin::OrderBy('id','desc')->get();
        }
        // Fetch all stock-in records
        return view('backend.pages.stockin.index', compact('stockIn', 'title'));  // Return the stock-in list view
    }
    public function getUnitByName($name)
    {
        // Fetch the accessory by name
        $accessory = Accesories::where('name', $name)->first();

        if ($accessory) {
            return response()->json([
                'unit' => $accessory->unit,
            ]);
        }

        return response()->json([
            'unit' => null,
        ]);
    }
    // Show the form to create a new stock-in entry
    public function create()
    {
        $accounts = ChartOfAccount::whereIn('id', [getAccountByUniqueID(6)->id])->get();
        $auth = Auth::user();

        $userRole = $auth->role_id;
       $ledgers = ChartOfAccount::where('parent_id', 16)->where('accountable_type','App\Models\Supplier')->get();
        $auth = Auth::user();

        $userRole = $auth->role_id;
        if ($userRole > 1) {

            $branchs = Branch::where("id", $auth->branch_id)->get();
        } else {

            $branchs = Branch::where("parent_id", 0)->get();
        }
        // dd($accounts);
        return view('backend.pages.stockin.create', get_defined_vars());  // Return the create form view
    }
    public function supplierDuePayment($accountId)
    {
    
      
       $due = supplierDue($accountId);
       

        return response()->json($due);
    }

    public function store(Request $request)
    {
        // dd($request->all());

        $request->validate([
            'ledger_id'  => 'required',
            'in_quantity.*'  => 'required|integer|min:1',
            'accessory_id.*' => 'required|exists:accesories,id',
            'price.*'        => 'nullable|numeric|min:0',
            'kg.*'           => 'nullable|numeric|min:0',
            'total_price.*'  => 'nullable|numeric|min:0',
        ]);
        $stock = new StockIn();
        $stock->date = today();
        $stock->ledger_id = $request->ledger_id;
        $stock->branch_id = $request->branch_id;
        $stock->delivery_cost = $request->delivery_cost;
        $stock->totalKg = $request->totalKg;
        $stock->ttlqty = $request->totalQty;
        $stock->ttlunitprice = $request->ttlunitprice;
        $stock->grandtotal = $request->grandtotal;
        $stock->grandsubTotaltotal = $request->grandsubTotaltotal;
        $stock->previouse_due_amount = $request->previouse_due_amount;
        $stock->labor_bill = $request->labor_bill;
        $stock->ngrandTotal = $request->ngrandTotal;
        $stock->advance_ledger_id = $request->advance_ledger_id;
        $stock->advance = $request->advance;
        $stock->finalDue = $request->finalDue;

        $charOfAccount = ChartOfAccount::where('id', $request->ledger_id)->first();
        // dd($charOfAccount);

        $supplier = Supplier::where('id', $charOfAccount->accountable_id)->first();
        $supplier->totalDue = $request->finalDue;
        $supplier->save();


        if ($request->voucher) {
            $logoname = $request->voucher->getClientOriginalName();
            $request->voucher->move(public_path() . '/backend/logo/', $logoname);
            $stock->voucher = $logoname;
        }

        $stock->save();
        $stockId = $stock->id;
        foreach ($request->input('in_quantity') as $key => $description) {
            $accessoryId = $request->input('accessory_id')[$key];
            $quantity    = $request->input('in_quantity')[$key];
            $price       = $request->input('price')[$key] ?? null;
            $kg          = $request->input('kg')[$key] ?? null;
            $totalPrice  = $request->input('total_price')[$key] ?? null;

            $stockIn = new Stockindetails();
            $stockIn->aceesories_id = $accessoryId;
            $stockIn->stock_ins_id  = $stock->id;
            $stockIn->in_quantity   = $quantity;
            $stockIn->description   = $description ?? "";
            $stockIn->price         = $price;
            $stockIn->kg            = $kg;
            $stockIn->total_price   = $totalPrice;
            $stockIn->save();


            $stockSummary = stockinsummary::where('product_id', $accessoryId)
                ->first();

            if ($stockSummary) {
                $stockSummary->quantity += $quantity;
                 $stockSummary->kg += $kg;
                $stockSummary->save();
            } else {
                $newStockSummary = new stockinsummary();
                $newStockSummary->product_id = $accessoryId;
                $newStockSummary->quantity = $quantity;
                $newStockSummary->kg = $kg;
                $newStockSummary->save();
            }
        }

       if ($request->ledger_id) {

    $invoice = AccountTransaction::accountInvoice();

    // 1️⃣ Debit Entry (Purchase)
    $transactionPay = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $stock->id,
        'account_id'      => getAccountByUniqueID(22)->id,  // Inventory / Purchase
        'type'            => 14,
        'debit'           => $request->ngrandTotal,
        'remark'          => $request->narration,
        'created_by'      => Auth::id(),
        'supplier_id'     => $request->supplier_id ?? 0,
        'created_at'      => now(),
    ];
    AccountTransaction::create($transactionPay);


    // 2️⃣ Credit Entry (Supplier Payable)
    $transaction = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $stock->id,
        'account_id'      => $request->ledger_id,
        'type'            => 14,
        'credit'          => $request->ngrandTotal,
        'remark'          => $request->narration,
        'created_by'      => Auth::id(),
        'supplier_id'     => $request->supplier_id ?? 0,
        'created_at'      => now(),
    ];
    AccountTransaction::create($transaction);
}




// ------------------------------
//  ADVANCE PAYMENT SECTION
// ------------------------------
if ($request->advance) {

    // 3️⃣ Debit Entry (Advance Paid TO Supplier)
    $transaction = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $stock->id,
        'account_id'      => $request->advance_ledger_id,  // Asset (Advance to supplier)
        'type'            => 14,
        'credit'           => $request->advance,
        'remark'          => "Advance Payment",
        'created_by'      => Auth::id(),
        'created_at'      => now(),
    ];
    AccountTransaction::create($transaction);


    // 4️⃣ Credit Entry (Cash/Bank Paid)
    $transaction = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $stock->id,
        'account_id'      => $request->ledger_id,  // Cash/Bank
        'type'            => 14,
        'debit'          => $request->advance,
        'remark'          => "Advance Payment",
        'created_by'      => Auth::id(),
        'created_at'      => now(),
    ];
    AccountTransaction::create($transaction);
}

        return redirect()->route('stockin.list')->with('success', 'Stock-in created successfully.');
    }


    // Show the details of a specific stock-in entry
    public function show($id)
    {
        $accounts = ChartOfAccount::whereIn('id', [getAccountByUniqueID(6)->id])->get();

       
        $auth = Auth::user();

        $userRole = $auth->role_id;
       $ledgers = ChartOfAccount::whereIn('id', [getAccountByUniqueID(16)->id])->get();
        $auth = Auth::user();

        $userRole = $auth->role_id;
        if ($userRole > 1) {

            $branchs = Branch::where("id", $auth->branch_id)->get();
        } else {

            $branchs = Branch::where("parent_id", 0)->get();
        }
        $stockIn = StockIn::findOrFail($id);  // Find the stock-in record by ID
        return view('backend.pages.stockin.show', compact('stockIn', 'accounts'));  // Return the show view
    }

    // Show the form to edit a specific stock-in entry
    public function edit($id)
    {
        $accounts = ChartOfAccount::whereIn('id', [getAccountByUniqueID(6)->id])->get();
        $auth = Auth::user();

        $userRole = $auth->role_id;
      
        $ledgers = ChartOfAccount::whereIn('id', [getAccountByUniqueID(16)->id])->get();
        $auth = Auth::user();

        $userRole = $auth->role_id;
        if ($userRole > 1) {

            $branchs = Branch::where("id", $auth->branch_id)->get();
        } else {

            $branchs = Branch::where("parent_id", 0)->get();
        }
        $stockIn = StockIn::findOrFail($id);  // Find the stock-in record by ID
        return view('backend.pages.stockin.edit', get_defined_vars());  // Return the edit form view
    }



    public function update(Request $request, $id)
    {
        // dd($request->all());
        $stockIn = StockIn::findOrFail($id);
        $stockIn->totalKg = $request->totalKg;
        $stockIn->ttlqty = $request->totalQty;
        $stockIn->ttlunitprice = $request->ttlunitprice;
        $stockIn->grandtotal = $request->grandtotal;
        $stockIn->grandsubTotaltotal = $request->grandsubTotaltotal;
        $stockIn->previouse_due_amount = $request->previouse_due_amount;
        $stockIn->labor_bill = $request->labor_bill;
        $stockIn->ngrandTotal = $request->ngrandTotal;
        $stockIn->advance_ledger_id = $request->advance_ledger_id;
        $stockIn->advance = $request->advance;
        $stockIn->finalDue = $request->finalDue;

        $charOfAccount = ChartOfAccount::where('id', $request->ledger_id)->first();

        $supplier = Supplier::where('id', $charOfAccount->accountable_id)->first();
        $supplier->totalDue = $request->finalDue;
        $supplier->save();
        
        $stockIn->save();
        $tableId = $stockIn->id;
        $existingDetailIds = $request->detail_id ?? []; // Array of submitted detail IDs

   
        Stockindetails::where('stock_ins_id', $stockIn->id)
            // ->whereNotIn('id', $existingDetailIds)
            ->delete();

        foreach ($request->accessory_id as $key => $accessoryId) {
            $description   = $request->description[$key] ?? "";
            $in_quantity   = $request->in_quantity[$key] ?? "";
            $old_quantity  = $request->old_quantity[$key] ?? 0;
            $price         = $request->price[$key] ?? null;
            $kg            = $request->kg[$key] ?? null;
            $total_price   = $request->total_price[$key] ?? null;


            // Check if this detail already exists

            $detail = new Stockindetails();
            $detail->stock_ins_id   = $stockIn->id;
            $detail->aceesories_id  = $accessoryId;
            $detail->description    = $description;
            $detail->in_quantity    = $in_quantity;
            $detail->price          = $price;
            $detail->kg             = $kg;
            $detail->total_price    = $total_price;


            $newStockSummary = new stockinsummary();
            $newStockSummary->product_id = $accessoryId;
            $newStockSummary->quantity = $in_quantity;
            $newStockSummary->kg = $kg;
            $newStockSummary->save();

            $detail->save();

        

        }

         if ($request->ledger_id) {
      $account = AccountTransaction::where('table_id', $tableId)->where('type', 14)->delete();

    $invoice = AccountTransaction::accountInvoice();

    // 1️⃣ Debit Entry (Purchase)
    $transactionPay = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $tableId,
        'account_id'      => getAccountByUniqueID(22)->id,  // Inventory / Purchase
        'type'            => 14,
        'debit'           => $request->ngrandTotal,
        'remark'          => $request->narration,
        'created_by'      => Auth::id(),
        'supplier_id'     => $request->supplier_id ?? 0,
        'created_at'      => now(),
    ];
    AccountTransaction::create($transactionPay);


    // 2️⃣ Credit Entry (Supplier Payable)
    $transaction = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $tableId,
        'account_id'      => $request->ledger_id,
        'type'            => 14,
        'credit'          => $request->ngrandTotal,
        'remark'          => $request->narration,
        'created_by'      => Auth::id(),
        'supplier_id'     => $request->supplier_id ?? 0,
        'created_at'      => now(),
    ];
    AccountTransaction::create($transaction);
}




// ------------------------------
//  ADVANCE PAYMENT SECTION
// ------------------------------
if ($request->advance) {

    // 3️⃣ Debit Entry (Advance Paid TO Supplier)
    $transaction = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $tableId ,
        'account_id'      => $request->advance_ledger_id,  // Asset (Advance to supplier)
        'type'            => 14,
        'credit'           => $request->advance,
        'remark'          => "Advance Payment",
        'created_by'      => Auth::id(),
        'created_at'      => now(),
    ];
    AccountTransaction::create($transaction);


    // 4️⃣ Credit Entry (Cash/Bank Paid)
    $transaction = [
        'payment_invoice' => $invoice,
        'invoice'         => $invoice,
        'branch_id'       => $request->branch_id ?? 0,
        'table_id'        => $tableId ,
        'account_id'      => $request->ledger_id,  // Cash/Bank
        'type'            => 14,
        'debit'          => $request->advance,
        'remark'          => "Advance Payment",
        'created_by'      => Auth::id(),
        'created_at'      => now(),
    ];
    AccountTransaction::create($transaction);
}


        return redirect()->route('stockin.list')->with('success', 'Stock-in details updated successfully.');
    }


    // Delete a specific stock-in entry
    public function delete($id)
    {
        $stockIn = Stockin::findOrFail($id);  
        $stockIn->delete();  

        return redirect()->route('stockin.list')->with('success', 'Stock-in deleted successfully.');  // Redirect with success message
    }

    // Optionally, a report or other action related to stock-in can be added
    public function report()
    {
        // Logic for generating a stock-in report
        return view('backend.pages.stockin.report');  // Return a report view
    }
}
