<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech


ob_start();
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../include/config.php';
require_once __DIR__ . '/../../include/otp_functions.php';
require_once __DIR__ . '/../../include/smspva_functions.php';

// ── Input validation ─────────────────────────────────────────────────────────

// Discard any stray PHP warnings/notices that would break JSON
function json_clean_response(array $data, int $code = 200): void {
    ob_clean();
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data);
    exit;
}

if (empty($_GET['token'])) {
    json_clean_response(['status' => '500', 'message' => 'Token Blank']);
}

$token     = trim($_GET['token']);
$server_id = trim($_GET['server'] ?? '');
$page      = max(1, (int)($_GET['page']  ?? 1));
$limit     = max(1, min(100, (int)($_GET['limit'] ?? 50)));
$search    = trim($_GET['search'] ?? '');

// ── Auth ─────────────────────────────────────────────────────────────────────

$user_id = otp_verify_user($token, $pdo);
if ($user_id === false) {
    json_clean_response(['status' => '500', 'message' => 'Invalid session. Please login again.']);
}

// ── If no server specified, return countries list (both providers) ─────────────

if (empty($server_id)) {
    try {
        // Join api_detail so the front-end knows which provider each country uses
        $stmt = $pdo->prepare(
            "SELECT os.id, os.server_name, os.server_code, os.flag_url,
                    ad.api_type AS provider
               FROM otp_server os
               JOIN api_detail ad ON ad.id = os.api_id
              WHERE os.status = '1'
              ORDER BY os.server_name ASC"
        );
        $stmt->execute();
        $servers = $stmt->fetchAll(PDO::FETCH_ASSOC);

        json_clean_response([
            'status'  => '200',
            'message' => 'Countries loaded.',
            'data'    => $servers,
        ]);
    } catch (PDOException $e) {
        json_clean_response(['status' => '500', 'message' => 'Database error.']);
    }
}

// ── Load server + API detail ──────────────────────────────────────────────────

$server_data = otp_get_server($server_id, $pdo);
if (!$server_data) {
    json_clean_response(['status' => '500', 'message' => 'Server not found.']);
}

$api_data = otp_get_api($server_data['api_id'], $pdo);
if (!$api_data) {
    json_clean_response(['status' => '500', 'message' => 'API configuration error.']);
}

$provider = $api_data['api_type'] ?? 'smscodes';

// ── Popular service names ─────────────────────────────────────────────────────

$popular_names = [
    'WhatsAPP', 'Telegram', 'Instagram (+Threads)', 'Facebook',
    'X (Twitter)', 'TikTok', 'Google (YouTube, Gmail)',
    'Netflix', 'Uber', 'PayPal + Ebay', 'Amazon', 'Discord',
    'Signal', 'Snapchat', 'LinkedIn',
    'Microsoft (Azure, Bing, Skype, etc)', 'Apple', 'Steam',
    'OpenAI API (chatGPT, DALL-e 2)', 'Claude (Anthropic)',
    'Viber', 'WeChat', 'Tinder', 'Airbnb',
];

// ── Count total services for this server ─────────────────────────────────────

try {
    $count_sql    = "SELECT COUNT(*) FROM service WHERE server_id = :server_id AND status = '1'";
    $count_params = [':server_id' => $server_id];

    if (!empty($search)) {
        $count_sql .= " AND service_name LIKE :search";
        $count_params[':search'] = '%' . $search . '%';
    }

    $count_stmt = $pdo->prepare($count_sql);
    $count_stmt->execute($count_params);
    $total = (int)$count_stmt->fetchColumn();
} catch (PDOException $e) {
    json_clean_response(['status' => '500', 'message' => 'Database error.']);
}

// ── Fetch services (paginated) ────────────────────────────────────────────────

$offset = ($page - 1) * $limit;

try {
    $sql    = "SELECT s.id, s.service_name, s.service_id, s.service_price, s.service_logo,
                      sv.server_name, sv.server_code
                 FROM service s
                 JOIN otp_server sv ON sv.id = s.server_id
                WHERE s.server_id = :server_id AND s.status = '1'";
    $params = [':server_id' => $server_id];

    if (!empty($search)) {
        $sql .= " AND s.service_name LIKE :search";
        $params[':search'] = '%' . $search . '%';
    }

    $sql .= " ORDER BY s.service_name ASC LIMIT :limit OFFSET :offset";

    $stmt = $pdo->prepare($sql);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }
    $stmt->bindValue(':limit',  $limit,  PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    json_clean_response(['status' => '500', 'message' => 'Database error.']);
}

if (empty($services) && $page === 1) {
    json_clean_response(['status' => '500', 'message' => 'No services available for this country.']);
}

// ── Logo helpers ──────────────────────────────────────────────────────────────

$logo_base    = 'https://dashboard.smscodes.io/assets/images/services/';
$default_logo = 'https://i.ibb.co/ySRhxqh/default.png';

// ── Live operator counts (smspva only, fetched ONCE per request) ──────────────
// Calls /activation/countnumbers/{country} to get real-time stock per operator.
// Stored as ['OperatorName' => count] for O(1) lookup inside the service loop.
$live_op_counts = [];
if ($provider === 'smspva') {
    $live_op_counts = smspva_count_numbers(
        $api_data['api_url'],
        $api_data['api_key'],
        $server_data['server_code']
    );
    // If the live call fails (empty array), we fall back to cached count_available values
}

// ── Build service list ────────────────────────────────────────────────────────

$top_services = [];
$all_services = [];

foreach ($services as $svc) {
    $base_price = (float)$svc['service_price'];
    $user_price = otp_custom_price($user_id, $svc['service_id'], $server_id, $base_price, $pdo);

    // ── Logo ─────────────────────────────────────────────────────────────────
    $logo = $default_logo;
    if (!empty($svc['service_logo'])) {
        $logo = $logo_base . $svc['service_logo'];
    } else {
        try {
            $icon_stmt = $pdo->prepare(
                "SELECT img_url FROM service_icon WHERE short_code = :code LIMIT 1"
            );
            $icon_stmt->execute([':code' => $svc['service_id']]);
            $icon_row = $icon_stmt->fetch(PDO::FETCH_ASSOC);
            if ($icon_row && !empty($icon_row['img_url'])) {
                $logo = $icon_row['img_url'];
            }
        } catch (PDOException $e) {}
    }

    // ── For smspva (Server 1), load per-operator options from cache ──────────
    // Counts come from the live $live_op_counts map fetched once above.
    // If the live call returned nothing, fall back to the cached count_available.
    $operators = [];
    if ($provider === 'smspva') {
        try {
            // No count filter here — we apply the live count below and filter then
            $op_stmt = $pdo->prepare(
                "SELECT operator, usd_price, ngn_price, count_available
                   FROM smspva_service_cache
                  WHERE service_code = :sc
                    AND country_code = :cc
                    AND ngn_price > 0
                  ORDER BY ngn_price ASC"
            );
            $op_stmt->execute([
                ':sc' => $svc['service_id'],
                ':cc' => $svc['server_code'],
            ]);
            $op_rows = $op_stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($op_rows as $op_row) {
                $op_name = $op_row['operator'] ?: 'any';

                // Resolve count: live API result takes priority, then cached value
                if (!empty($live_op_counts)) {
                    // smspva operator names in countnumbers match cache exactly (e.g. "O2_UK")
                    $live_count = $live_op_counts[$op_name] ?? 0;
                } else {
                    // Live call failed — trust the cached value
                    $live_count = (int)$op_row['count_available'];
                }

                // Skip operators with no numbers right now
                if ($live_count <= 0) continue;

                $op_price = otp_custom_price($user_id, $svc['service_id'], $server_id, (float)$op_row['ngn_price'], $pdo);
                $operators[] = [
                    'operator'        => $op_name,
                    'ngn_price'       => number_format($op_price, 2),
                    'usd_price'       => (string)$op_row['usd_price'],
                    'count_available' => $live_count,
                ];
            }
        } catch (PDOException $e) { /* non-fatal — operators stays empty */ }
    }

    $item = [
        'id'            => $svc['service_id'],
        'service_name'  => $svc['service_name'],
        'service_price' => number_format($user_price, 2),
        'logo_url'      => $logo,
        'server_name'   => $svc['server_name'],
        'server_code'   => $svc['server_code'],
        'provider'      => $provider,
        'operators'     => $operators,   // empty array for smscodes
    ];

    // Top services (page 1 only)
    if ($page === 1) {
        foreach ($popular_names as $pop) {
            if (strcasecmp($svc['service_name'], $pop) === 0) {
                $top_services[] = $item;
                break;
            }
        }
    }

    $all_services[] = $item;
}

// ── Response ──────────────────────────────────────────────────────────────────

json_clean_response([
    'status'       => '200',
    'message'      => 'Services loaded.',
    'provider'     => $provider,
    'top_services' => ($page === 1) ? $top_services : [],
    'service'      => $all_services,
    'pagination'   => [
        'total'    => $total,
        'page'     => $page,
        'limit'    => $limit,
        'has_more' => ($offset + $limit) < $total,
    ],
]);