<?php

namespace App\Http\Controllers;

use App\Models\Vendor;
use App\Models\VendorLedger;
use Illuminate\Http\Request;

class VendorController extends Controller
{
    public function index()
    {
        $vendors = Vendor::orderBy('name')->paginate(15);

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

    public function create()
    {
        return view('vendors.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'    => ['required', 'string', 'max:255'],
            'phone'   => ['nullable', 'string', 'max:50'],
            'address' => ['nullable', 'string', 'max:500'],
        ]);

        Vendor::create($data);

        return redirect()->route('vendors.index')->with('success', __('Vendor added successfully.'));
    }

    public function edit(Vendor $vendor)
    {
        return view('vendors.edit', compact('vendor'));
    }

    public function update(Request $request, Vendor $vendor)
    {
        $data = $request->validate([
            'name'      => ['required', 'string', 'max:255'],
            'phone'     => ['nullable', 'string', 'max:50'],
            'address'   => ['nullable', 'string', 'max:500'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $data['is_active'] = $request->boolean('is_active', true);
        $vendor->update($data);

        return redirect()->route('vendors.index')->with('success', __('Vendor updated successfully.'));
    }

    public function destroy(Vendor $vendor)
    {
        $vendor->delete();

        return redirect()->route('vendors.index')->with('success', __('Vendor deleted.'));
    }

    // ─── Vendor Ledger ────────────────────────────────────────────────────────

    public function ledger(Vendor $vendor)
    {
        $ledgers = $vendor->ledgers()->latest('transaction_date')->paginate(20);

        return view('vendors.ledger', compact('vendor', 'ledgers'));
    }

    public function ledgerStore(Request $request, Vendor $vendor)
    {
        $data = $request->validate([
            'transaction_date' => ['required', 'date'],
            'type'             => ['required', 'in:debit,payment'],
            'amount'           => ['required', 'numeric', 'min:0.01'],
            'description'      => ['nullable', 'string', 'max:500'],
        ]);

        $balance = $vendor->current_due;
        if ($data['type'] === 'debit') {
            $balance += $data['amount'];
        } else {
            $balance = max(0, $balance - $data['amount']);
        }

        VendorLedger::create([
            'vendor_id'        => $vendor->id,
            'transaction_date' => $data['transaction_date'],
            'type'             => $data['type'],
            'amount'           => $data['amount'],
            'balance'          => $balance,
            'description'      => $data['description'] ?? null,
        ]);

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

        return redirect()->route('vendors.ledger', $vendor)->with('success', __('Ledger entry saved.'));
    }

    public function ledgerDestroy(Vendor $vendor, VendorLedger $vendorLedger)
    {
        // Reverse the balance effect
        $balance = $vendor->current_due;
        if ($vendorLedger->type === 'debit') {
            $balance = max(0, $balance - $vendorLedger->amount);
        } else {
            $balance += $vendorLedger->amount;
        }

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

        return redirect()->route('vendors.ledger', $vendor)->with('success', __('Ledger entry deleted.'));
    }
}
