<?php
/**
 * ESP Monitor - مراقبة مخرجات ESP مباشرة
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../../config/database.php';

$device_id = $_GET['device_id'] ?? null;
$device = null;

if ($device_id) {
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        $device_query = "SELECT * FROM iot_devices WHERE device_id = ?";
        $device_stmt = $db->prepare($device_query);
        $device_stmt->execute([$device_id]);
        $device = $device_stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مراقب ESP - Serial Monitor</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * { font-family: 'Tajawal', sans-serif; }
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
        .card { background: white; border-radius: 20px; padding: 30px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); margin-bottom: 20px; }
        .btn { padding: 12px 24px; border-radius: 10px; font-weight: 600; transition: all 0.3s; cursor: pointer; border: none; text-decoration: none; display: inline-block; }
        .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
        .btn-success { background: linear-gradient(135deg, #10b981, #059669); color: white; }
        .btn-danger { background: linear-gradient(135deg, #ef4444, #dc2626); color: white; }
        .btn:hover { transform: scale(1.05); }
        .monitor { background: #1e1e1e; color: #00ff00; padding: 20px; border-radius: 15px; font-family: 'Courier New', monospace; font-size: 14px; height: 500px; overflow-y: auto; }
        .monitor-line { margin: 2px 0; }
        .monitor-line.info { color: #00ff00; }
        .monitor-line.warning { color: #ffa500; }
        .monitor-line.error { color: #ff0000; }
        .monitor-line.success { color: #00ffff; }
        .status-online { background: #10b981; color: white; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; }
        .status-offline { background: #ef4444; color: white; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; }
        .input-field { width: 100%; padding: 12px; border: 2px solid #e5e7eb; border-radius: 10px; }
    </style>
</head>
<body>
    <div class="max-w-6xl mx-auto">
        <!-- Header -->
        <div class="card">
            <div class="flex items-center justify-between mb-4">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-terminal text-purple-600 ml-2"></i>
                        مراقب ESP - Serial Monitor
                    </h1>
                    <p class="text-gray-600">شاهد مخرجات ESP مباشرة</p>
                </div>
                <div class="flex gap-3">
                    <a href="index.php" class="btn bg-gray-200 text-gray-800">
                        <i class="fas fa-arrow-right ml-2"></i>
                        رجوع
                    </a>
                </div>
            </div>

            <!-- Device Selector -->
            <div class="bg-blue-50 border-r-4 border-blue-500 p-4 rounded-lg">
                <label class="block text-sm font-bold text-gray-900 mb-2">
                    <i class="fas fa-microchip ml-2"></i>
                    اختر الجهاز
                </label>
                <select class="input-field" onchange="window.location.href='?device_id='+this.value">
                    <option value="">-- اختر جهاز --</option>
                    <?php
                    try {
                        $database = new Database();
                        $db = $database->getConnection();
                        $devices_query = "SELECT device_id, device_name FROM iot_devices ORDER BY device_id";
                        $devices_stmt = $db->query($devices_query);
                        while ($dev = $devices_stmt->fetch(PDO::FETCH_ASSOC)) {
                            $selected = ($device_id === $dev['device_id']) ? 'selected' : '';
                            echo "<option value='{$dev['device_id']}' {$selected}>{$dev['device_name']} ({$dev['device_id']})</option>";
                        }
                    } catch (Exception $e) {}
                    ?>
                </select>
            </div>
        </div>

        <?php if ($device): ?>
        
        <!-- Device Info -->
        <div class="card">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-microchip ml-2"></i>
                        <?php echo htmlspecialchars($device['device_name']); ?>
                    </h2>
                    <p class="text-gray-600">
                        <i class="fas fa-network-wired ml-2"></i>
                        <?php echo htmlspecialchars($device['ip_address']); ?>:<?php echo $device['port'] ?? 80; ?>
                    </p>
                </div>
                <span class="status-online" id="deviceStatus">
                    <i class="fas fa-circle ml-1"></i>
                    جاري الفحص...
                </span>
            </div>
        </div>

        <!-- Monitor Controls -->
        <div class="card">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-bold text-gray-900">
                    <i class="fas fa-tv ml-2"></i>
                    شاشة المراقبة
                </h2>
                <div class="flex gap-2">
                    <button onclick="clearMonitor()" class="btn bg-yellow-600 text-white text-sm">
                        <i class="fas fa-eraser ml-1"></i>
                        مسح
                    </button>
                    <button onclick="toggleAutoScroll()" class="btn bg-blue-600 text-white text-sm" id="scrollBtn">
                        <i class="fas fa-arrow-down ml-1"></i>
                        تمرير تلقائي
                    </button>
                    <button onclick="toggleMonitoring()" class="btn btn-success text-sm" id="monitorBtn">
                        <i class="fas fa-play ml-1"></i>
                        بدء المراقبة
                    </button>
                </div>
            </div>

            <!-- Monitor Screen -->
            <div class="monitor" id="monitor">
                <div class="monitor-line info">
                    ═══════════════════════════════════════════════════════
                </div>
                <div class="monitor-line success">
                    ✓ ESP Monitor - جاهز للمراقبة
                </div>
                <div class="monitor-line info">
                    ═══════════════════════════════════════════════════════
                </div>
                <div class="monitor-line">
                    اضغط "بدء المراقبة" لعرض مخرجات ESP...
                </div>
            </div>

            <!-- Stats -->
            <div class="grid grid-cols-4 gap-4 mt-4">
                <div class="bg-blue-50 p-3 rounded-lg text-center">
                    <p class="text-sm text-gray-600">إجمالي الرسائل</p>
                    <p class="text-2xl font-bold text-blue-600" id="totalMessages">0</p>
                </div>
                <div class="bg-green-50 p-3 rounded-lg text-center">
                    <p class="text-sm text-gray-600">نجاح</p>
                    <p class="text-2xl font-bold text-green-600" id="successMessages">0</p>
                </div>
                <div class="bg-yellow-50 p-3 rounded-lg text-center">
                    <p class="text-sm text-gray-600">تحذيرات</p>
                    <p class="text-2xl font-bold text-yellow-600" id="warningMessages">0</p>
                </div>
                <div class="bg-red-50 p-3 rounded-lg text-center">
                    <p class="text-sm text-gray-600">أخطاء</p>
                    <p class="text-2xl font-bold text-red-600" id="errorMessages">0</p>
                </div>
            </div>
        </div>

        <!-- Instructions -->
        <div class="card">
            <h2 class="text-xl font-bold text-gray-900 mb-4">
                <i class="fas fa-info-circle ml-2"></i>
                كيف يعمل؟
            </h2>
            <div class="space-y-3 text-gray-700">
                <p><strong>1.</strong> ESP يرسل الرسائل للسيرفر عبر HTTP</p>
                <p><strong>2.</strong> السيرفر يحفظها في جدول <code class="bg-gray-200 px-2 py-1 rounded">iot_logs</code></p>
                <p><strong>3.</strong> هذه الصفحة تقرأ الرسائل وتعرضها مباشرة</p>
                <p><strong>4.</strong> التحديث كل ثانيتين تلقائياً</p>
            </div>
        </div>

        <?php else: ?>
        
        <div class="card">
            <div class="text-center py-16">
                <i class="fas fa-microchip text-gray-300 text-6xl mb-4"></i>
                <p class="text-gray-500 text-lg mb-4">اختر جهاز من القائمة أعلاه</p>
            </div>
        </div>

        <?php endif; ?>
    </div>

    <script>
    const deviceId = '<?php echo $device_id ?? ""; ?>';
    let isMonitoring = false;
    let autoScroll = true;
    let monitorInterval;
    let lastLogId = 0;
    let stats = { total: 0, success: 0, warning: 0, error: 0 };

    function addLog(message, type = 'info') {
        const monitor = document.getElementById('monitor');
        const line = document.createElement('div');
        line.className = `monitor-line ${type}`;
        
        const timestamp = new Date().toLocaleTimeString('ar-EG');
        line.textContent = `[${timestamp}] ${message}`;
        
        monitor.appendChild(line);
        
        // Update stats
        stats.total++;
        if (type === 'success') stats.success++;
        if (type === 'warning') stats.warning++;
        if (type === 'error') stats.error++;
        
        updateStats();
        
        if (autoScroll) {
            monitor.scrollTop = monitor.scrollHeight;
        }
    }

    function updateStats() {
        document.getElementById('totalMessages').textContent = stats.total;
        document.getElementById('successMessages').textContent = stats.success;
        document.getElementById('warningMessages').textContent = stats.warning;
        document.getElementById('errorMessages').textContent = stats.error;
    }

    function clearMonitor() {
        document.getElementById('monitor').innerHTML = '';
        stats = { total: 0, success: 0, warning: 0, error: 0 };
        updateStats();
        addLog('تم مسح الشاشة', 'info');
    }

    function toggleAutoScroll() {
        autoScroll = !autoScroll;
        const btn = document.getElementById('scrollBtn');
        if (autoScroll) {
            btn.innerHTML = '<i class="fas fa-arrow-down ml-1"></i> تمرير تلقائي';
            btn.className = 'btn bg-blue-600 text-white text-sm';
        } else {
            btn.innerHTML = '<i class="fas fa-pause ml-1"></i> تمرير متوقف';
            btn.className = 'btn bg-gray-600 text-white text-sm';
        }
    }

    function toggleMonitoring() {
        isMonitoring = !isMonitoring;
        const btn = document.getElementById('monitorBtn');
        
        if (isMonitoring) {
            btn.innerHTML = '<i class="fas fa-stop ml-1"></i> إيقاف المراقبة';
            btn.className = 'btn btn-danger text-sm';
            startMonitoring();
            addLog('✓ بدأت المراقبة...', 'success');
        } else {
            btn.innerHTML = '<i class="fas fa-play ml-1"></i> بدء المراقبة';
            btn.className = 'btn btn-success text-sm';
            stopMonitoring();
            addLog('✗ توقفت المراقبة', 'warning');
        }
    }

    async function fetchLogs() {
        try {
            const response = await fetch(`../../api/iot/logs.php?device_id=${deviceId}&since=${lastLogId}`);
            const result = await response.json();
            
            if (result.success && result.logs && result.logs.length > 0) {
                result.logs.forEach(log => {
                    let type = 'info';
                    if (log.log_type === 'error') type = 'error';
                    else if (log.log_type === 'warning') type = 'warning';
                    else if (log.log_type === 'command' || log.log_type === 'status') type = 'success';
                    
                    addLog(log.message, type);
                    lastLogId = Math.max(lastLogId, log.id);
                });
            }
            
            // Update device status
            const statusEl = document.getElementById('deviceStatus');
            if (result.device_online) {
                statusEl.className = 'status-online';
                statusEl.innerHTML = '<i class="fas fa-circle ml-1"></i> متصل';
            } else {
                statusEl.className = 'status-offline';
                statusEl.innerHTML = '<i class="fas fa-circle ml-1"></i> غير متصل';
            }
            
        } catch (error) {
            addLog('خطأ في الاتصال: ' + error.message, 'error');
        }
    }

    function startMonitoring() {
        fetchLogs(); // Fetch immediately
        monitorInterval = setInterval(fetchLogs, 2000); // Then every 2 seconds
    }

    function stopMonitoring() {
        if (monitorInterval) {
            clearInterval(monitorInterval);
        }
    }

    // Auto-start if device selected
    <?php if ($device): ?>
    // Wait a bit then auto-start
    setTimeout(() => {
        if (!isMonitoring) {
            toggleMonitoring();
        }
    }, 1000);
    <?php endif; ?>
    </script>
</body>
</html>
