<?php
require_once 'admin_sold_credentials_common.php';
try {
    $input = sold_read_input();
    $adminId = sold_require_admin($input);
    vpnEnsureColumns($pdo);

    $q = trim((string)($_GET['q'] ?? $input['q'] ?? ''));
    $status = trim((string)($_GET['status'] ?? $input['status'] ?? ''));
    $page = max(1, (int)($_GET['page'] ?? $input['page'] ?? 1));
    $limit = min(100, max(10, (int)($_GET['limit'] ?? $input['limit'] ?? 50)));
    $offset = ($page - 1) * $limit;

    $where = ["d.id IS NOT NULL"];
    $params = [];
    if ($status !== '') {
        $where[] = "LOWER(d.status)=LOWER(?)";
        $params[] = $status;
    }
    if ($q !== '') {
        if (ctype_digit($q)) {
            $where[] = "(d.username LIKE ? OR c.username LIKE ? OR c.email LIKE ? OR d.user_id=? OR d.order_id=? OR d.id=? OR d.credential_id=?)";
            $like = '%' . $q . '%';
            array_push($params, $like, $like, $like, (int)$q, (int)$q, (int)$q, (int)$q);
        } else {
            $where[] = "(d.username LIKE ? OR c.username LIKE ? OR c.email LIKE ? OR u.username LIKE ? OR d.password LIKE ?)";
            $like = '%' . $q . '%';
            array_push($params, $like, $like, $like, $like, $like);
        }
    }
    $whereSql = implode(' AND ', $where);

    $countSt = $pdo->prepare("SELECT COUNT(*) FROM deliveries d LEFT JOIN credentials c ON c.id=d.credential_id LEFT JOIN users u ON u.id=d.user_id WHERE $whereSql");
    $countSt->execute($params);
    $total = (int)$countSt->fetchColumn();

    $notificationSelect = sold_column_exists($pdo, 'deliveries', 'notification_status')
        ? "d.notification_status, d.notification_sent_at, d.notification_error, d.notification_attempts,"
        : "NULL AS notification_status, NULL AS notification_sent_at, NULL AS notification_error, 0 AS notification_attempts,";

    $sql = "SELECT
            d.id AS delivery_id,
            d.order_id,
            d.user_id,
            d.credential_id,
            COALESCE(NULLIF(d.username,''), NULLIF(c.username,''), NULLIF(c.email,'')) AS username,
            COALESCE(NULLIF(d.password,''), NULLIF(c.password,'')) AS password,
            d.status,
            d.delivered_at,
            d.created_at,
            $notificationSelect
            c.status AS credential_status,
            c.is_sold,
            c.used_seats,
            c.max_seats,
            c.email AS credential_email,
            c.duration,
            c.traffic_type,
            c.traffic_limit_gb,
            o.status AS order_status,
            o.delivery_status AS order_delivery_status,
            o.payment_status,
            u.username AS telegram_username,
            u.first_name,
            u.last_name
        FROM deliveries d
        LEFT JOIN credentials c ON c.id=d.credential_id
        LEFT JOIN orders o ON o.id=d.order_id
        LEFT JOIN users u ON u.id=d.user_id
        WHERE $whereSql
        ORDER BY d.delivered_at DESC, d.id DESC
        LIMIT $limit OFFSET $offset";
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);

    sold_admin_log($pdo, $adminId, 'sold_credentials_list', [
        'target_type' => 'sold_credentials',
        'q' => $q,
        'status' => $status,
        'page' => $page,
        'returned' => count($rows),
    ]);

    sold_json_ok([
        'items' => $rows,
        'total' => $total,
        'page' => $page,
        'limit' => $limit,
        'has_more' => ($page * $limit) < $total,
    ], 'فهرست اشتراک‌های فروخته‌شده دریافت شد');
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();
    vpnLogEvent('admin_sold_credentials_failed', ['error' => $e->getMessage()]);
    sold_json_error('خطای سرور: ' . $e->getMessage());
}
