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

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

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

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

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

$token   = trim($_GET['token']);
$user_id = otp_verify_user($token, $pdo);

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

// ── Optional filters ─────────────────────────────────────────────────────────

$filter  = isset($_GET['filter']) ? trim($_GET['filter']) : 'all';
$page    = max(1, (int)($_GET['page'] ?? 1));
$limit   = min(50, max(1, (int)($_GET['limit'] ?? 20)));
$offset  = ($page - 1) * $limit;

// ── Build WHERE clause ───────────────────────────────────────────────────────
// Only show finalised orders (active_status='1') — not ones still waiting

$where  = "WHERE an.user_id = :uid AND an.active_status = '1'";
$params = [':uid' => $user_id];

switch ($filter) {
    case 'received':
        $where .= " AND an.status = '1' AND an.sms_text != ''";
        break;
    case 'cancelled':
        $where .= " AND an.status = '3'";
        break;
}

// ── Count total ──────────────────────────────────────────────────────────────

try {
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM active_number an $where");
    $count_stmt->execute($params);
    $total = (int)$count_stmt->fetchColumn();
} catch (PDOException $e) {
    otp_json_response(['status' => '500', 'message' => 'Database error.']);
}

// ── Fetch records ────────────────────────────────────────────────────────────

try {
    $hist_stmt = $pdo->prepare(
        "SELECT an.*, os.server_name, os.flag_url
           FROM active_number an
           LEFT JOIN otp_server os ON os.id = an.server_id
           $where
           ORDER BY an.id DESC
           LIMIT :lim OFFSET :off"
    );
    foreach ($params as $k => $v) {
        $hist_stmt->bindValue($k, $v);
    }
    $hist_stmt->bindValue(':lim', $limit,  PDO::PARAM_INT);
    $hist_stmt->bindValue(':off', $offset, PDO::PARAM_INT);
    $hist_stmt->execute();
    $rows = $hist_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    otp_json_response(['status' => '500', 'message' => 'Database error.']);
}

// ── Build response ───────────────────────────────────────────────────────────

$final = [];
$i     = $offset + 1;

foreach ($rows as $row) {
    $logo_url  = otp_get_logo($row['service_id'], $pdo);
    $formatted = date('M d, Y - h:i A', strtotime($row['buy_time']));
    $has_sms   = (!empty($row['sms_text']) && $row['status'] === '1' && otp_is_valid_sms($row['sms_text']));

    $final[] = [
        'row_number'    => $i++,
        'order_id'      => $row['order_id'],
        'service_name'  => $row['service_name'],
        'service_id'    => $row['service_id'],
        'server_id'     => $row['server_id'],
        'server_name'   => $row['server_name'] ?? '',
        'flag_url'      => $row['flag_url']    ?? '',
        'number'        => $row['number'],
        'sms_text'      => $has_sms ? $row['sms_text'] : '',
        'service_price' => $row['service_price'],
        'date'          => $formatted,
        'status'        => $has_sms ? 'received' : 'cancelled',
        'logo_url'      => $logo_url,
    ];
}

otp_json_response([
    'status' => '200',
    'total'  => $total,
    'page'   => $page,
    'pages'  => (int)ceil($total / $limit),
    'data'   => $final,
]);