<?php
/**
 * My Payment Requests (Admin/Accountant)
 * GET /api/v1/payments/my-requests
 */

declare(strict_types=1);

use App\Core\Database;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$tenantId = $decoded['tenant_id'];

$db = Database::getInstance();

try {
    $stmt = $db->prepare("
        SELECT pr.id, pr.plan_id, pr.amount_jod, pr.internal_reference, pr.cliq_alias,
               pr.bank_reference, pr.status, pr.created_at, pr.verified_at,
               sp.name_ar AS plan_name
        FROM payment_requests pr
        LEFT JOIN subscription_plans sp ON pr.plan_id = sp.id
        WHERE pr.tenant_id = ?
        ORDER BY pr.created_at DESC
    ");
    $stmt->execute([$tenantId]);
    $requests = $stmt->fetchAll();

    // Map internal_reference to reference_number for Flutter compatibility
    foreach ($requests as &$req) {
        $req['reference_number'] = $req['internal_reference'];
    }

    json_success($requests, 'طلبات الدفع الخاصة بك');

} catch (\Throwable $e) {
    error_log("My Payment Requests Error: " . $e->getMessage());
    json_error('حدث خطأ أثناء جلب طلبات الدفع.', 500);
}
