<?php
/**
 * Manage Device Pins - إدارة البينات
 */

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        die('<div style="padding:20px;background:#ef4444;color:white;">❌ فشل الاتصال بقاعدة البيانات</div>');
    }
    
    // Check if tables exist
    $check_table = $db->query("SHOW TABLES LIKE 'device_pins'");
    if ($check_table->rowCount() == 0) {
        die('<div style="padding:20px;background:#f59e0b;color:white;text-align:center;">
            ⚠️ جداول Pins غير موجودة<br><br>
            <a href="../../database/run_pins_setup.php" 
               style="display:inline-block;background:white;color:#f59e0b;padding:15px 30px;
                      text-decoration:none;border-radius:8px;font-weight:bold;">
            🚀 إنشاء الجداول الآن
            </a>
            </div>');
    }
} catch (Exception $e) {
    die('<div style="padding:20px;background:#ef4444;color:white;">❌ خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>');
}

// Get device_id from URL
$device_id = $_GET['device_id'] ?? 'ESP01';

// Fetch device info
$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');
}

// Fetch all 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);

// Available GPIO pins
$available_gpios = [16, 5, 4, 0, 2, 14, 12, 13, 15];
$used_gpios = array_column($pins, 'pin_gpio');
$free_gpios = array_diff($available_gpios, $used_gpios);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة Pins - <?php echo htmlspecialchars($device['device_name']); ?></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); }
        .pin-card { background: linear-gradient(135deg, #f3f4f6 0%, #ffffff 100%); border-radius: 15px; padding: 20px; margin-bottom: 15px; border: 2px solid #e5e7eb; transition: all 0.3s; }
        .pin-card:hover { transform: translateY(-3px); box-shadow: 0 10px 30px rgba(0,0,0,0.1); border-color: #667eea; }
        .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); }
        .input-field { width: 100%; padding: 12px; border: 2px solid #e5e7eb; border-radius: 10px; transition: all 0.3s; }
        .input-field:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        .modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); backdrop-filter: blur(5px); z-index: 1000; align-items: center; justify-content: center; }
        .modal.active { display: flex; }
        .modal-content { background: white; border-radius: 20px; max-width: 600px; width: 100%; max-height: 90vh; overflow-y: auto; animation: slideUp 0.3s; }
        @keyframes slideUp { from { opacity: 0; transform: translateY(50px); } to { opacity: 1; transform: translateY(0); } }
        .icon-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 10px; }
        .icon-btn { padding: 15px; border: 2px solid #e5e7eb; border-radius: 10px; cursor: pointer; text-align: center; transition: all 0.3s; }
        .icon-btn:hover, .icon-btn.selected { border-color: #667eea; background: #ede9fe; }
    </style>
</head>
<body>
    <div class="max-w-6xl mx-auto">
        <!-- Header -->
        <div class="card mb-6">
            <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-sliders-h text-purple-600 ml-2"></i>
                        إدارة Pins
                    </h1>
                    <p class="text-gray-600">
                        <i class="fas fa-microchip ml-2"></i>
                        <?php echo htmlspecialchars($device['device_name']); ?> (<?php echo $device_id; ?>)
                    </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>
                    <button onclick="openAddPinModal()" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة Pin
                    </button>
                </div>
            </div>
            
            <div class="bg-blue-50 border-r-4 border-blue-500 p-4 rounded-lg">
                <p class="text-blue-900">
                    <i class="fas fa-info-circle ml-2"></i>
                    <strong>Pins المتاحة:</strong> <?php echo count($free_gpios); ?> من 9
                    | <strong>Pins المستخدمة:</strong> <?php echo count($pins); ?>
                </p>
            </div>
        </div>

        <!-- Pins List -->
        <div class="card">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">
                <i class="fas fa-list ml-2"></i>
                Pins المُكوّنة
            </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">لم تقم بإضافة أي Pins بعد</p>
                    <button onclick="openAddPinModal()" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة Pin الآن
                    </button>
                </div>
            <?php else: ?>
                <div class="space-y-4">
                    <?php foreach ($pins as $pin): ?>
                        <div class="pin-card">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-4 flex-1">
                                    <div class="text-4xl">
                                        <i class="fas <?php echo $pin['pin_icon']; ?> text-purple-600"></i>
                                    </div>
                                    <div class="flex-1">
                                        <h3 class="text-xl font-bold text-gray-900"><?php echo htmlspecialchars($pin['pin_name']); ?></h3>
                                        <div class="flex gap-4 text-sm text-gray-600 mt-1">
                                            <span><i class="fas fa-microchip ml-1"></i> GPIO<?php echo $pin['pin_gpio']; ?></span>
                                            <span><i class="fas fa-tag ml-1"></i> <?php echo ucfirst($pin['pin_type']); ?></span>
                                            <?php if ($pin['pin_location']): ?>
                                                <span><i class="fas fa-map-marker-alt ml-1"></i> <?php echo htmlspecialchars($pin['pin_location']); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex gap-2">
                                    <button onclick="editPin(<?php echo htmlspecialchars(json_encode($pin)); ?>)" 
                                            class="btn bg-blue-600 text-white text-sm">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button onclick="deletePin(<?php echo $pin['id']; ?>, '<?php echo htmlspecialchars($pin['pin_name']); ?>')" 
                                            class="btn btn-danger text-sm">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Add/Edit Pin Modal -->
    <div id="pinModal" class="modal">
        <div class="modal-content p-8">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-2xl font-bold text-gray-900" id="modalTitle">إضافة Pin جديد</h3>
                <button onclick="closePinModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>

            <form id="pinForm" class="space-y-4">
                <input type="hidden" id="pin_id" name="pin_id">
                <input type="hidden" name="device_id" value="<?php echo $device_id; ?>">

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">اختر GPIO Pin *</label>
                    <select name="pin_gpio" id="pin_gpio" required class="input-field">
                        <option value="">-- اختر Pin --</option>
                        <?php foreach ($available_gpios as $gpio): ?>
                            <option value="<?php echo $gpio; ?>">
                                GPIO<?php echo $gpio; ?> (D<?php echo array_search($gpio, [16=>0,5=>1,4=>2,0=>3,2=>4,14=>5,12=>6,13=>7,15=>8]); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">اسم Pin *</label>
                    <input type="text" name="pin_name" id="pin_name" required class="input-field" 
                           placeholder="مثال: إضاءة غرفة النوم">
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">نوع Pin *</label>
                    <select name="pin_type" id="pin_type" required class="input-field">
                        <option value="relay">Relay (ريلاي - للتحكم)</option>
                        <option value="sensor">Sensor (حساس)</option>
                        <option value="led">LED (ليد)</option>
                        <option value="button">Button (زر)</option>
                        <option value="pwm">PWM (تعتيم)</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">الموقع</label>
                    <input type="text" name="pin_location" id="pin_location" class="input-field" 
                           placeholder="مثال: غرفة النوم">
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">اختر أيقونة</label>
                    <div class="icon-grid" id="iconGrid">
                        <?php
                        $icons = [
                            'fa-lightbulb' => 'لمبة',
                            'fa-fan' => 'مروحة',
                            'fa-door-open' => 'باب',
                            'fa-thermometer-half' => 'حرارة',
                            'fa-walking' => 'حركة',
                            'fa-tree' => 'حديقة',
                            'fa-lock' => 'قفل',
                            'fa-bell' => 'جرس',
                            'fa-tv' => 'تلفاز',
                            'fa-wind' => 'مكيف',
                            'fa-fire' => 'سخان',
                            'fa-water' => 'مضخة'
                        ];
                        foreach ($icons as $icon => $label): ?>
                            <div class="icon-btn" onclick="selectIcon('<?php echo $icon; ?>')" data-icon="<?php echo $icon; ?>">
                                <i class="fas <?php echo $icon; ?> text-2xl"></i>
                                <p class="text-xs mt-1"><?php echo $label; ?></p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <input type="hidden" name="pin_icon" id="pin_icon" value="fa-plug">
                </div>

                <div class="flex gap-3 pt-4">
                    <button type="submit" class="flex-1 btn btn-success py-3">
                        <i class="fas fa-save ml-2"></i>
                        <span id="submitText">حفظ Pin</span>
                    </button>
                    <button type="button" onclick="closePinModal()" class="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-bold">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
    let editMode = false;

    function openAddPinModal() {
        editMode = false;
        document.getElementById('modalTitle').textContent = 'إضافة Pin جديد';
        document.getElementById('submitText').textContent = 'حفظ Pin';
        document.getElementById('pinForm').reset();
        document.getElementById('pin_id').value = '';
        document.getElementById('pinModal').classList.add('active');
    }

    function closePinModal() {
        document.getElementById('pinModal').classList.remove('active');
    }

    function selectIcon(icon) {
        document.querySelectorAll('.icon-btn').forEach(btn => btn.classList.remove('selected'));
        document.querySelector(`[data-icon="${icon}"]`).classList.add('selected');
        document.getElementById('pin_icon').value = icon;
    }

    function editPin(pin) {
        editMode = true;
        document.getElementById('modalTitle').textContent = 'تعديل Pin';
        document.getElementById('submitText').textContent = 'تحديث Pin';
        document.getElementById('pin_id').value = pin.id;
        document.getElementById('pin_gpio').value = pin.pin_gpio;
        document.getElementById('pin_name').value = pin.pin_name;
        document.getElementById('pin_type').value = pin.pin_type;
        document.getElementById('pin_location').value = pin.pin_location || '';
        document.getElementById('pin_icon').value = pin.pin_icon;
        selectIcon(pin.pin_icon);
        document.getElementById('pinModal').classList.add('active');
    }

    async function deletePin(pinId, pinName) {
        if (!confirm(`هل أنت متأكد من حذف Pin "${pinName}"؟`)) return;

        try {
            const response = await fetch('../../api/iot/pin_control.php', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pin_id: pinId })
            });
            const result = await response.json();

            if (result.success) {
                alert('✅ تم حذف Pin بنجاح!');
                location.reload();
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    }

    document.getElementById('pinForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);

        try {
            const url = '../../api/iot/pin_control.php';
            const method = editMode ? 'PUT' : 'POST';
            
            const response = await fetch(url, {
                method: method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await response.json();

            if (result.success) {
                alert(editMode ? '✅ تم تحديث Pin بنجاح!' : '✅ تم إضافة Pin بنجاح!');
                location.reload();
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    });
    </script>
</body>
</html>
