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

$auth = new Auth();
$userModel = new User();
$currentBalance = $auth->refreshBalance($_SESSION['user_id']);
$pdo = getDBConnection();

$error = '';
$success = '';

$orderId = intval($_GET['id'] ?? 0);

if (!$orderId) {
    header('Location: sms.php');
    exit;
}

// Get order with country/service info
$stmt = $pdo->prepare("SELECT o.*, c.name as country_name, c.short_name, s.custom_name as service_name 
    FROM sms_orders o 
    LEFT JOIN sms_countries c ON o.country_id = c.id 
    LEFT JOIN sms_services s ON o.service_id = s.id 
    WHERE o.id = ? AND o.user_id = ?");
$stmt->execute([$orderId, $_SESSION['user_id']]);
$order = $stmt->fetch();

if (!$order) {
    header('Location: sms.php');
    exit;
}

$api = new SMSPoolAPI();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'check_sms') {
        if ($order['api_order_id']) {
            $result = $api->checkSMS($order['api_order_id']);
            
            $code = $result['sms'] ?? $result['full_code'] ?? $result['code'] ?? '';
            $fullSms = $result['full_sms'] ?? $result['sms'] ?? '';
            
            if ($code && $code !== '0') {
                $stmt = $pdo->prepare("UPDATE sms_orders SET sms_code = ?, full_sms = ?, status = 'received' WHERE id = ?");
                $stmt->execute([$code, $fullSms, $orderId]);
                $order['sms_code'] = $code;
                $order['full_sms'] = $fullSms;
                $order['status'] = 'received';
                $success = 'SMS Code received!';
            } else {
                $success = 'Still waiting for SMS... Auto-checking every 5 seconds.';
            }
        }
    }
    
    if ($action === 'resend') {
        if ($order['api_order_id']) {
            $result = $api->resendSMS($order['api_order_id']);
            if (isset($result['success']) && $result['success'] == 1) {
                $success = 'Resend request sent!';
            } else {
                $error = 'Resend failed: ' . ($result['message'] ?? 'Unknown error');
            }
        }
    }
    
    if ($action === 'cancel') {
        if ($order['api_order_id']) {
            $api->cancelSMS($order['api_order_id']);
        }
        
        // Refund
        $userModel->updateBalance($_SESSION['user_id'], $order['charge'], 'add');
        $stmt = $pdo->prepare("UPDATE sms_orders SET status = 'cancelled' WHERE id = ?");
        $stmt->execute([$orderId]);
        
        header('Location: sms.php?cancelled=1');
        exit;
    }
}

// Calculate time remaining
// Set timezone to match server
date_default_timezone_set('UTC');
$expiresAt = strtotime($order['expires_at']);
$now = time();
$timeRemaining = max(0, $expiresAt - $now);

// Only auto-expire if REALLY expired (give 30 second buffer for timezone issues)
$isExpired = $timeRemaining <= 0 && $order['status'] === 'pending';

// Check API status for pending orders - refund if cancelled/expired on API side
if (($order['status'] === 'pending' || $order['status'] === 'waiting') && $order['api_order_id']) {
    $apiStatus = $api->checkSMS($order['api_order_id']);
    $apiOrderStatus = strtolower($apiStatus['status'] ?? '');
    
    if (in_array($apiOrderStatus, ['cancelled', 'expired', 'refunded', 'timeout'])) {
        // Refund the user
        $userModel->updateBalance($_SESSION['user_id'], $order['charge'], 'add');
        $currentBalance = $auth->refreshBalance($_SESSION['user_id']);
        
        $newStatus = ($apiOrderStatus === 'cancelled') ? 'cancelled' : 'expired';
        $stmt = $pdo->prepare("UPDATE sms_orders SET status = ? WHERE id = ?");
        $stmt->execute([$newStatus, $orderId]);
        $order['status'] = $newStatus;
        $success = 'Order ' . $newStatus . '. ' . formatCurrency($order['charge']) . ' refunded to your balance.';
    }
}

// Auto-expire if time is up
if ($isExpired && $order['status'] === 'pending') {
    // Double check by comparing timestamps
    $stmt = $pdo->prepare("SELECT TIMESTAMPDIFF(SECOND, NOW(), expires_at) as remaining FROM sms_orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $check = $stmt->fetch();
    
    if ($check && $check['remaining'] <= 0) {
        // Refund the user
        $userModel->updateBalance($_SESSION['user_id'], $order['charge'], 'add');
        $currentBalance = $auth->refreshBalance($_SESSION['user_id']);
        
        $stmt = $pdo->prepare("UPDATE sms_orders SET status = 'expired' WHERE id = ?");
        $stmt->execute([$orderId]);
        $order['status'] = 'expired';
        $success = 'Order expired. ' . formatCurrency($order['charge']) . ' refunded to your balance.';
    } else {
        // Timezone mismatch - recalculate from DB
        $timeRemaining = max(0, intval($check['remaining']));
        $isExpired = false;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS Order #<?php echo $orderId; ?> - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            background: #0f172a; 
            color: #fff; 
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header { 
            background: rgba(15, 23, 42, 0.95); 
            backdrop-filter: blur(10px);
            padding: 0.75rem 1rem; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            position: sticky; 
            top: 0; 
            z-index: 100;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .header-back { 
            background: rgba(255,255,255,0.1);
            border: none;
            color: #fff; 
            font-size: 0.85rem; 
            cursor: pointer; 
            display: flex; 
            align-items: center; 
            gap: 0.4rem; 
            text-decoration: none;
            padding: 0.4rem 0.8rem;
            border-radius: 8px;
        }
        
        .header-title { 
            font-weight: 600;
            font-size: 0.9rem;
            color: #94a3b8;
        }
        
        .header-balance { 
            background: #f59e0b;
            color: #0f172a;
            padding: 0.4rem 0.8rem; 
            border-radius: 20px; 
            font-weight: 700;
            font-size: 0.85rem;
        }
        
        .content { 
            padding: 1rem; 
            max-width: 400px; 
            margin: 0 auto;
            width: 100%;
            flex: 1;
        }
        
        .alert { 
            padding: 0.75rem 1rem; 
            border-radius: 10px; 
            margin-bottom: 1rem;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .alert-success { 
            background: rgba(16, 185, 129, 0.15); 
            border: 1px solid rgba(16, 185, 129, 0.3); 
            color: #10b981; 
        }
        
        .alert-danger { 
            background: rgba(244, 63, 94, 0.15); 
            border: 1px solid rgba(244, 63, 94, 0.3); 
            color: #f43f5e; 
        }
        
        .card {
            background: rgba(30, 41, 59, 0.6);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 1.25rem;
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        .status-badge { 
            display: inline-flex;
            align-items: center;
            gap: 0.4rem;
            padding: 0.4rem 0.8rem; 
            border-radius: 20px; 
            font-weight: 600; 
            font-size: 0.75rem; 
            text-transform: uppercase;
            margin-bottom: 0.75rem;
        }
        
        .status-pending, .status-waiting { 
            background: rgba(245, 158, 11, 0.2); 
            color: #f59e0b;
        }
        
        .status-received { 
            background: rgba(16, 185, 129, 0.2); 
            color: #10b981;
        }
        
        .status-cancelled, .status-expired { 
            background: rgba(244, 63, 94, 0.2); 
            color: #f43f5e;
        }
        
        .service-name { 
            font-size: 1.1rem; 
            font-weight: 700; 
            color: #fbbf24;
            margin-bottom: 0.25rem;
        }
        
        .country-name { 
            color: #94a3b8; 
            font-size: 0.85rem;
            margin-bottom: 1rem;
        }
        
        .phone-box { 
            background: rgba(15, 23, 42, 0.8);
            border-radius: 12px; 
            padding: 1rem; 
            text-align: center;
            margin-bottom: 1rem;
            border: 1px solid rgba(255,255,255,0.05);
        }
        
        .phone-label { 
            font-size: 0.7rem; 
            color: #64748b; 
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 0.5rem;
        }
        
        .phone-number { 
            font-size: 1.5rem; 
            font-weight: 700; 
            color: #fff;
            font-family: monospace;
            letter-spacing: 2px;
            margin-bottom: 0.75rem;
        }
        
        .copy-btn { 
            background: rgba(245, 158, 11, 0.15);
            border: 1px solid rgba(245, 158, 11, 0.3);
            color: #f59e0b; 
            padding: 0.4rem 0.8rem; 
            border-radius: 6px; 
            cursor: pointer; 
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .copy-btn.copied { 
            background: #10b981;
            border-color: #10b981;
            color: #fff;
        }
        
        .code-box { 
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(245, 158, 11, 0.05));
            border: 1px solid rgba(245, 158, 11, 0.3);
            border-radius: 12px; 
            padding: 1.25rem; 
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .code-label { 
            font-size: 0.7rem; 
            color: #f59e0b;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 0.5rem;
        }
        
        .code-value { 
            font-size: 2.5rem; 
            font-weight: 800; 
            color: #fbbf24;
            font-family: monospace;
            letter-spacing: 4px;
            margin-bottom: 0.75rem;
        }
        
        .full-sms { 
            font-size: 0.8rem; 
            color: #94a3b8; 
            margin-top: 0.75rem; 
            padding-top: 0.75rem; 
            border-top: 1px solid rgba(245, 158, 11, 0.2);
            text-align: left;
            word-break: break-word;
        }
        
        .waiting-box { 
            padding: 1.5rem;
            text-align: center;
        }
        
        .waiting-spinner {
            width: 40px;
            height: 40px;
            margin: 0 auto 0.75rem;
            border: 3px solid rgba(245, 158, 11, 0.2);
            border-top-color: #f59e0b;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin { 
            to { transform: rotate(360deg); } 
        }
        
        .waiting-text { 
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 0.25rem;
        }
        
        .auto-check { 
            font-size: 0.75rem; 
            color: #64748b;
        }
        
        .timer-box { 
            background: rgba(15, 23, 42, 0.8);
            border-radius: 10px; 
            padding: 0.75rem;
            display: flex; 
            align-items: center; 
            justify-content: center; 
            gap: 0.75rem;
            margin-bottom: 1rem;
        }
        
        .timer-icon { 
            color: #f59e0b;
            font-size: 1rem;
        }
        
        .timer-text { 
            font-size: 0.8rem; 
            color: #64748b; 
        }
        
        .timer-value { 
            font-size: 1.25rem; 
            font-weight: 700; 
            color: #f59e0b;
            font-family: monospace;
        }
        
        .timer-value.urgent { 
            color: #f43f5e;
        }
        
        .notice {
            background: rgba(244, 63, 94, 0.1);
            border: 1px solid rgba(244, 63, 94, 0.2);
            border-radius: 10px;
            padding: 0.875rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: #f43f5e;
            font-size: 0.8rem;
        }
        
        .notice.refunded {
            background: rgba(16, 185, 129, 0.1);
            border: 1px solid rgba(16, 185, 129, 0.2);
            color: #10b981;
        }
        
        .actions { 
            display: flex; 
            gap: 0.5rem;
        }
        
        .actions form { 
            flex: 1; 
        }
        
        .btn { 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            gap: 0.4rem; 
            width: 100%; 
            padding: 0.75rem; 
            border: none; 
            border-radius: 10px; 
            font-size: 0.85rem; 
            font-weight: 600; 
            cursor: pointer; 
        }
        
        .btn-navy {
            background: rgba(59, 130, 246, 0.2);
            color: #60a5fa;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }
        
        .btn-danger {
            background: rgba(244, 63, 94, 0.2);
            color: #f43f5e;
            border: 1px solid rgba(244, 63, 94, 0.3);
        }
        
        .btn-green {
            background: #10b981;
            color: #fff;
        }
        
        .back-link { 
            display: block; 
            text-align: center; 
            margin-top: 1rem; 
            color: #64748b; 
            text-decoration: none;
            font-size: 0.85rem;
            padding: 0.75rem;
        }
    </style>
</head>
<body>
    <header class="header">
        <a href="orders.php" class="header-back"><i class="fas fa-arrow-left"></i> Back</a>
        <span class="header-title">Order #<?php echo $orderId; ?></span>
        <div class="header-balance"><?php echo formatCurrency($currentBalance); ?></div>
    </header>
    
    <main class="content">
        <?php if ($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?></div><?php endif; ?>
        
        <div class="card">
            <span class="status-badge status-<?php echo $order['status']; ?>">
                <?php 
                $statusLabels = [
                    'pending' => '<i class="fas fa-clock"></i> Waiting',
                    'waiting' => '<i class="fas fa-clock"></i> Waiting',
                    'received' => '<i class="fas fa-check"></i> Received',
                    'cancelled' => '<i class="fas fa-times"></i> Cancelled',
                    'expired' => '<i class="fas fa-hourglass"></i> Expired',
                    'refunded' => '<i class="fas fa-undo"></i> Refunded'
                ];
                echo $statusLabels[$order['status']] ?? ucfirst($order['status']);
                ?>
            </span>
            
            <div class="service-name"><?php echo htmlspecialchars($order['service_name']); ?></div>
            <div class="country-name"><i class="fas fa-globe"></i> <?php echo htmlspecialchars($order['country_name']); ?><?php if($order['short_name']): ?> (<?php echo htmlspecialchars($order['short_name']); ?>)<?php endif; ?></div>
            
            <div class="phone-box">
                <div class="phone-label">Phone Number</div>
                <div class="phone-number" id="phoneNumber"><?php echo htmlspecialchars($order['phone_number']); ?></div>
                <button class="copy-btn" onclick="copyPhone()"><i class="fas fa-copy"></i> Copy</button>
            </div>
            
            <?php if ($order['status'] === 'received' && $order['sms_code']): ?>
            <div class="code-box">
                <div class="code-label">Verification Code</div>
                <div class="code-value" id="smsCode"><?php echo htmlspecialchars($order['sms_code']); ?></div>
                <button class="copy-btn" onclick="copyCode()" style="background:#f59e0b;color:#0f172a;border:none;"><i class="fas fa-copy"></i> Copy Code</button>
                <?php if ($order['full_sms']): ?>
                <div class="full-sms"><?php echo htmlspecialchars($order['full_sms']); ?></div>
                <?php endif; ?>
            </div>
            
            <?php elseif ($order['status'] === 'pending' || $order['status'] === 'waiting'): ?>
            <div class="waiting-box">
                <div class="waiting-spinner"></div>
                <div class="waiting-text">Waiting for SMS...</div>
            </div>
            
            <div class="timer-box">
                <i class="fas fa-clock timer-icon"></i>
                <span class="timer-text">Expires in</span>
                <span class="timer-value" id="countdown"><?php echo gmdate('i:s', $timeRemaining); ?></span>
            </div>
            
            <?php elseif ($order['status'] === 'expired'): ?>
            <div class="notice refunded"><i class="fas fa-check-circle"></i> Order expired. <?php echo formatCurrency($order['charge']); ?> refunded to your balance.</div>
            
            <?php elseif ($order['status'] === 'cancelled'): ?>
            <div class="notice refunded"><i class="fas fa-check-circle"></i> Order cancelled. <?php echo formatCurrency($order['charge']); ?> refunded to your balance.</div>
            <?php endif; ?>
            
            <?php if ($order['status'] === 'pending' || $order['status'] === 'waiting'): ?>
            <div class="actions">
                <form method="POST">
                    <?php echo csrfTokenField(); ?>
                    <input type="hidden" name="action" value="resend">
                    <button type="submit" class="btn btn-navy"><i class="fas fa-redo"></i> Resend</button>
                </form>
                <form method="POST" onsubmit="return confirm('Cancel order?')">
                    <?php echo csrfTokenField(); ?>
                    <input type="hidden" name="action" value="cancel">
                    <button type="submit" class="btn btn-danger"><i class="fas fa-times"></i> Cancel</button>
                </form>
            </div>
            <?php elseif ($order['status'] === 'received'): ?>
            <div class="actions">
                <a href="sms.php" class="btn btn-green" style="text-decoration:none;"><i class="fas fa-plus"></i> New Number</a>
            </div>
            <?php endif; ?>
        </div>
        
        <a href="sms.php" class="back-link"><i class="fas fa-arrow-left"></i> Back to SMS</a>
    </main>
    
    <script>
        function copyPhone() {
            navigator.clipboard.writeText(document.getElementById('phoneNumber').textContent).then(function() {
                var btn = document.querySelector('.phone-box .copy-btn');
                btn.innerHTML = '<i class="fas fa-check"></i> Copied';
                btn.classList.add('copied');
                setTimeout(function() {
                    btn.innerHTML = '<i class="fas fa-copy"></i> Copy';
                    btn.classList.remove('copied');
                }, 2000);
            });
        }
        
        function copyCode() {
            navigator.clipboard.writeText(document.getElementById('smsCode').textContent).then(function() {
                var btn = document.querySelector('.code-box .copy-btn');
                btn.innerHTML = '<i class="fas fa-check"></i> Copied';
                setTimeout(function() {
                    btn.innerHTML = '<i class="fas fa-copy"></i> Copy Code';
                }, 2000);
            });
        }
        
        <?php if (($order['status'] === 'pending' || $order['status'] === 'waiting') && $timeRemaining > 0): ?>
        var timeRemaining = <?php echo $timeRemaining; ?>;
        var countdownEl = document.getElementById('countdown');
        
        function updateCountdown() {
            if (timeRemaining <= 0) {
                countdownEl.textContent = '00:00';
                countdownEl.classList.add('urgent');
                location.reload();
                return;
            }
            var minutes = Math.floor(timeRemaining / 60);
            var seconds = timeRemaining % 60;
            countdownEl.textContent = String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
            if (timeRemaining <= 60) countdownEl.classList.add('urgent');
            timeRemaining--;
        }
        
        setInterval(updateCountdown, 1000);
        updateCountdown();
        
        setInterval(function() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '<?php echo SITE_URL; ?>/api/sms-check.php?order_id=<?php echo urlencode($order['api_order_id']); ?>&db_id=<?php echo $order['id']; ?>', true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        var data = JSON.parse(xhr.responseText);
                        if (data.code && data.code !== '0' && data.code !== '') location.reload();
                    } catch(e) {}
                }
            };
            xhr.send();
        }, 5000);
        <?php endif; ?>
    </script>
</body>
</html>