<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PurchaseStock;
use App\Models\PurchaseInvoice;
use App\Models\FaultStock;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;


class StockController extends Controller
{
 public function create()
    {
        return view('purchase');
    }

    public function store(Request $request)
    {
        Log::info("request".$request);
        $request->validate([
            'invoice_number' => 'required',
            'incoming_date'  => 'required|date',
            'company_name'   => 'required',
            'courier_charge' => 'required|numeric'
        ]);

        $items = $request->item_name;
        $products_total = 0;

        foreach ($items as $i => $item) {
            $qty = max(0, (int) $request->qty[$i]);
            $rate = max(0, (float) $request->rate[$i]);
            $gst  = (float) $request->gst[$i];
            $fault = (int) ($request->fault_count[$i] ?? 0);
            $remarks = $request->fault_remarks[$i] ?? null;

            if ($fault > $qty) $fault = $qty;

            $total = ($qty * $rate) + $gst;
            $products_total += $total;

            // ✅ Insert purchase stock
            PurchaseStock::create([
                'invoice_number' => $request->invoice_number,
                'incoming_date'  => $request->incoming_date,
                'courier_name'   => $request->courier_name,
                'company_name'   => $request->company_name,
                'item_name'      => $item,
                'particular_name'=> $request->particular_name[$i],
                'specification'  => $request->specification[$i],
                'model_number'   => $request->model_number[$i],
                'qty'            => $qty,
                'rate'           => $rate,
                'gst'            => $gst,
                'total'          => $total,
                'fault_count'    => $fault > 0 ? $fault : null
            ]);

            // ✅ If fault exists, save to fault_stock
            if ($fault > 0) {
                FaultStock::create([
                    'fault_date'      => $request->incoming_date,
                    'given_to'        => 'Nilatech('.auth()->user()->name.')',
                    'item_name'       => $item,
                    'qty'             => $fault,
                    'remarks'         => $remarks,
                    'particular_name' => $request->particular_name[$i],
                    'specification'   => $request->specification[$i],
                    'model_number'    => $request->model_number[$i],
                    'company_name'    => $request->company_name,
                ]);
            }
        }

        // ✅ Insert Invoice
        $invoice_total = $products_total + $request->courier_charge;
        PurchaseInvoice::create([
            'invoice_number' => $request->invoice_number,
            'incoming_date'  => $request->incoming_date,
            'courier_name'   => $request->courier_name,
            'company_name'   => $request->company_name,
            'courier_charge' => $request->courier_charge,
            'total_amount'   => $invoice_total
        ]);

        return redirect()->route('inventory')->with('success', 'Stock saved successfully!');
    }

     public function edit($id)
    {
        $product = PurchaseStock::findOrFail($id);

        // fault remarks
        $faultRemark = FaultStock::where('purchase_stock_id', $id)->value('remarks') ?? '';

        // available qty = purchase - outward - fault
        $outwardQty = $product->outwardStocks()->sum('qty');
        $faultQty   = $product->faultStocks()->sum('qty');
        $available  = $product->qty - $outwardQty - $faultQty;

        return view('edit_product', compact('product', 'faultRemark', 'available'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'invoice_number' => 'required',
            'incoming_date'  => 'required|date',
            'company_name'   => 'required',
            'item_name'      => 'required',
            'qty'            => 'required|numeric|min:0',
            'rate'           => 'required|numeric|min:0',
            'gst'            => 'nullable|numeric|min:0',
            'fault_count'    => 'nullable|numeric|min:0',
        ]);

        $product = PurchaseStock::findOrFail($id);

        $outwardQty = $product->outwardStocks()->sum('qty');
        $faultQtyExisting = $product->faultStocks()->sum('qty');

        $faultCount = $request->fault_count ?? 0;
        $availableCheck = $request->qty - $outwardQty - $faultCount;

        if ($availableCheck < 0) {
            return back()->with('error', '⚠️ Fault quantity cannot exceed available stock ('.($request->qty - $outwardQty).')');
        }

        DB::transaction(function () use ($request, $product, $faultCount) {
            $total = ($request->qty * $request->rate) + $request->gst;

            $product->update([
                'invoice_number' => $request->invoice_number,
                'incoming_date'  => $request->incoming_date,
                'courier_name'   => $request->courier_name,
                'company_name'   => $request->company_name,
                'item_name'      => $request->item_name,
                'particular_name'=> $request->particular_name,
                'specification'  => $request->specification,
                'model_number'   => $request->model_number,
                'qty'            => $request->qty,
                'rate'           => $request->rate,
                'gst'            => $request->gst,
                'total'          => $total,
                'fault_count'    => $faultCount ?: null
            ]);

            if ($faultCount > 0) {
                FaultStock::updateOrCreate(
                    [
                        'purchase_stock_id' => $product->id,
                        'company_name'      => $request->company_name,
                        'given_to'          => 'Nilatech',
                    ],
                    [
                        'item_name'      => $request->item_name,
                        'particular_name'=> $request->particular_name,
                        'specification'  => $request->specification,
                        'model_number'   => $request->model_number,
                        'qty'            => $faultCount,
                        'remarks'        => $request->remarks,
                        'fault_date'     => now(),
                    ]
                );
            } else {
                FaultStock::where('purchase_stock_id', $product->id)
                          ->where('company_name', $request->company_name)
                          ->where('given_to', 'Nilatech')
                          ->delete();
            }
        });

        return redirect()->route('inventory', $product->id)->with('success', 'Product updated successfully!');
    }


    public function delete($id){

      $product = PurchaseStock::findOrFail($id);
        $product->delete();

        
        return redirect()->route('inventory', $product->id)->with('success', 'Product deleted successfully!');
    }
}
