<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\PaymentResource;
use App\Models\Payment;
use App\Models\Rental;
use App\Services\PaymentService;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    public function __construct(protected PaymentService $paymentService) {}

    /**
     * GET /api/payments
     */
    public function index(Request $request)
    {
        $query = Payment::with(['client', 'rental', 'paymentMethod', 'collectedBy']);

        if ($clientId = $request->get('client_id'))  $query->where('client_id', $clientId);
        if ($rentalId = $request->get('rental_id'))  $query->where('rental_id', $rentalId);
        if ($status   = $request->get('status'))     $query->where('status', $status);
        if ($type     = $request->get('type'))       $query->where('type', $type);
        if ($from     = $request->get('from'))       $query->whereDate('paid_at', '>=', $from);
        if ($to       = $request->get('to'))         $query->whereDate('paid_at', '<=', $to);

        return PaymentResource::collection(
            $query->latest()->paginate($request->get('per_page', 20))
        );
    }

    /**
     * POST /api/payments — Record a manual payment
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'rental_id'         => 'required|exists:rentals,id',
            'payment_method_id' => 'required|exists:payment_methods,id',
            'amount'            => 'required|numeric|min:0.01',
            'type'              => 'required|in:rental,deposit,deposit_refund,lost_key_fee,renewal,other',
            'notes'             => 'nullable|string',
            'paid_at'           => 'nullable|date',
        ]);

        $payment = $this->paymentService->recordPayment($data, auth()->user());
        return new PaymentResource($payment->load('paymentMethod', 'collectedBy', 'invoice'));
    }

    /**
     * GET /api/payments/{payment}
     */
    public function show(Payment $payment)
    {
        $payment->load(['client', 'rental.locker', 'paymentMethod', 'collectedBy', 'invoice']);
        return new PaymentResource($payment);
    }

    /**
     * POST /api/payments/{payment}/void
     */
    public function void(Request $request, Payment $payment)
    {
        if ($payment->status !== 'completed') {
            return response()->json(['message' => 'Only completed payments can be voided.'], 422);
        }

        $payment->update(['status' => 'voided']);

        return new PaymentResource($payment->fresh());
    }

    /**
     * POST /api/payments/{payment}/refund
     */
    public function refund(Payment $payment)
    {
        if (! in_array($payment->status, ['completed'])) {
            return response()->json(['message' => 'Payment cannot be refunded.'], 422);
        }

        $payment->update(['status' => 'refunded']);
        return new PaymentResource($payment->fresh());
    }

    /**
     * GET /api/payments/{payment}/receipt/pdf
     */
    public function receiptPdf(Payment $payment)
    {
        $payment->load(['client', 'rental.locker.category', 'paymentMethod', 'collectedBy']);
        $pdf = Pdf::loadView('pdf.receipt', compact('payment'));
        return $pdf->download("receipt-{$payment->transaction_ref}.pdf");
    }

    // ── Gateway Callbacks ────────────────────────────────────────────────

    public function bkashCallback(Request $request)
    {
        return $this->paymentService->handleBkashCallback($request->all());
    }

    public function nagadCallback(Request $request)
    {
        return $this->paymentService->handleNagadCallback($request->all());
    }

    public function sslcommerzCallback(Request $request)
    {
        return $this->paymentService->handleSslcommerzCallback($request->all());
    }
}
