<?php
/**
 * List All Payment Requests (Super Admin)
 * GET /api/v1/payments/list
 */

declare(strict_types=1);

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

$decoded = AuthMiddleware::check();

if ($decoded['role'] !== 'super_admin') {
    json_error('هذه الصفحة لمدير النظام فقط.', 403);
}

$db = Database::getInstance();
$status = $_GET['status'] ?? null;
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

try {
    $where = '';
    $params = [];

    if ($status && in_array($status, ['pending', 'uploaded', 'verified', 'approved', 'rejected'])) {
        $where = 'WHERE pr.status = ?';
        $params[] = $status;
    }

    $stmt = $db->prepare("
        SELECT pr.*, 
               u.name AS user_name, u.phone AS user_phone,
               sp.name_ar AS plan_name_ar, sp.name_en AS plan_name_en
        FROM payment_requests pr
        LEFT JOIN users u ON pr.user_id = u.id
        LEFT JOIN subscription_plans sp ON pr.plan_id = sp.id
        $where
        ORDER BY pr.created_at DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute($params);
    $payments = $stmt->fetchAll();

    // Total count
    $countStmt = $db->prepare("SELECT COUNT(*) as total FROM payment_requests pr $where");
    $countStmt->execute($params);
    $total = $countStmt->fetch()['total'];

    json_success([
        'payments' => $payments,
        'pagination' => [
            'page' => $page,
            'limit' => $limit,
            'total' => (int)$total,
            'pages' => ceil($total / $limit)
        ]
    ], 'طلبات الدفع');

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