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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Kullanıcı kimlik doğrulaması
function authenticate() {
    session_start();
    
    if (!isset($_SESSION['user_id'])) {
        return null;
    }
    
    return $_SESSION['user_id'];
}

// İstek parametresini al
function getParameter($param, $default = null) {
    return $_GET[$param] ?? $_POST[$param] ?? $default;
}

// Tarih aralığını formatla
function formatDateRange($dateFrom, $dateTo) {
    $from = new DateTime($dateFrom);
    $to = new DateTime($dateTo);
    
    return [
        'from' => $from->format('Y-m-d H:i:s'),
        'to' => $to->format('Y-m-d H:i:s'),
        'display' => $from->format('d.m.Y') . ' - ' . $to->format('d.m.Y')
    ];
}

// Ana analitik verileri
function getAnalyticsStats($period) {
    global $con;
    $user_id = authenticate();
    if (!$user_id) {
        return ['error' => 'Unauthorized'];
    }
    
    $dateRange = formatDateRange(
        getParameter('date_from', date('Y-m-d', strtotime('-7 days'))),
        getParameter('date_to', date('Y-m-d'))
    );
    
    // Toplam cihazlar
    $stmt = $con->prepare("SELECT COUNT(*) as total FROM devices");
    $stmt->execute();
    $totalDevices = ($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    
    // Aktif cihazlar
    $stmt = $con->prepare("SELECT COUNT(*) as active FROM devices WHERE status = 'online'");
    $stmt->execute();
    $activeDevices = ($stmt->get_result()->fetch_assoc()['active'] ?? 0);
    
    // Toplam kullanıcılar
    $stmt = $con->prepare("SELECT COUNT(*) as total FROM users");
    $stmt->execute();
    $totalUsers = ($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    
    // Toplam sensörler
    $stmt = $con->prepare("SELECT COUNT(DISTINCT sensor_code) as total FROM sensor_data WHERE timestamp >= ? AND timestamp <= ?");
    $stmt->bind_param("ss", $dateRange['from'], $dateRange['to']);
    $stmt->execute();
    $totalSensors = ($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    
    // Veri noktaları
    $stmt = $con->prepare("SELECT COUNT(*) as total FROM sensor_data WHERE timestamp >= ? AND timestamp <= ?");
    $stmt->bind_param("ss", $dateRange['from'], $dateRange['to']);
    $stmt->execute();
    $dataPoints = ($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    
    // Ortal yanıt süresi (basit hesaplama)
    $stmt = $con->prepare("
        SELECT AVG(TIMESTAMPDIFF(SECOND, created_at, updated_at)) as avg_response 
        FROM device_events 
        WHERE created_at >= ? AND created_at <= ? AND status = 'completed'
    ");
    $stmt->bind_param("ss", $dateRange['from'], $dateRange['to']);
    $stmt->execute();
    $avgResponse = ($stmt->get_result()->fetch_assoc()['avg_response'] ?? 0);
    
    return [
        'total_devices' => $totalDevices,
        'active_devices' => $activeDevices,
        'total_users' => $totalUsers,
        'total_sensors' => $totalSensors,
        'data_points' => $dataPoints,
        'avg_response_time' => round($avgResponse, 2),
        'date_range' => $dateRange['display']
    ];
}

// Cihaz grafiği verileri
function getDeviceChart($period) {
    global $con;
    $user_id = authenticate();
    if (!$user_id) {
        return ['error' => 'Unauthorized'];
    }
    
    $dateRange = formatDateRange(
        getParameter('date_from', date('Y-m-d', strtotime('-7 days'))),
        getParameter('date_to', date('Y-m-d'))
    );
    
    // Son 7 günlük cihaz durumu verileri
    $stmt = $con->prepare("
        SELECT 
            DATE_FORMAT(last_seen, '%Y-%m-%d %H:00') as label,
            SUM(CASE WHEN status = 'online' THEN 1 ELSE 0 END) as active_devices,
            SUM(CASE WHEN status = 'offline' THEN 1 ELSE 0 END) as offline_devices
        FROM devices 
        WHERE last_seen >= ? AND last_seen <= ?
        GROUP BY DATE_FORMAT(last_seen, '%Y-%m-%d %H:00')
        ORDER BY label
    ");
    $stmt->bind_param("ss", $dateRange['from'], $dateRange['to']);
    $stmt->execute();
    
    $data = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $data[] = [
            'label' => $row['label'],
            'active_devices' => (int)$row['active_devices'],
            'offline_devices' => (int)$row['offline_devices']
        ];
    }
    
    // Eğer veri yoksa, son 7 gün için örnek veri oluştur
    if (empty($data)) {
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d H:00', strtotime("-$i days"));
            $data[] = [
                'label' => $date,
                'active_devices' => rand(5, 15),
                'offline_devices' => rand(1, 5)
            ];
        }
    }
    
    return [
        'labels' => array_column($data, 'label'),
        'active_devices' => array_column($data, 'active_devices'),
        'offline_devices' => array_column($data, 'offline_devices')
    ];
}

// Sensör grafiği verileri
function getSensorChart($period) {
    global $con;
    $user_id = authenticate();
    if (!$user_id) {
        return ['error' => 'Unauthorized'];
    }
    
    $dateRange = formatDateRange(
        getParameter('date_from', date('Y-m-d', strtotime('-7 days'))),
        getParameter('date_to', date('Y-m-d'))
    );
    
    // Son sensör verileri
    $stmt = $con->prepare("
        SELECT 
            DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i:%s') as label,
            sensor_code,
            AVG(value) as value
        FROM sensor_data 
        WHERE timestamp >= ? AND timestamp <= ?
        GROUP BY DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i:%s'), sensor_code
        ORDER BY label
    ");
    $stmt->bind_param("ss", $dateRange['from'], $dateRange['to']);
    $stmt->execute();
    
    $data = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        if (!isset($data[$row['sensor_code']])) {
            $data[$row['sensor_code']] = [
                'labels' => [],
                'temperature' => [],
                'humidity' => [],
                'pressure' => [],
                'voltage' => [],
                'current' => [],
                'power' => []
            ];
        }
        
        $data[$row['sensor_code']]['labels'][] = $row['label'];
        
        // Sensör tipine göre veriyi ayır
        if (strpos($row['sensor_code'], 'TEMP') !== false) {
            $data[$row['sensor_code']]['temperature'][] = $row['value'];
        } elseif (strpos($row['sensor_code'], 'HUM') !== false) {
            $data[$row['sensor_code']]['humidity'][] = $row['value'];
        } elseif (strpos($row['sensor_code'], 'PRESS') !== false) {
            $data[$row['sensor_code']]['pressure'][] = $row['value'];
        } elseif (strpos($row['sensor_code'], 'VOLT') !== false) {
            $data[$row['sensor_code']]['voltage'][] = $row['value'];
        } elseif (strpos($row['sensor_code'], 'CURR') !== false) {
            $data[$row['sensor_code']]['current'][] = $row['value'];
        } elseif (strpos($row['sensor_code'], 'POWER') !== false) {
            $data[$row['sensor_code']]['power'][] = $row['value'];
        }
    }
    
    // Ortal değerleri hesapla
    $result = [];
    foreach ($data as $sensorCode => $sensorData) {
        $result[] = [
            'labels' => $sensorData['labels'],
            'temperature' => array_map('floatval', $sensorData['temperature']),
            'humidity' => array_map('floatval', $sensorData['humidity']),
            'pressure' => array_map('floatval', $sensorData['pressure']),
            'voltage' => array_map('floatval', $sensorData['voltage']),
            'current' => array_map('floatval', $sensorData['current']),
            'power' => array_map('floatval', $sensorData['power'])
        ];
    }
    
    return $result;
}

// Kullanıcı grafiği verileri
function getUserChart($period) {
    global $con;
    $user_id = authenticate();
    if (!$user_id) {
        return ['error' => 'Unauthorized'];
    }
    
    $dateRange = formatDateRange(
        getParameter('date_from', date('Y-m-d', strtotime('-7 days'))),
        getParameter('date_to', date('Y-m-d'))
    );
    
    // Kullanıcı dağılımı
    $stmt = $con->prepare("
        SELECT 
            u.role,
            COUNT(*) as count
        FROM users u
        WHERE u.created_at >= ? AND u.created_at <= ?
        GROUP BY u.role
    ");
    $stmt->bind_param("ss", $dateRange['from'], $dateRange['to']);
    $stmt->execute();
    
    $data = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $data[] = [
            'label' => ucfirst($row['role']),
            'value' => (int)$row['count']
        ];
    }
    
    return [
        'labels' => array_column($data, 'label'),
        'values' => array_column($data, 'value')
    ];
}

// Ana route handler
$action = getParameter('action');
$period = getParameter('period', 'week');

switch ($action) {
    case 'stats':
        echo json_encode(getAnalyticsStats($period));
        break;
        
    case 'device_chart':
        echo json_encode(getDeviceChart($period));
        break;
        
    case 'sensor_chart':
        echo json_encode(getSensorChart($period));
        break;
        
    case 'user_chart':
        echo json_encode(getUserChart($period));
        break;
        
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        break;
}
?>
