<?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';


// Ensure no stray output breaks JSON
if (!function_exists('json_clean_response')) {
    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;
    }
}

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

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

$token = trim($_GET['token']);

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

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

// ── Fetch active (waiting) orders ─────────────────────────────────────────────

try {
    $stmt = $pdo->prepare(
        "SELECT an.*, sv.server_name, sv.server_code, sv.flag_url, sv.api_id,
                ad.api_type, ad.api_url, ad.api_key
           FROM active_number an
           JOIN otp_server sv ON sv.id = an.server_id
           JOIN api_detail  ad ON ad.id = sv.api_id
          WHERE an.user_id       = :uid
            AND an.active_status = '2'
          ORDER BY an.buy_time DESC"
    );
    $stmt->execute([':uid' => $user_id]);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    json_clean_response(['status' => '500', 'message' => 'Database error.']);
}

if (empty($orders)) {
    json_clean_response(['status' => '500', 'message' => 'No active numbers.']);
}

// smscodes orders: 300s (5 min) | smspva orders: 600s (10 min)
// We track per-order using buy_time; smspva's orderExpireIn=600
$timeout_smscodes = 300;
$timeout_smspva   = 600;
$now     = time();
$result  = [];

foreach ($orders as $order) {
    $buy_ts   = strtotime($order['buy_time']);
    $elapsed  = $now - $buy_ts;
    $provider = $order['provider'] ?? 'smscodes';
    $timeout  = ($provider === 'smspva') ? $timeout_smspva : $timeout_smscodes;

    // If SMS already received — close the order and skip from active list
    if (!empty($order['sms_text']) && otp_is_valid_sms($order['sms_text'])) {
        try {
            $pdo->prepare(
                "UPDATE active_number SET active_status='1' WHERE id=:id AND active_status='2'"
            )->execute([':id' => $order['id']]);
        } catch (Exception $e) {}
        continue;
    }

    // Auto-expire orders older than 20 minutes
    if ($elapsed > $timeout) {
        try {
            $pdo->beginTransaction();

            $w = $pdo->prepare("SELECT id, main_balance FROM users WHERE id = :uid FOR UPDATE");
            $w->execute([':uid' => $user_id]);
            $wallet = $w->fetch(PDO::FETCH_ASSOC);

            // Double-check still active (prevent double-refund race with getMessage.php)
            $chk = $pdo->prepare(
                "SELECT id FROM active_number WHERE id=:id AND active_status='2' LIMIT 1"
            );
            $chk->execute([':id' => $order['id']]);

            if ($chk->fetch()) {
                $new_balance = (float)$wallet['main_balance'] + (float)$order['service_price'];
                $pdo->prepare("UPDATE users SET main_balance = :b WHERE id = :uid")
                    ->execute([':b' => $new_balance, ':uid' => $user_id]);
                $pdo->prepare(
                    "UPDATE active_number SET active_status='1', status='3' WHERE id=:id AND active_status='2'"
                )->execute([':id' => $order['id']]);
            }

            $pdo->commit();
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
        }
        continue;
    }

    $left_ms = max(0, (($buy_ts + $timeout) - $now) * 1000);

    // ── Build logo URL ────────────────────────────────────────────────────────
    $logo = '';
    try {
        $svc_stmt = $pdo->prepare(
            "SELECT service_logo FROM service WHERE service_id = :sid LIMIT 1"
        );
        $svc_stmt->execute([':sid' => $order['service_id']]);
        $svc_row = $svc_stmt->fetch(PDO::FETCH_ASSOC);
        if ($svc_row && !empty($svc_row['service_logo'])) {
            $logo = 'https://dashboard.smscodes.io/assets/images/services/' . $svc_row['service_logo'];
        }
    } catch (PDOException $e) {}

    if (empty($logo)) {
        $logo = otp_get_logo($order['service_id'], $pdo);
    }

    // ── Provider label ────────────────────────────────────────────────────────
    $provider_label = ($provider === 'smspva') ? 'Server1' : 'Server2';

    $result[] = [
        'order_id'       => $order['order_id'],
        'number'         => $order['number'],
        'service_name'   => $order['service_name'],
        'service_logo'   => $logo,
        'server_name'    => $order['server_name'],
        'flag_url'       => $order['flag_url'],
        'service_price'  => $order['service_price'],
        'status'         => $order['status'],
        'sms_text'       => '',
        'buy_time'       => $order['buy_time'],
        'left_time'      => (string)$left_ms,
        'provider'       => $provider,
        'provider_label' => $provider_label,
        'operator'       => $order['operator'] ?? '',
    ];
}

if (empty($result)) {
    json_clean_response(['status' => '500', 'message' => 'No active numbers.']);
}

json_clean_response([
    'status'  => '200',
    'message' => 'Active numbers found.',
    'data'    => $result,
    'total'   => count($result),
]);