<?php
/**
 * Smart Door Lock System with PIN Code
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get devices with door locks
    $devices_query = "SELECT DISTINCT d.* 
                     FROM iot_devices d
                     INNER JOIN device_pins p ON d.device_id = p.device_id
                     WHERE p.pin_type IN ('lock', 'door', 'relay')
                     ORDER BY d.device_id";
    $devices_stmt = $db->query($devices_query);
    $devices = $devices_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $device = null;
    $lock_pin = null;
    
    if ($device_id) {
        // Get 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);
        
        // Get lock pin
        $lock_query = "SELECT * FROM device_pins 
                      WHERE device_id = ? AND pin_type IN ('lock', 'door', 'relay')
                      LIMIT 1";
        $lock_stmt = $db->prepare($lock_query);
        $lock_stmt->execute([$device_id]);
        $lock_pin = $lock_stmt->fetch(PDO::FETCH_ASSOC);
    }
    
} catch (Exception $e) {
    die('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>القفل الذكي - Smart Lock</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;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, #1e3a8a 0%, #1e40af 50%, #3b82f6 100%); 
            min-height: 100vh; 
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .lock-container { 
            background: white; 
            border-radius: 30px; 
            padding: 40px; 
            box-shadow: 0 30px 80px rgba(0,0,0,0.4);
            max-width: 500px;
            width: 100%;
        }
        .lock-icon { 
            font-size: 120px; 
            text-align: center; 
            margin-bottom: 30px;
            transition: all 0.3s;
        }
        .lock-icon.locked { color: #ef4444; }
        .lock-icon.unlocked { color: #10b981; }
        .pin-display {
            background: #f3f4f6;
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            font-size: 48px;
            font-weight: bold;
            letter-spacing: 20px;
            margin-bottom: 30px;
            min-height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 3px solid #e5e7eb;
        }
        .keypad {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }
        .key {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
            border: none;
            border-radius: 15px;
            padding: 25px;
            font-size: 32px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.2s;
            box-shadow: 0 5px 15px rgba(59, 130, 246, 0.3);
        }
        .key:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(59, 130, 246, 0.4);
        }
        .key:active {
            transform: translateY(0);
        }
        .key.clear {
            background: linear-gradient(135deg, #ef4444, #dc2626);
        }
        .key.enter {
            background: linear-gradient(135deg, #10b981, #059669);
            grid-column: span 2;
        }
        .status-message {
            text-align: center;
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            font-weight: bold;
            display: none;
        }
        .status-message.success {
            background: #d1fae5;
            color: #065f46;
            display: block;
        }
        .status-message.error {
            background: #fee2e2;
            color: #991b1b;
            display: block;
        }
        .access-log {
            margin-top: 30px;
            max-height: 200px;
            overflow-y: auto;
        }
        .log-entry {
            background: #f9fafb;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 14px;
        }
        .log-entry.success { border-right: 4px solid #10b981; }
        .log-entry.failed { border-right: 4px solid #ef4444; }
    </style>
</head>
<body>
    <?php if (!$device_id): ?>
    <!-- Device Selection -->
    <div class="lock-container">
        <h1 class="text-3xl font-bold text-center mb-6">
            <i class="fas fa-lock text-blue-600"></i>
            القفل الذكي
        </h1>
        <p class="text-center text-gray-600 mb-6">اختر الجهاز</p>
        
        <?php if (empty($devices)): ?>
        <div class="text-center py-8">
            <i class="fas fa-door-closed text-gray-300 text-6xl mb-4"></i>
            <p class="text-gray-500">لا توجد أقفال مُكوّنة</p>
        </div>
        <?php else: ?>
        <div class="space-y-3">
            <?php foreach ($devices as $dev): ?>
            <a href="?device_id=<?php echo $dev['device_id']; ?>" 
               class="block bg-gradient-to-r from-blue-50 to-blue-100 hover:from-blue-100 hover:to-blue-200 p-4 rounded-lg transition-all">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="font-bold text-gray-900"><?php echo htmlspecialchars($dev['device_name']); ?></h3>
                        <p class="text-sm text-gray-600"><?php echo $dev['device_id']; ?></p>
                    </div>
                    <i class="fas fa-chevron-left text-blue-600"></i>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        
        <a href="index.php" class="block text-center mt-6 text-blue-600 hover:text-blue-800">
            <i class="fas fa-arrow-right ml-2"></i>
            رجوع للرئيسية
        </a>
    </div>
    <?php else: ?>
    
    <!-- Smart Lock Interface -->
    <div class="lock-container">
        <div class="text-center mb-6">
            <h2 class="text-2xl font-bold text-gray-900"><?php echo htmlspecialchars($device['device_name']); ?></h2>
            <p class="text-gray-600 text-sm"><?php echo $device['device_id']; ?></p>
        </div>
        
        <div class="lock-icon locked" id="lockIcon">
            <i class="fas fa-lock"></i>
        </div>
        
        <div class="pin-display" id="pinDisplay">
            <span id="pinDots"></span>
        </div>
        
        <div class="keypad">
            <button class="key" onclick="addDigit('1')">1</button>
            <button class="key" onclick="addDigit('2')">2</button>
            <button class="key" onclick="addDigit('3')">3</button>
            <button class="key" onclick="addDigit('4')">4</button>
            <button class="key" onclick="addDigit('5')">5</button>
            <button class="key" onclick="addDigit('6')">6</button>
            <button class="key" onclick="addDigit('7')">7</button>
            <button class="key" onclick="addDigit('8')">8</button>
            <button class="key" onclick="addDigit('9')">9</button>
            <button class="key clear" onclick="clearPin()">
                <i class="fas fa-backspace"></i>
            </button>
            <button class="key" onclick="addDigit('0')">0</button>
            <button class="key enter" onclick="checkPin()">
                <i class="fas fa-check ml-2"></i>
                فتح
            </button>
        </div>
        
        <div class="status-message" id="statusMessage"></div>
        
        <div class="text-center mt-6">
            <p class="text-sm text-gray-600">
                <i class="fas fa-info-circle ml-1"></i>
                الرمز الافتراضي: <strong>1234</strong>
            </p>
            <a href="smart-lock.php" class="text-blue-600 hover:text-blue-800 text-sm mt-2 inline-block">
                <i class="fas fa-exchange-alt ml-1"></i>
                تغيير الجهاز
            </a>
        </div>
        
        <!-- Access Log -->
        <div class="access-log" id="accessLog">
            <h3 class="text-lg font-bold text-gray-900 mb-3">
                <i class="fas fa-history ml-2"></i>
                سجل الدخول
            </h3>
            <div id="logEntries"></div>
        </div>
    </div>
    
    <script>
    let pin = '';
    const correctPin = '1234'; // يمكن تغييره من قاعدة البيانات
    const deviceId = '<?php echo $device_id; ?>';
    const lockGpio = <?php echo $lock_pin['pin_gpio'] ?? 5; ?>;
    
    function addDigit(digit) {
        if (pin.length < 6) {
            pin += digit;
            updateDisplay();
        }
    }
    
    function clearPin() {
        pin = pin.slice(0, -1);
        updateDisplay();
    }
    
    function updateDisplay() {
        const dots = '●'.repeat(pin.length);
        document.getElementById('pinDots').textContent = dots || '----';
    }
    
    async function checkPin() {
        if (pin.length === 0) return;
        
        const statusMsg = document.getElementById('statusMessage');
        const lockIcon = document.getElementById('lockIcon');
        
        if (pin === correctPin) {
            // Correct PIN - Unlock door
            statusMsg.className = 'status-message success';
            statusMsg.innerHTML = '<i class="fas fa-check-circle ml-2"></i> تم فتح الباب بنجاح!';
            
            lockIcon.className = 'lock-icon unlocked';
            lockIcon.innerHTML = '<i class="fas fa-lock-open"></i>';
            
            // Send unlock command
            await sendUnlockCommand();
            
            // Add to log
            addLogEntry('فتح ناجح', true);
            
            // Auto-lock after 5 seconds
            setTimeout(() => {
                lockIcon.className = 'lock-icon locked';
                lockIcon.innerHTML = '<i class="fas fa-lock"></i>';
                sendLockCommand();
            }, 5000);
            
        } else {
            // Wrong PIN
            statusMsg.className = 'status-message error';
            statusMsg.innerHTML = '<i class="fas fa-times-circle ml-2"></i> رمز خاطئ! حاول مرة أخرى';
            
            // Shake animation
            document.querySelector('.lock-container').style.animation = 'shake 0.5s';
            setTimeout(() => {
                document.querySelector('.lock-container').style.animation = '';
            }, 500);
            
            addLogEntry('محاولة فاشلة', false);
        }
        
        pin = '';
        updateDisplay();
        
        setTimeout(() => {
            statusMsg.style.display = 'none';
        }, 3000);
    }
    
    async function sendUnlockCommand() {
        try {
            const formData = new FormData();
            formData.append('device_id', deviceId);
            formData.append('action', 'pin_control');
            formData.append('payload', JSON.stringify({
                gpio: lockGpio,
                state: 1
            }));
            
            await fetch('../../api/iot/commands.php', {
                method: 'POST',
                body: formData
            });
        } catch (error) {
            console.error('Failed to send unlock command:', error);
        }
    }
    
    async function sendLockCommand() {
        try {
            const formData = new FormData();
            formData.append('device_id', deviceId);
            formData.append('action', 'pin_control');
            formData.append('payload', JSON.stringify({
                gpio: lockGpio,
                state: 0
            }));
            
            await fetch('../../api/iot/commands.php', {
                method: 'POST',
                body: formData
            });
        } catch (error) {
            console.error('Failed to send lock command:', error);
        }
    }
    
    function addLogEntry(message, success) {
        const logEntries = document.getElementById('logEntries');
        const entry = document.createElement('div');
        entry.className = `log-entry ${success ? 'success' : 'failed'}`;
        
        const now = new Date().toLocaleTimeString('ar-EG');
        entry.innerHTML = `
            <span>${message}</span>
            <span class="text-gray-500">${now}</span>
        `;
        
        logEntries.insertBefore(entry, logEntries.firstChild);
        
        // Keep only last 10 entries
        while (logEntries.children.length > 10) {
            logEntries.removeChild(logEntries.lastChild);
        }
    }
    
    // Keyboard support
    document.addEventListener('keydown', (e) => {
        if (e.key >= '0' && e.key <= '9') {
            addDigit(e.key);
        } else if (e.key === 'Backspace') {
            clearPin();
        } else if (e.key === 'Enter') {
            checkPin();
        }
    });
    
    // Shake animation
    const style = document.createElement('style');
    style.textContent = `
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-10px); }
            75% { transform: translateX(10px); }
        }
    `;
    document.head.appendChild(style);
    
    updateDisplay();
    </script>
    <?php endif; ?>
</body>
</html>
