<?php

namespace App\Http\Controllers\Admin;

use App\Models\Invoice;
use App\Models\Customer;
use App\Models\CustomerContact;
use App\Models\Quote;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index()
    {
        $invoices = Invoice::with(['customer', 'contact', 'quote'])->get();
        return view('invoices.index', compact('invoices'));
    }

    public function create()
    {
        $customers = Customer::all();
        $contacts = CustomerContact::all();
        $quotes = Quote::all();
        return view('invoices.create', compact('customers', 'contacts', 'quotes'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'invoice_number' => 'required|unique:invoices',
            'invoice_date' => 'required|date',
            'customer_id' => 'required|exists:customers,id',
            'customer_contact_id' => 'nullable|exists:customer_contacts,id',
            'quote_id' => 'nullable|exists:quotes,id',
            'subtotal' => 'required|numeric',
            'discount' => 'nullable|numeric',
            'tax_total' => 'required|numeric',
            'total' => 'required|numeric',
        ]);

        $invoice = Invoice::create($validated);
        return redirect()->route('invoices.index')->with('success', 'Invoice created.');
    }

    public function show(Invoice $invoice)
    {
        return view('invoices.show', compact('invoice'));
    }

    public function edit(Invoice $invoice)
    {
        $customers = Customer::all();
        $contacts = CustomerContact::all();
        $quotes = Quote::all();
        return view('invoices.edit', compact('invoice', 'customers', 'contacts', 'quotes'));
    }

    public function update(Request $request, Invoice $invoice)
    {
        $validated = $request->validate([
            'invoice_date' => 'required|date',
            'customer_id' => 'required|exists:customers,id',
            'customer_contact_id' => 'nullable|exists:customer_contacts,id',
            'quote_id' => 'nullable|exists:quotes,id',
            'subtotal' => 'required|numeric',
            'discount' => 'nullable|numeric',
            'tax_total' => 'required|numeric',
            'total' => 'required|numeric',
        ]);

        $invoice->update($validated);
        return redirect()->route('invoices.index')->with('success', 'Invoice updated.');
    }

    public function destroy(Invoice $invoice)
    {
        $invoice->delete();
        return redirect()->route('invoices.index')->with('success', 'Invoice deleted.');
    }
}
