<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\Payment;
use Illuminate\Http\Request;
use Inertia\Inertia;

class PaymentController extends Controller
{
    public function index(Request $request)
    {
        $payments = Payment::with(['invoice.lease.shop', 'invoice.lease.tenant'])
            ->when($request->search, fn($q, $s) => $q->whereHas('invoice.lease.tenant', fn($tq) => $tq->where('name', 'like', "%{$s}%")))
            ->latest()
            ->paginate(20)
            ->withQueryString();

        $invoices = Invoice::whereIn('status', ['pending', 'partial', 'overdue'])
            ->with(['lease.shop', 'lease.tenant', 'payments'])
            ->get();

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

    public function create(Request $request)
    {
        $invoices = Invoice::whereIn('status', ['pending', 'partial', 'overdue'])
            ->with(['lease.shop', 'lease.tenant', 'payments'])
            ->get();

        return Inertia::render('Payments/Create', [
            'invoices' => $invoices,
            'preselected_invoice_id' => $request->invoice_id,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'invoice_id' => 'required|exists:invoices,id',
            'amount_paid' => 'required|numeric|min:1',
            'payment_date' => 'required|date',
            'payment_method' => 'required|in:cash,bank_transfer,online',
            'proof_file' => 'nullable|file|max:5120',
            'received_by' => 'nullable|string|max:255',
            'remarks' => 'nullable|string',
        ]);

        if ($request->hasFile('proof_file')) {
            $validated['proof_file'] = $request->file('proof_file')->store('payment-proofs', 'public');
        }

        Payment::create($validated);

        // Update invoice status
        $invoice = Invoice::findOrFail($validated['invoice_id']);
        $totalPaid = $invoice->payments()->sum('amount_paid');

        if ($totalPaid >= $invoice->total_amount) {
            $invoice->update(['status' => 'paid']);
        } else {
            $invoice->update(['status' => 'partial']);
        }

        return redirect()->route('payments.index')->with('success', 'Payment recorded.');
    }

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

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

    public function destroy(Payment $payment)
    {
        $invoiceId = $payment->invoice_id;
        $payment->delete();

        // Recalculate invoice status
        $invoice = Invoice::find($invoiceId);
        if ($invoice) {
            $totalPaid = $invoice->payments()->sum('amount_paid');
            if ($totalPaid <= 0) {
                $invoice->update(['status' => 'pending']);
            } elseif ($totalPaid >= $invoice->total_amount) {
                $invoice->update(['status' => 'paid']);
            } else {
                $invoice->update(['status' => 'partial']);
            }
        }

        return redirect()->route('payments.index')->with('success', 'Payment deleted.');
    }
}
