<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\PaymentTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Carbon\Carbon;

class InvoiceController extends Controller
{
    public function index(Request $request)
    {
        $query = Invoice::with(['client', 'items']);

        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('invoice_number', 'like', "%{$search}%")
                  ->orWhereHas('client', function ($cq) use ($search) {
                      $cq->where('name', 'like', "%{$search}%")
                         ->orWhere('company', 'like', "%{$search}%");
                  });
            });
        }

        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }

        $invoices = $query->orderBy('created_at', 'desc')->paginate(12);
        $clients = Client::orderBy('name', 'asc')->get();

        return view('admin.invoices.index', compact('invoices', 'clients'));
    }

    public function show(Invoice $invoice)
    {
        $invoice->load(['client', 'items', 'payments']);
        return response()->json($invoice);
    }

    public function store(Request $request)
    {
        $request->validate([
            'client_id' => 'required|exists:clients,id',
            'issue_date' => 'required|date',
            'due_date' => 'required|date|after_or_equal:issue_date',
            'tax_percent' => 'nullable|numeric|min:0|max:100',
            'discount_amount' => 'nullable|numeric|min:0',
            'items' => 'required|array|min:1',
            'items.*.description' => 'required|string',
            'items.*.quantity' => 'required|integer|min:1',
            'items.*.unit_price' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        $lastInv = Invoice::orderBy('id', 'desc')->first();
        $nextId = $lastInv ? ($lastInv->id + 1) : 1;
        $invNum = 'INV-2026-' . str_pad($nextId, 4, '0', STR_PAD_LEFT);

        $subtotal = 0;
        foreach ($request->items as $item) {
            $subtotal += ($item['quantity'] * $item['unit_price']);
        }

        $taxPercent = $request->input('tax_percent', 10.00);
        $taxAmount = round($subtotal * ($taxPercent / 100), 2);
        $discount = $request->input('discount_amount', 0);
        $totalAmount = max(0, $subtotal + $taxAmount - $discount);

        $invoice = Invoice::create([
            'invoice_number' => $invNum,
            'client_id' => $request->client_id,
            'issue_date' => $request->issue_date,
            'due_date' => $request->due_date,
            'subtotal' => $subtotal,
            'tax_percent' => $taxPercent,
            'tax_amount' => $taxAmount,
            'discount_amount' => $discount,
            'total_amount' => $totalAmount,
            'status' => 'Unpaid',
            'notes' => $request->notes ?? 'Payment due upon receipt.',
        ]);

        foreach ($request->items as $item) {
            InvoiceItem::create([
                'invoice_id' => $invoice->id,
                'description' => $item['description'],
                'quantity' => $item['quantity'],
                'unit_price' => $item['unit_price'],
                'total' => $item['quantity'] * $item['unit_price'],
            ]);
        }

        // Update Client Billed total
        $client = Client::find($request->client_id);
        $client->increment('total_billed', $totalAmount);

        return redirect()->route('admin.invoices.index')->with('success', "Invoice {$invNum} created successfully!");
    }

    public function markAsPaid(Request $request, Invoice $invoice)
    {
        if ($invoice->status !== 'Paid') {
            $invoice->update(['status' => 'Paid']);
            
            // Create payment record
            PaymentTransaction::create([
                'transaction_reference' => 'TXN-' . Str::upper(Str::random(10)),
                'invoice_id' => $invoice->id,
                'client_id' => $invoice->client_id,
                'amount' => $invoice->total_amount,
                'payment_method' => $request->input('payment_method', 'Credit Card'),
                'status' => 'Success',
                'paid_at' => now(),
            ]);

            // Update Client Paid total
            $invoice->client->increment('total_paid', $invoice->total_amount);
        }

        return redirect()->route('admin.invoices.index')->with('success', "Invoice {$invoice->invoice_number} marked as Paid!");
    }

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