<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\Sale;
use App\Models\SaleSource;
use Illuminate\Http\Request;

class SaleController extends Controller
{
    public function index()
    {
        $sales = Sale::with(['customer'])->latest()->paginate(15);

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

    public function create()
    {
        $customers = Customer::active()->get();
        $saleSources = SaleSource::active()->orderBy('name')->get();
        $nextInvoice = 'SL-' . str_pad((Sale::max('id') ?? 0) + 1, 5, '0', STR_PAD_LEFT);

        return view('sales.create', compact('customers', 'saleSources', 'nextInvoice'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'customer_id'    => ['nullable', 'exists:customers,id'],
            'invoice_no'     => ['nullable', 'string', 'max:50', 'unique:sales,invoice_no'],
            'sale_date'      => ['required', 'date'],
            'payment_method' => ['required', 'in:cash,card,other'],
            'sale_source_id' => ['nullable', 'exists:sale_sources,id'],
            'amount'         => ['required', 'numeric', 'min:0'],
            'reference'      => ['nullable', 'string', 'max:255'],
            'notes'          => ['nullable', 'string'],
        ]);

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

        Sale::create($data);

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

    public function destroy(Sale $sale)
    {
        $sale->delete();

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