<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\Lease;
use App\Models\MeterReading;
use App\Models\Setting;
use Illuminate\Http\Request;
use Inertia\Inertia;

class InvoiceController extends Controller
{
    public function index(Request $request)
    {
        $invoices = Invoice::with(['lease.shop.owner', 'lease.tenant', 'payments'])
            ->when($request->status, fn($q, $s) => $q->where('status', $s))
            ->when($request->month, fn($q, $m) => $q->where('month', $m))
            ->when($request->search, fn($q, $s) => $q->whereHas('lease', fn($lq) => $lq->whereHas('tenant', fn($tq) => $tq->where('name', 'like', "%{$s}%"))->orWhereHas('shop', fn($sq) => $sq->where('shop_number', 'like', "%{$s}%"))))
            ->latest()
            ->paginate(20)
            ->withQueryString();

        return Inertia::render('Invoices/Index', [
            'invoices' => $invoices,
            'filters' => $request->only('search', 'status', 'month'),
        ]);
    }

    public function create()
    {
        $leases = Lease::active()->with(['shop.owner', 'tenant'])->get();

        return Inertia::render('Invoices/Create', [
            'leases' => $leases,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'lease_id' => 'required|exists:leases,id',
            'month' => 'required|string|size:7',
            'due_date' => 'required|date',
            'other_charges' => 'nullable|numeric|min:0',
            'other_charges_description' => 'nullable|string',
        ]);

        $lease = Lease::findOrFail($validated['lease_id']);
        $rentAmount = $lease->getRentForMonth($validated['month']);
        $maintenanceAmount = $lease->maintenance_fee;

        // Get electricity if enabled
        $electricityAmount = null;
        if ($lease->electricity_enabled) {
            $reading = MeterReading::where('lease_id', $lease->id)->where('month', $validated['month'])->first();
            $electricityAmount = $reading ? $reading->total_amount : null;
        }

        $otherCharges = $validated['other_charges'] ?? 0;
        $totalAmount = $rentAmount + ($electricityAmount ?? 0) + ($maintenanceAmount ?? 0) + $otherCharges;

        Invoice::create([
            'lease_id' => $lease->id,
            'invoice_number' => Invoice::generateInvoiceNumber(),
            'month' => $validated['month'],
            'rent_amount' => $rentAmount,
            'electricity_amount' => $electricityAmount,
            'maintenance_amount' => $maintenanceAmount,
            'other_charges' => $otherCharges,
            'other_charges_description' => $validated['other_charges_description'] ?? null,
            'total_amount' => $totalAmount,
            'due_date' => $validated['due_date'],
        ]);

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

    public function show(Invoice $invoice)
    {
        $invoice->load(['lease.shop.owner', 'lease.tenant', 'payments']);

        return Inertia::render('Invoices/Show', ['invoice' => $invoice]);
    }

    public function print(Invoice $invoice)
    {
        $invoice->load(['lease.shop.owner', 'lease.tenant', 'lease.securityDepositPayments', 'payments']);
        $settings = Setting::all()->pluck('value', 'key');

        return Inertia::render('Invoices/Print', [
            'invoice' => $invoice,
            'settings' => $settings,
        ]);
    }

    public function generateBulk(Request $request)
    {
        $validated = $request->validate([
            'month' => 'required|string|size:7',
            'due_date' => 'required|date',
        ]);

        $leases = Lease::active()->get();
        $generated = 0;

        foreach ($leases as $lease) {
            // Skip if invoice already exists for this month
            if (Invoice::where('lease_id', $lease->id)->where('month', $validated['month'])->exists()) {
                continue;
            }

            $rentAmount = $lease->getRentForMonth($validated['month']);
            $maintenanceAmount = $lease->maintenance_fee;

            $electricityAmount = null;
            if ($lease->electricity_enabled) {
                $reading = MeterReading::where('lease_id', $lease->id)->where('month', $validated['month'])->first();
                $electricityAmount = $reading ? $reading->total_amount : null;
            }

            $totalAmount = $rentAmount + ($electricityAmount ?? 0) + ($maintenanceAmount ?? 0);

            Invoice::create([
                'lease_id' => $lease->id,
                'invoice_number' => Invoice::generateInvoiceNumber(),
                'month' => $validated['month'],
                'rent_amount' => $rentAmount,
                'electricity_amount' => $electricityAmount,
                'maintenance_amount' => $maintenanceAmount,
                'other_charges' => 0,
                'total_amount' => $totalAmount,
                'due_date' => $validated['due_date'],
            ]);

            $generated++;
        }

        return redirect()->route('invoices.index')->with('success', "{$generated} invoices generated.");
    }

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