<?php
/**
 * Sensors Dashboard with Charts
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get devices
    $devices_query = "SELECT * FROM iot_devices ORDER BY device_id";
    $devices_stmt = $db->query($devices_query);
    $devices = $devices_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $device = null;
    $sensors = [];
    $sensor_data = [];
    
    if ($device_id) {
        // Get 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);
        
        // Get INPUT pins (sensors)
        $sensors_query = "SELECT * FROM device_pins WHERE device_id = ? AND pin_mode = 'INPUT' ORDER BY pin_gpio";
        $sensors_stmt = $db->prepare($sensors_query);
        $sensors_stmt->execute([$device_id]);
        $sensors = $sensors_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get sensor data for charts (last 50 readings)
        if ($sensor_id) {
            $data_query = "SELECT value, created_at 
                          FROM iot_sensors_data 
                          WHERE device_id = ? AND sensor_type = ?
                          ORDER BY created_at DESC 
                          LIMIT 50";
            $data_stmt = $db->prepare($data_query);
            $data_stmt->execute([$device_id, $sensor_id]);
            $sensor_data = array_reverse($data_stmt->fetchAll(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>لوحة الحساسات - IoT</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>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></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; }
        .sensor-card { background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%); border-radius: 15px; padding: 25px; border: 2px solid #bae6fd; transition: all 0.3s; cursor: pointer; }
        .sensor-card:hover { transform: translateY(-5px); box-shadow: 0 15px 40px rgba(0,0,0,0.15); border-color: #38bdf8; }
        .sensor-card.active { border-color: #0284c7; background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%); }
        .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; }
        .stat-box { background: linear-gradient(135deg, #3b82f6, #2563eb); color: white; padding: 20px; border-radius: 15px; text-align: center; }
        .chart-container { position: relative; height: 400px; }
    </style>
</head>
<body>
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <div class="card">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-chart-line text-blue-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">اختر الجهاز</h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <?php foreach ($devices as $dev): ?>
                <a href="?device_id=<?php echo $dev['device_id']; ?>" class="sensor-card block text-center">
                    <i class="fas fa-microchip text-6xl text-blue-600 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-900"><?php echo htmlspecialchars($dev['device_name']); ?></h3>
                    <p class="text-gray-600 text-sm"><?php echo $dev['device_id']; ?></p>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php else: ?>
        
        <!-- Device Info -->
        <div class="card">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-900">
                        <i class="fas fa-microchip ml-2"></i>
                        <?php echo htmlspecialchars($device['device_name']); ?>
                    </h2>
                    <p class="text-gray-600"><?php echo $device['device_id']; ?></p>
                </div>
                <a href="sensors.php" class="btn bg-gray-200 text-gray-800">
                    <i class="fas fa-exchange-alt ml-2"></i>
                    تغيير الجهاز
                </a>
            </div>
        </div>

        <?php if (empty($sensors)): ?>
        <div class="card text-center py-16">
            <i class="fas fa-sensor 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: ?>
        
        <!-- Sensors Grid -->
        <div class="card">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">
                <i class="fas fa-list ml-2"></i>
                الحساسات المتاحة
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <?php foreach ($sensors as $sensor): ?>
                <a href="?device_id=<?php echo $device_id; ?>&sensor_id=<?php echo $sensor['pin_type']; ?>" 
                   class="sensor-card <?php echo ($sensor_id === $sensor['pin_type']) ? 'active' : ''; ?>">
                    <i class="fas <?php echo $sensor['pin_icon']; ?> text-4xl text-blue-600 mb-3"></i>
                    <h3 class="text-lg font-bold text-gray-900"><?php echo htmlspecialchars($sensor['pin_name']); ?></h3>
                    <p class="text-sm text-gray-600">GPIO<?php echo $sensor['pin_gpio']; ?></p>
                    <p class="text-xs text-gray-500 mt-2"><?php echo ucfirst($sensor['pin_type']); ?></p>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if ($sensor_id): ?>
        <!-- Statistics -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
            <div class="stat-box">
                <i class="fas fa-chart-line text-4xl mb-2"></i>
                <p class="text-sm opacity-90">القيمة الحالية</p>
                <p class="text-3xl font-bold" id="currentValue">--</p>
            </div>
            <div class="stat-box" style="background: linear-gradient(135deg, #10b981, #059669);">
                <i class="fas fa-arrow-up text-4xl mb-2"></i>
                <p class="text-sm opacity-90">أعلى قيمة</p>
                <p class="text-3xl font-bold" id="maxValue">--</p>
            </div>
            <div class="stat-box" style="background: linear-gradient(135deg, #ef4444, #dc2626);">
                <i class="fas fa-arrow-down text-4xl mb-2"></i>
                <p class="text-sm opacity-90">أقل قيمة</p>
                <p class="text-3xl font-bold" id="minValue">--</p>
            </div>
            <div class="stat-box" style="background: linear-gradient(135deg, #f59e0b, #d97706);">
                <i class="fas fa-calculator text-4xl mb-2"></i>
                <p class="text-sm opacity-90">المتوسط</p>
                <p class="text-3xl font-bold" id="avgValue">--</p>
            </div>
        </div>

        <!-- Chart -->
        <div class="card">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold text-gray-900">
                    <i class="fas fa-chart-area ml-2"></i>
                    الرسم البياني
                </h2>
                <div class="flex gap-2">
                    <button onclick="changeChartType('line')" class="btn bg-blue-100 text-blue-800 text-sm">
                        <i class="fas fa-chart-line ml-1"></i>
                        خطي
                    </button>
                    <button onclick="changeChartType('bar')" class="btn bg-green-100 text-green-800 text-sm">
                        <i class="fas fa-chart-bar ml-1"></i>
                        أعمدة
                    </button>
                </div>
            </div>
            <div class="chart-container">
                <canvas id="sensorChart"></canvas>
            </div>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
        <?php endif; ?>
    </div>

    <script>
    let chart = null;
    const sensorData = <?php echo json_encode($sensor_data); ?>;
    
    function initChart(type = 'line') {
        if (chart) chart.destroy();
        
        const ctx = document.getElementById('sensorChart').getContext('2d');
        const labels = sensorData.map(d => new Date(d.created_at).toLocaleTimeString('ar-EG'));
        const values = sensorData.map(d => parseFloat(d.value));
        
        // Calculate statistics
        if (values.length > 0) {
            document.getElementById('currentValue').textContent = values[values.length - 1].toFixed(2);
            document.getElementById('maxValue').textContent = Math.max(...values).toFixed(2);
            document.getElementById('minValue').textContent = Math.min(...values).toFixed(2);
            document.getElementById('avgValue').textContent = (values.reduce((a,b) => a+b, 0) / values.length).toFixed(2);
        }
        
        chart = new Chart(ctx, {
            type: type,
            data: {
                labels: labels,
                datasets: [{
                    label: 'القيمة',
                    data: values,
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }
    
    function changeChartType(type) {
        initChart(type);
    }
    
    // Auto-refresh every 5 seconds
    <?php if ($sensor_id): ?>
    initChart();
    setInterval(() => {
        location.reload();
    }, 5000);
    <?php endif; ?>
    </script>
</body>
</html>
