<?php

namespace App\Http\Controllers\Platform;

use App\Http\Controllers\Controller;
use App\Models\SaasInvoice;
use App\Models\SaasPayment;
use App\Models\Tenant;
use App\Services\BillingService;
use Illuminate\Http\Request;

class BillingController extends Controller
{
    public function invoices(Request $request)
    {
        $query = SaasInvoice::with(['tenant', 'plan']);

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

        $invoices = $query->latest()->paginate(15);
        $totalCollected = SaasPayment::where('status', 'success')->sum('amount');
        $totalOutstanding = SaasInvoice::whereIn('status', ['issued', 'partially_paid', 'overdue'])->sum('balance');

        return view('platform.billing.invoices', compact('invoices', 'totalCollected', 'totalOutstanding'));
    }

    public function payments()
    {
        $payments = SaasPayment::with(['tenant', 'invoice', 'receiver'])->latest()->paginate(15);
        $tenants = Tenant::where('status', '!=', 'cancelled')->get();

        return view('platform.billing.payments', compact('payments', 'tenants'));
    }

    public function createPayment()
    {
        $tenants = Tenant::where('status', '!=', 'cancelled')->get();
        $invoices = SaasInvoice::whereIn('status', ['issued', 'partially_paid', 'overdue'])->with('tenant')->get();

        return view('platform.billing.manual_payment', compact('tenants', 'invoices'));
    }

    public function storeManualPayment(Request $request, BillingService $billingService)
    {
        $request->validate([
            'tenant_id' => 'required|exists:tenants,id',
            'amount' => 'required|numeric|min:1',
            'payment_method' => 'required|string',
        ]);

        $tenant = Tenant::findOrFail($request->tenant_id);
        $invoice = $request->filled('invoice_id') ? SaasInvoice::find($request->invoice_id) : null;

        $payment = $billingService->recordManualPayment(
            $tenant,
            $invoice,
            (float) $request->amount,
            $request->payment_method,
            $request->transaction_reference,
            $request->remarks
        );

        return redirect()->route('platform.billing.payments')->with('status', 'Manual payment of AED '.number_format($payment->amount, 2).' recorded successfully for '.$tenant->company_name);
    }
}
