<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/classes/SMSPoolAPI.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$orderId = $_GET['order_id'] ?? '';
$dbId = intval($_GET['db_id'] ?? 0);

if (!$orderId) {
    echo json_encode(['error' => 'Order ID required']);
    exit;
}

$api = new SMSPoolAPI();
$result = $api->checkSMS($orderId);

$pdo = getDBConnection();

$code = '';
$status = 'pending';

if (isset($result['sms']) && !empty($result['sms'])) {
    $code = $result['sms'];
    $status = 'received';
} elseif (isset($result['full_code']) && !empty($result['full_code']) && $result['full_code'] !== '0') {
    $code = $result['full_code'];
    $status = 'received';
} elseif (isset($result['code']) && !empty($result['code']) && $result['code'] !== '0') {
    $code = $result['code'];
    $status = 'received';
}

// Update database if code received
if ($code && $dbId) {
    $stmt = $pdo->prepare("UPDATE sms_orders SET sms_code = ?, full_sms = ?, status = 'received' WHERE id = ? AND user_id = ?");
    $stmt->execute([
        $code,
        $result['full_sms'] ?? $result['sms'] ?? '',
        $dbId,
        $_SESSION['user_id']
    ]);
}

echo json_encode([
    'code' => $code,
    'status' => $status,
    'phone' => $result['phonenumber'] ?? '',
    'raw' => $result
]);