<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\Billing\PaymentService;
use App\Services\Billing\RefundService;
use Config\Database;

/**
 * Super Admin only (enforced via roleguard on routes). Gives the platform
 * owner visibility into every payment across every agency, and a way to
 * manually confirm Bank Transfer payments — which have no automated
 * webhook callback at all (see BankTransferGateway) — or fall back to
 * manual confirmation for any other gateway when needed.
 */
class AdminPaymentController extends BaseController
{
    private PaymentService $payments;
    private RefundService $refunds;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->payments = new PaymentService();
        $this->refunds  = new RefundService();
    }

    public function index()
    {
        $status = $this->request->getGet('status');
        $gateway = $this->request->getGet('gateway');

        $payments = $this->payments->listAll($status ?: null, $gateway ?: null);

        // attach agency name + invoice number for the admin table
        $db = Database::connect();
        foreach ($payments as &$p) {
            $agency = $db->table('agencies')->select('company_name')->where('id', $p['agency_id'])->get()->getRowArray();
            $p['agency_name'] = $agency['company_name'] ?? null;
            if ($p['invoice_id']) {
                $invoice = $db->table('invoices')->select('invoice_number')->where('id', $p['invoice_id'])->get()->getRowArray();
                $p['invoice_number'] = $invoice['invoice_number'] ?? null;
            }
        }

        return $this->jsonSuccess($payments);
    }

    public function verify(int $id)
    {
        try {
            $result = $this->payments->manuallyVerifyPayment($id, $this->currentUser()->id);
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => $e->getMessage()]], 404);
        }

        return $this->jsonSuccess($result);
    }

    public function refundQueue()
    {
        return $this->jsonSuccess(['refund_requests' => $this->refunds->pendingQueue()]);
    }

    public function approveRefund(int $id)
    {
        try {
            $result = $this->refunds->approve($id, $this->currentUser()->id);
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => $e->getMessage()]], 404);
        }
        return $this->jsonSuccess($result);
    }

    public function rejectRefund(int $id)
    {
        try {
            $this->refunds->reject($id, $this->currentUser()->id);
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => $e->getMessage()]], 404);
        }
        return $this->jsonSuccess(['message' => 'Refund request rejected.']);
    }
}
