<?php
// GET ?action=sms_history&api_key=KEY&page=1&limit=20
// Returns SMS purchase history

$user_id = $GLOBALS['api_user_id'];
$page    = max(1, (int)($_GET['page'] ?? 1));
$limit   = max(1, min(100, (int)($_GET['limit'] ?? 20)));
$offset  = ($page - 1) * $limit;

try {
    $count = (int)$pdo->prepare("SELECT COUNT(*) FROM active_number WHERE user_id = :uid")
        ->execute([':uid' => $user_id]) ? $pdo->query("SELECT FOUND_ROWS()")->fetchColumn() : 0;

    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM active_number WHERE user_id = :uid");
    $count_stmt->execute([':uid' => $user_id]);
    $total = (int)$count_stmt->fetchColumn();

    $stmt = $pdo->prepare(
        "SELECT order_id, number, service_name, service_price, sms_text, active_status, buy_time
           FROM active_number
          WHERE user_id = :uid
          ORDER BY buy_time DESC
          LIMIT :lim OFFSET :off"
    );
    $stmt->bindValue(':uid', $user_id, PDO::PARAM_INT);
    $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':off', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Database error.'], 500);
}

$status_map = ['0' => 'cancelled', '1' => 'completed', '2' => 'waiting', '3' => 'expired'];
$result = [];
foreach ($orders as $o) {
    $result[] = [
        'order_id'   => $o['order_id'],
        'number'     => $o['number'],
        'service'    => $o['service_name'],
        'price'      => $o['service_price'],
        'sms_code'   => $o['sms_text'] ?: null,
        'status'     => $status_map[$o['active_status']] ?? 'unknown',
        'created_at' => $o['buy_time'],
    ];
}

api_response([
    'status'     => 'success',
    'total'      => $total,
    'page'       => $page,
    'limit'      => $limit,
    'orders'     => $result,
]);
