<?php
// GET ?action=sms_check&api_key=KEY&order_id=ORDERID
// Check if SMS has been received for an order

$user_id  = $GLOBALS['api_user_id'];
$order_id = trim($_GET['order_id'] ?? '');

if (empty($order_id)) {
    api_response(['status' => 'error', 'message' => 'Missing order_id.'], 400);
}

try {
    $stmt = $pdo->prepare(
        "SELECT order_id, number, service_name, sms_text, status, active_status, buy_time
           FROM active_number
          WHERE order_id = :oid AND user_id = :uid
          LIMIT 1"
    );
    $stmt->execute([':oid' => $order_id, ':uid' => $user_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Database error.'], 500);
}

if (!$order) {
    api_response(['status' => 'error', 'message' => 'Order not found.'], 404);
}

$sms_received = !empty($order['sms_text']);

// Map status codes
$status_map = [
    '0' => 'cancelled',
    '1' => 'completed',
    '2' => 'waiting',
    '3' => 'expired',
];
$display_status = $status_map[$order['active_status']] ?? 'unknown';

$response = [
    'status'       => 'success',
    'order_id'     => $order['order_id'],
    'number'       => $order['number'],
    'service'      => $order['service_name'],
    'sms_code'     => $sms_received ? $order['sms_text'] : null,
    'order_status' => $display_status,
    'created_at'   => $order['buy_time'],
];

api_response($response);
