<?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();
    
    $device_id = $_GET['device_id'] ?? null;
    
    if ($device_id) {
        // Get specific device
        $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);
        
        if (!$device) {
            die('Device not found');
        }
        
        // Get pins for this device
        $pins_query = "SELECT * FROM device_pins WHERE device_id = ? ORDER BY pin_gpio";
        $pins_stmt = $db->prepare($pins_query);
        $pins_stmt->execute([$device_id]);
        $pins = $pins_stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        // 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);
    }
    
} 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); }
        .control-card { background: linear-gradient(135deg, #f3f4f6 0%, #ffffff 100%); border-radius: 15px; padding: 25px; border: 2px solid #e5e7eb; transition: all 0.3s; text-align: center; }
        .control-card:hover { transform: translateY(-5px); box-shadow: 0 15px 40px rgba(0,0,0,0.15); }
        .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; }
        .sensor-value { background: linear-gradient(135deg, #3b82f6, #2563eb); color: white; padding: 15px 20px; border-radius: 10px; font-size: 18px; font-weight: bold; text-align: center; }
        .btn:hover { transform: scale(1.05); }
        .toggle-btn { width: 100%; padding: 20px; border-radius: 15px; font-size: 18px; font-weight: bold; border: none; cursor: pointer; transition: all 0.3s; }
        .toggle-btn.off { background: linear-gradient(135deg, #ef4444, #dc2626); color: white; }
        .toggle-btn.on { background: linear-gradient(135deg, #10b981, #059669); color: white; }
        .toggle-btn:hover { transform: scale(1.05); box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
        .toggle-btn:active { transform: scale(0.95); }
        .device-selector { padding: 15px; border: 2px solid #e5e7eb; border-radius: 10px; font-size: 16px; font-weight: 600; }
    </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-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-gamepad text-purple-600 ml-2"></i>
                        التحكم المباشر
                    </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-arrow-right ml-2"></i>
                        رجوع
                    </a>
                </div>
            </div>
        </div>

        <?php if (!$device_id): ?>
            <!-- Device Selection -->
            <div class="card">
                <h2 class="text-2xl font-bold text-gray-900 mb-6">
                    <i class="fas fa-microchip 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 $dev): ?>
                            <a href="?device_id=<?php echo $dev['device_id']; ?>" class="control-card block">
                                <i class="fas fa-microchip text-6xl text-purple-600 mb-4"></i>
                                <h3 class="text-xl font-bold text-gray-900 mb-2">
                                    <?php echo htmlspecialchars($dev['device_name']); ?>
                                </h3>
                                <p class="text-gray-600 text-sm"><?php echo $dev['device_id']; ?></p>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <!-- Device Info -->
            <div class="card mb-6">
                <div class="flex items-center justify-between">
                    <div>
                        <h2 class="text-2xl 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>
                    <a href="control.php" class="btn bg-gray-200 text-gray-800">
                        <i class="fas fa-exchange-alt ml-2"></i>
                        تغيير الجهاز
                    </a>
                </div>
            </div>

            <!-- Control Pins -->
            <div class="card">
                <h2 class="text-2xl font-bold text-gray-900 mb-6">
                    <i class="fas fa-sliders-h ml-2"></i>
                    التحكم في البينات
                </h2>

                <?php if (empty($pins)): ?>
                    <div class="text-center py-16">
                        <i class="fas fa-plug text-gray-300 text-6xl mb-4"></i>
                        <p class="text-gray-500 text-lg mb-4">لا توجد بينات مُكوّنة لهذا الجهاز</p>
                        <a href="pins.php?device_id=<?php echo $device_id; ?>" class="btn btn-primary">
                            <i class="fas fa-plus ml-2"></i>
                            إضافة بينات
                        </a>
                    </div>
                <?php else: ?>
                    <?php 
                    // Separate pins by mode
                    $output_pins = array_filter($pins, function($p) { return ($p['pin_mode'] ?? 'OUTPUT') === 'OUTPUT'; });
                    $input_pins = array_filter($pins, function($p) { return ($p['pin_mode'] ?? 'OUTPUT') === 'INPUT'; });
                    ?>
                    
                    <!-- OUTPUT Pins (Control) -->
                    <?php if (!empty($output_pins)): ?>
                    <div class="mb-8">
                        <h3 class="text-xl font-bold text-gray-900 mb-4 flex items-center">
                            <i class="fas fa-toggle-on text-green-600 ml-2"></i>
                            المخرجات (Outputs) - التحكم
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            <?php foreach ($output_pins as $pin): ?>
                                <div class="control-card">
                                    <i class="fas <?php echo $pin['pin_icon']; ?> text-6xl text-purple-600 mb-4"></i>
                                    <h3 class="text-xl font-bold text-gray-900 mb-2">
                                        <?php echo htmlspecialchars($pin['pin_name']); ?>
                                    </h3>
                                    <p class="text-gray-600 text-sm mb-4">
                                        GPIO<?php echo $pin['pin_gpio']; ?> - <?php echo ucfirst($pin['pin_type']); ?>
                                    </p>
                                    
                                    <button 
                                        class="toggle-btn off" 
                                        id="pin_<?php echo $pin['id']; ?>"
                                        data-pin-id="<?php echo $pin['id']; ?>"
                                        data-device-id="<?php echo $device_id; ?>"
                                        data-gpio="<?php echo $pin['pin_gpio']; ?>"
                                        onclick="togglePin(this)">
                                        <i class="fas fa-power-off ml-2"></i>
                                        إيقاف
                                    </button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- INPUT Pins (Sensors) -->
                    <?php if (!empty($input_pins)): ?>
                    <div class="mb-8">
                        <h3 class="text-xl font-bold text-gray-900 mb-4 flex items-center">
                            <i class="fas fa-chart-line text-blue-600 ml-2"></i>
                            المدخلات (Inputs) - القراءة
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            <?php foreach ($input_pins as $pin): ?>
                                <div class="control-card bg-blue-50 border-blue-200">
                                    <i class="fas <?php echo $pin['pin_icon']; ?> text-6xl text-blue-600 mb-4"></i>
                                    <h3 class="text-xl font-bold text-gray-900 mb-2">
                                        <?php echo htmlspecialchars($pin['pin_name']); ?>
                                    </h3>
                                    <p class="text-gray-600 text-sm mb-4">
                                        GPIO<?php echo $pin['pin_gpio']; ?> - <?php echo ucfirst($pin['pin_type']); ?>
                                    </p>
                                    
                                    <div class="sensor-value" id="sensor_<?php echo $pin['id']; ?>">
                                        <i class="fas fa-spinner fa-spin ml-2"></i>
                                        جاري القراءة...
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="mt-6 bg-yellow-50 border-r-4 border-yellow-500 p-4 rounded-lg">
                        <p class="text-yellow-900">
                            <i class="fas fa-info-circle ml-2"></i>
                            <strong>ملاحظة:</strong> تأكد من أن جهاز ESP متصل بالشبكة وأن البرنامج مرفوع عليه بشكل صحيح
                        </p>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
    // Track pin states
    const pinStates = {};

    async function togglePin(button) {
        const pinId = button.dataset.pinId;
        const deviceId = button.dataset.deviceId;
        const gpio = button.dataset.gpio;
        
        // Toggle state
        const currentState = pinStates[pinId] || 0;
        const newState = currentState === 0 ? 1 : 0;
        
        // Update UI immediately
        button.disabled = true;
        button.innerHTML = '<i class="fas fa-spinner fa-spin ml-2"></i> جاري التحكم...';
        
        try {
            // Send command via commands API
            const formData = new FormData();
            formData.append('device_id', deviceId);
            formData.append('action', 'pin_control');
            formData.append('payload', JSON.stringify({
                gpio: parseInt(gpio),
                state: newState
            }));
            formData.append('priority', 5);
            
            const response = await fetch('../../api/iot/commands.php', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success) {
                // Update state
                pinStates[pinId] = newState;
                
                // Update button
                if (newState === 1) {
                    button.className = 'toggle-btn on';
                    button.innerHTML = '<i class="fas fa-check-circle ml-2"></i> تشغيل';
                } else {
                    button.className = 'toggle-btn off';
                    button.innerHTML = '<i class="fas fa-power-off ml-2"></i> إيقاف';
                }
            } else {
                alert('❌ خطأ: ' + (result.error || 'فشل التحكم في Pin'));
                button.className = 'toggle-btn off';
                button.innerHTML = '<i class="fas fa-power-off ml-2"></i> إيقاف';
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
            button.className = 'toggle-btn off';
            button.innerHTML = '<i class="fas fa-power-off ml-2"></i> إيقاف';
        } finally {
            button.disabled = false;
        }
    }

    // Function to load and update pin states
    async function loadPinStates() {
        try {
            const response = await fetch('../../api/iot/pin_status.php?device_id=<?php echo $device_id; ?>');
            const result = await response.json();
            
            if (result.success && result.pins) {
                result.pins.forEach(pin => {
                    const button = document.getElementById('pin_' + pin.id);
                    if (button) {
                        pinStates[pin.id] = pin.state;
                        
                        if (pin.state === 1) {
                            button.className = 'toggle-btn on';
                            button.innerHTML = '<i class="fas fa-check-circle ml-2"></i> تشغيل';
                        } else {
                            button.className = 'toggle-btn off';
                            button.innerHTML = '<i class="fas fa-power-off ml-2"></i> إيقاف';
                        }
                    }
                });
            }
        } catch (error) {
            console.error('Failed to load pin states:', error);
        }
    }

    // Load initial states on page load
    <?php if ($device_id && !empty($pins)): ?>
    window.addEventListener('DOMContentLoaded', () => {
        loadPinStates();
    });

    // Auto-refresh pin states every 5 seconds
    setInterval(loadPinStates, 5000);
    <?php endif; ?>
    </script>
</body>
</html>
