<?php
/**
 * IoT Control Panel - لوحة التحكم المركزية
 */

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get all devices
    $devices_query = "SELECT * FROM iot_devices ORDER BY device_id";
    $devices_stmt = $db->query($devices_query);
    $devices = $devices_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get total pins count
    $pins_query = "SELECT COUNT(*) as total FROM device_pins";
    $pins_stmt = $db->query($pins_query);
    $total_pins = $pins_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
} catch (Exception $e) {
    die('<div style="padding:20px;background:#ef4444;color:white;">❌ خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>');
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة التحكم IoT</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700;800&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); }
        .device-card { background: linear-gradient(135deg, #f3f4f6 0%, #ffffff 100%); border-radius: 15px; padding: 25px; border: 2px solid #e5e7eb; transition: all 0.3s; cursor: pointer; }
        .device-card:hover { transform: translateY(-5px); box-shadow: 0 15px 40px rgba(0,0,0,0.15); border-color: #667eea; }
        .stat-card { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border-radius: 15px; padding: 25px; text-align: center; }
        .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:hover { transform: scale(1.05); }
        .status-badge { padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; }
        .status-online { background: #10b981; color: white; }
        .status-offline { background: #ef4444; color: white; }
    </style>
</head>
<body>
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <div class="card mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-4xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-microchip text-purple-600 ml-3"></i>
                        لوحة التحكم IoT
                    </h1>
                    <p class="text-gray-600">إدارة الأجهزة والبينات والإعدادات</p>
                </div>
                <div class="flex gap-3">
                    <a href="../index.php" class="btn bg-gray-200 text-gray-800">
                        <i class="fas fa-home ml-2"></i>
                        الرئيسية
                    </a>
                    <a href="settings.php" class="btn btn-primary">
                        <i class="fas fa-cog ml-2"></i>
                        الإعدادات
                    </a>
                </div>
            </div>
        </div>

        <!-- Stats -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <div class="stat-card">
                <i class="fas fa-microchip text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo count($devices); ?></h3>
                <p class="text-sm opacity-90">إجمالي الأجهزة</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-plug text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo $total_pins; ?></h3>
                <p class="text-sm opacity-90">إجمالي البينات</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-check-circle text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo count(array_filter($devices, fn($d) => isset($d['status']) && $d['status'] === 'online')); ?></h3>
                <p class="text-sm opacity-90">أجهزة متصلة</p>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="card mb-6">
            <h2 class="text-2xl font-bold text-gray-900 mb-4">
                <i class="fas fa-bolt ml-2"></i>
                إجراءات سريعة
            </h2>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <a href="devices.php" class="btn btn-primary text-center">
                    <i class="fas fa-microchip block text-2xl mb-2"></i>
                    إدارة الأجهزة
                </a>
                <a href="pins.php" class="btn btn-success text-center">
                    <i class="fas fa-sliders-h block text-2xl mb-2"></i>
                    إدارة البينات
                </a>
                <a href="control.php" class="btn bg-blue-600 text-white text-center">
                    <i class="fas fa-gamepad block text-2xl mb-2"></i>
                    التحكم المباشر
                </a>
                <a href="arduino-code-generator.php" class="btn bg-green-600 text-white text-center">
                    <i class="fas fa-code block text-2xl mb-2"></i>
                    كود Arduino
                </a>
                <a href="monitor.php" class="btn bg-purple-600 text-white text-center">
                    <i class="fas fa-terminal block text-2xl mb-2"></i>
                    مراقب ESP
                </a>
                <a href="sensors.php" class="btn bg-blue-600 text-white text-center">
                    <i class="fas fa-chart-line block text-2xl mb-2"></i>
                    لوحة الحساسات
                </a>
                <a href="smart-lock.php" class="btn bg-indigo-600 text-white text-center">
                    <i class="fas fa-lock block text-2xl mb-2"></i>
                    القفل الذكي
                </a>
            </div>
        </div>

        <!-- Devices List -->
        <div class="card">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">
                <i class="fas fa-list ml-2"></i>
                الأجهزة المتاحة
            </h2>

            <?php if (empty($devices)): ?>
                <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>
                    <a href="devices.php" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة جهاز
                    </a>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <?php foreach ($devices as $device): 
                        // Get pins count for this device
                        $pins_count_query = "SELECT COUNT(*) as count FROM device_pins WHERE device_id = ?";
                        $pins_count_stmt = $db->prepare($pins_count_query);
                        $pins_count_stmt->execute([$device['device_id']]);
                        $pins_count = $pins_count_stmt->fetch(PDO::FETCH_ASSOC)['count'];
                    ?>
                        <div class="device-card" onclick="window.location.href='pins.php?device_id=<?php echo $device['device_id']; ?>'">
                            <div class="flex items-start justify-between mb-4">
                                <div class="text-4xl">
                                    <i class="fas fa-microchip text-purple-600"></i>
                                </div>
                                <span class="status-badge <?php echo (isset($device['status']) && $device['status'] === 'online') ? 'status-online' : 'status-offline'; ?>">
                                    <?php echo (isset($device['status']) && $device['status'] === 'online') ? 'متصل' : 'غير متصل'; ?>
                                </span>
                            </div>
                            
                            <h3 class="text-xl font-bold text-gray-900 mb-2">
                                <?php echo htmlspecialchars($device['device_name']); ?>
                            </h3>
                            
                            <div class="space-y-2 text-sm text-gray-600 mb-4">
                                <p><i class="fas fa-tag ml-2"></i> <?php echo $device['device_id']; ?></p>
                                <p><i class="fas fa-network-wired ml-2"></i> <?php echo htmlspecialchars($device['ip_address']); ?></p>
                                <p><i class="fas fa-plug ml-2"></i> <?php echo $pins_count; ?> بينات مُكوّنة</p>
                            </div>
                            
                            <div class="flex gap-2">
                                <a href="pins.php?device_id=<?php echo $device['device_id']; ?>" 
                                   class="flex-1 btn btn-primary text-center text-sm"
                                   onclick="event.stopPropagation()">
                                    <i class="fas fa-sliders-h ml-1"></i>
                                    إدارة البينات
                                </a>
                                <a href="control.php?device_id=<?php echo $device['device_id']; ?>" 
                                   class="flex-1 btn btn-success text-center text-sm"
                                   onclick="event.stopPropagation()">
                                    <i class="fas fa-gamepad ml-1"></i>
                                    التحكم
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
    // Auto-refresh device status every 5 seconds
    setInterval(function() {
        // Update offline devices
        fetch('../database/update_offline_devices.php')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.affected_rows > 0) {
                    // Reload page if any device status changed
                    location.reload();
                }
            })
            .catch(error => console.error('Error:', error));
    }, 5000);
    </script>
</body>
</html>
