<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Customer;
use Illuminate\Http\Request;
use DB;
use Barryvdh\DomPDF\Facade\Pdf;

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

    public function create()
    {
        $customers = Customer::orderBy('customer_name')->get();
        
        // Auto-generate invoice number (INV000001 format)
        $lastInvoice = Invoice::latest('id')->first();
        $nextId = $lastInvoice ? $lastInvoice->id + 1 : 1;
        $invoiceNo = 'INV' . str_pad($nextId, 6, '0', STR_PAD_LEFT);

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

    public function store(Request $request)
    {
        $request->validate([
            'invoice_no' => 'required|unique:invoices,invoice_no',
            'invoice_date' => 'required|date',
            'customer_id' => 'required|exists:customers,id',
            'subtotal' => 'required|numeric',
            'discount' => 'required|numeric',
            'grand_total' => 'required|numeric',
            'products' => 'required|array|min:1',
            'products.*.product_name' => 'required|string',
            'products.*.qty' => 'required|numeric|min:1',
            'products.*.rate' => 'required|numeric|min:0',
            'products.*.amount' => 'required|numeric|min:0',
        ]);

        DB::transaction(function () use ($request) {
            $invoice = Invoice::create([
                'invoice_no' => $request->invoice_no,
                'invoice_date' => $request->invoice_date,
                'customer_id' => $request->customer_id,
                'subtotal' => $request->subtotal,
                'discount' => $request->discount,
                'grand_total' => $request->grand_total,
            ]);

            foreach ($request->products as $item) {
                InvoiceItem::create([
                    'invoice_id' => $invoice->id,
                    'product_name' => $item['product_name'],
                    'qty' => $item['qty'],
                    'rate' => $item['rate'],
                    'amount' => $item['amount'],
                ]);
            }
        });

        return redirect()->route('invoices.index')->with('success', 'Invoice created successfully.');
    }

    public function show(Invoice $invoice)
    {
        $invoice->load('customer', 'items');
        return view('invoices.show', compact('invoice'));
    }

    public function edit(Invoice $invoice)
    {
        $invoice->load('items');
        $customers = Customer::orderBy('customer_name')->get();
        return view('invoices.edit', compact('invoice', 'customers'));
    }

    public function update(Request $request, Invoice $invoice)
    {
        $request->validate([
            'invoice_date' => 'required|date',
            'customer_id' => 'required|exists:customers,id',
            'subtotal' => 'required|numeric',
            'discount' => 'required|numeric',
            'grand_total' => 'required|numeric',
            'products' => 'required|array|min:1',
            'products.*.product_name' => 'required|string',
            'products.*.qty' => 'required|numeric|min:1',
            'products.*.rate' => 'required|numeric|min:0',
            'products.*.amount' => 'required|numeric|min:0',
        ]);

        DB::transaction(function () use ($request, $invoice) {
            $invoice->update([
                'invoice_date' => $request->invoice_date,
                'customer_id' => $request->customer_id,
                'subtotal' => $request->subtotal,
                'discount' => $request->discount,
                'grand_total' => $request->grand_total,
            ]);

            // Delete old items and insert new ones to keep it simple and clean
            $invoice->items()->delete();

            foreach ($request->products as $item) {
                InvoiceItem::create([
                    'invoice_id' => $invoice->id,
                    'product_name' => $item['product_name'],
                    'qty' => $item['qty'],
                    'rate' => $item['rate'],
                    'amount' => $item['amount'],
                ]);
            }
        });

        return redirect()->route('invoices.index')->with('success', 'Invoice updated successfully.');
    }

    public function destroy(Invoice $invoice)
    {
        $invoice->delete();
        return response()->json(['success' => true, 'message' => 'Invoice deleted successfully.']);
    }

    public function print(Invoice $invoice)
    {
        $invoice->load('customer', 'items');
        return view('invoices.print', compact('invoice'));
    }

    public function downloadPdf(Invoice $invoice)
    {
        $invoice->load('customer', 'items');
        $pdf = Pdf::loadView('invoices.pdf', compact('invoice'));
        return $pdf->download($invoice->invoice_no . '.pdf');
    }
}
