<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\ConveyanceBill;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ConveyanceBillController extends Controller
{
    public function index(): View
    {
        $expenses = ConveyanceBill::latest('id')->paginate(25);
        return view('admin.expenses.index', compact('expenses'));
    }

    public function create(): View
    {
        return view('admin.expenses.form', ['branches' => Branch::orderBy('name')->get()]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'bill_date' => ['required', 'date'],
            'branch_id' => ['nullable','integer'],
            'employee_name' => ['nullable', 'string', 'max:120'],
            'purpose' => ['required', 'string', 'max:255'],
            'amount' => ['required', 'numeric', 'min:0'],
            'note' => ['nullable', 'string'],
        ]);

        ConveyanceBill::create($data);
        return redirect()->route('admin.expenses.index')->with('success', 'Expense saved successfully.');
    }

    public function edit(ConveyanceBill $expense): View
    {
        return view('admin.expenses.form', ['expense' => $expense, 'branches' => Branch::orderBy('name')->get()]);
    }

    public function update(Request $request, ConveyanceBill $expense): RedirectResponse
    {
        $data = $request->validate([
            'bill_date' => ['required', 'date'],
            'branch_id' => ['nullable','integer'],
            'employee_name' => ['nullable', 'string', 'max:120'],
            'purpose' => ['required', 'string', 'max:255'],
            'amount' => ['required', 'numeric', 'min:0'],
            'note' => ['nullable', 'string'],
        ]);

        $expense->update($data);
        return redirect()->route('admin.expenses.index')->with('success', 'Expense updated successfully.');
    }

    public function destroy(ConveyanceBill $expense): RedirectResponse
    {
        $expense->delete();
        return redirect()->route('admin.expenses.index')->with('success', 'Expense deleted successfully.');
    }
}
