<?php

namespace App\Http\Controllers;

use App\Models\Item;
use App\Models\ItemCategory;
use App\Models\Purchase;
use App\Models\Vendor;
use App\Models\VendorLedger;
use Illuminate\Http\Request;

class PurchaseController extends Controller
{
    public function index()
    {
        $purchases = Purchase::with(['vendor', 'item'])->latest()->paginate(15);

        return view('purchases.index', compact('purchases'));
    }

    public function create()
    {
        $vendors    = Vendor::active()->orderBy('name')->get();
        $categories = ItemCategory::orderBy('name')->get();
        $items      = Item::orderBy('name')->get(['id', 'name', 'category', 'unit']);
        $nextInvoice = 'PO-' . str_pad((Purchase::max('id') ?? 0) + 1, 5, '0', STR_PAD_LEFT);

        return view('purchases.create', compact('vendors', 'categories', 'items', 'nextInvoice'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'vendor_id'     => ['nullable', 'exists:vendors,id'],
            'item_id'       => ['nullable', 'exists:items,id'],
            'item_category' => ['nullable', 'string', 'max:100'],
            'invoice_no'    => ['nullable', 'string', 'max:50'],
            'purchase_date' => ['required', 'date'],
            'quantity'      => ['nullable', 'numeric', 'min:0'],
            'cost'          => ['required', 'numeric', 'min:0'],
            'payment_type'  => ['required', 'in:cash,due'],
            'notes'         => ['nullable', 'string'],
        ]);

        // item_type is a legacy enum; always set to 'other' as item_category holds the actual category
        $data['item_type'] = 'other';

        if (empty($data['invoice_no'])) {
            $data['invoice_no'] = 'PO-' . str_pad((Purchase::max('id') ?? 0) + 1, 5, '0', STR_PAD_LEFT);
        }

        $purchase = Purchase::create($data);

        // If purchased on credit (due), record in vendor ledger
        if ($data['payment_type'] === 'due' && ! empty($data['vendor_id'])) {
            $vendor  = Vendor::findOrFail($data['vendor_id']);
            $balance = $vendor->current_due + $data['cost'];

            VendorLedger::create([
                'vendor_id'        => $vendor->id,
                'transaction_date' => $data['purchase_date'],
                'type'             => 'debit',
                'amount'           => $data['cost'],
                'balance'          => $balance,
                'description'      => __('Purchase #:id', ['id' => $purchase->id]),
            ]);

            $vendor->update(['current_due' => $balance]);
        }

        return redirect()->route('purchases.index')->with('success', __('Purchase recorded successfully.'));
    }

    public function destroy(Purchase $purchase)
    {
        $purchase->delete();

        return redirect()->route('purchases.index')->with('success', __('Purchase removed successfully.'));
    }
}
