<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\CustomerLedger;
use Illuminate\Http\Request;

class CustomerLedgerController extends Controller
{
    public function index()
    {
        $ledgers = CustomerLedger::with('customer')->latest()->paginate(15);

        return view('customer_ledgers.index', compact('ledgers'));
    }

    public function create()
    {
        $customers = Customer::active()->get();

        return view('customer_ledgers.create', compact('customers'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'customer_id' => ['required', 'exists:customers,id'],
            'transaction_date' => ['required', 'date'],
            'type' => ['required', 'in:credit,payment,adjustment'],
            'amount' => ['required', 'numeric', 'min:0'],
            'description' => ['nullable', 'string'],
        ]);

        $customer = Customer::findOrFail($data['customer_id']);
        $balance = $customer->current_due;

        if ($data['type'] === 'credit') {
            $balance += $data['amount'];
        } elseif ($data['type'] === 'payment') {
            $balance -= $data['amount'];
        }

        $customer->current_due = max(0, $balance);
        $customer->save();

        CustomerLedger::create([
            'customer_id' => $customer->id,
            'transaction_date' => $data['transaction_date'],
            'type' => $data['type'],
            'amount' => $data['amount'],
            'balance' => $customer->current_due,
            'description' => $data['description'] ?? null,
        ]);

        return redirect()->route('customer-ledgers.index')->with('success', __('Customer ledger entry added.'));
    }

    public function destroy(CustomerLedger $customerLedger)
    {
        $customerLedger->delete();

        return redirect()->route('customer-ledgers.index')->with('success', __('Ledger entry removed.'));
    }
}
