<?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() {
    $headers = getallheaders();
    $auth_header = $headers['Authorization'] ?? '';
    
    if (!$auth_header) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    
    // Session kontrolü
    session_start();
    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    
    return $_SESSION['user_id'];
}

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

// Log seviyesini formatla
function formatLogLevel($level) {
    $levels = [
        'ERROR' => 'error',
        'WARNING' => 'warning',
        'INFO' => 'info',
        'DEBUG' => 'debug'
    ];
    
    return $levels[strtoupper($level)] ?? 'info';
}

// Ana route handler
$action = getParameter('action');
$user_id = authenticate();

switch ($action) {
    case 'list':
        echo json_encode(getDeviceLogs());
        break;
        
    case 'export':
        exportDeviceLogs();
        break;
        
    case 'clear':
        clearDeviceLogs();
        break;
        
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        break;
}

function getDeviceLogs() {
    global $con;
    
    $page = (int)getParameter('page', 1);
    $limit = (int)getParameter('limit', 50);
    $offset = ($page - 1) * $limit;
    
    $device_id = getParameter('device_id', '');
    $level = getParameter('level', '');
    $date_from = getParameter('date_from', '');
    $date_to = getParameter('date_to', '');
    $search = getParameter('search', '');
    
    // WHERE koşulları
    $where_conditions = [];
    $params = [];
    
    if (!empty($device_id)) {
        $where_conditions[] = "dl.device_id = ?";
        $params[] = $device_id;
    }
    
    if (!empty($level)) {
        $where_conditions[] = "dl.level = ?";
        $params[] = $level;
    }
    
    if (!empty($date_from)) {
        $where_conditions[] = "dl.created_at >= ?";
        $params[] = $date_from . ' 00:00:00';
    }
    
    if (!empty($date_to)) {
        $where_conditions[] = "dl.created_at <= ?";
        $params[] = $date_to . ' 23:59:59';
    }
    
    if (!empty($search)) {
        $where_conditions[] = "dl.message LIKE ?";
        $params[] = '%' . $search . '%';
    }
    
    $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
    
    // Toplam sayı
    $count_sql = "
        SELECT COUNT(*) as total
        FROM device_logs dl
        LEFT JOIN devices d ON dl.device_id = d.id
        LEFT JOIN users u ON dl.user_id = u.id
        $where_clause
    ";
    
    $stmt = $con->prepare($count_sql);
    if (!empty($params)) {
        $stmt->bind_param(str_repeat('s', count($params)), ...$params);
    }
    $stmt->execute();
    $total_logs = $stmt->fetch_assoc()['total'];
    
    // Logları getir
    $sql = "
        SELECT 
            dl.*,
            d.name as device_name,
            d.device_id as device_code,
            u.username as user_name
        FROM device_logs dl
        LEFT JOIN devices d ON dl.device_id = d.id
        LEFT JOIN users u ON dl.user_id = u.id
        $where_clause
        ORDER BY dl.created_at DESC
        LIMIT ? OFFSET ?
    ";
    
    $stmt = $con->prepare($sql);
    if (!empty($params)) {
        $param_types = str_repeat('s', count($params)) . 'ii';
        $all_params = array_merge($params, [$limit, $offset]);
        $stmt->bind_param($param_types, ...$all_params);
    } else {
        $stmt->bind_param('ii', $limit, $offset);
    }
    $stmt->execute();
    
    $logs = [];
    while ($row = $stmt->fetch_assoc()) {
        $logs[] = [
            'id' => $row['id'],
            'device_id' => $row['device_id'],
            'device_name' => $row['device_name'],
            'device_code' => $row['device_code'],
            'user_id' => $row['user_id'],
            'user_name' => $row['user_name'],
            'level' => $row['level'],
            'message' => $row['message'],
            'context' => json_decode($row['context'], true),
            'ip_address' => $row['ip_address'],
            'user_agent' => $row['user_agent'],
            'created_at' => $row['created_at']
        ];
    }
    
    // İstatistikler
    $stats_sql = "
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN level = 'ERROR' THEN 1 ELSE 0 END) as error,
            SUM(CASE WHEN level = 'WARNING' THEN 1 ELSE 0 END) as warning,
            SUM(CASE WHEN level = 'INFO' THEN 1 ELSE 0 END) as info,
            SUM(CASE WHEN level = 'DEBUG' THEN 1 ELSE 0 END) as debug
        FROM device_logs dl
        $where_clause
    ";
    
    $stmt = $con->prepare($stats_sql);
    if (!empty($params)) {
        $stmt->bind_param(str_repeat('s', count($params)), ...$params);
    }
    $stmt->execute();
    $stats = $stmt->fetch_assoc();
    
    return [
        'logs' => $logs,
        'stats' => $stats,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => ceil($total_logs / $limit),
            'total_logs' => $total_logs,
            'limit' => $limit
        ]
    ];
}

function exportDeviceLogs() {
    global $con;
    
    $format = getParameter('format', 'csv');
    $device_id = getParameter('device_id', '');
    $level = getParameter('level', '');
    $date_from = getParameter('date_from', '');
    $date_to = getParameter('date_to', '');
    $search = getParameter('search', '');
    
    // WHERE koşulları
    $where_conditions = [];
    $params = [];
    
    if (!empty($device_id)) {
        $where_conditions[] = "dl.device_id = ?";
        $params[] = $device_id;
    }
    
    if (!empty($level)) {
        $where_conditions[] = "dl.level = ?";
        $params[] = $level;
    }
    
    if (!empty($date_from)) {
        $where_conditions[] = "dl.created_at >= ?";
        $params[] = $date_from . ' 00:00:00';
    }
    
    if (!empty($date_to)) {
        $where_conditions[] = "dl.created_at <= ?";
        $params[] = $date_to . ' 23:59:59';
    }
    
    if (!empty($search)) {
        $where_conditions[] = "dl.message LIKE ?";
        $params[] = '%' . $search . '%';
    }
    
    $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
    
    // Logları getir
    $sql = "
        SELECT 
            dl.*,
            d.name as device_name,
            d.device_id as device_code,
            u.username as user_name
        FROM device_logs dl
        LEFT JOIN devices d ON dl.device_id = d.id
        LEFT JOIN users u ON dl.user_id = u.id
        $where_clause
        ORDER BY dl.created_at DESC
    ";
    
    $stmt = $con->prepare($sql);
    if (!empty($params)) {
        $stmt->bind_param(str_repeat('s', count($params)), ...$params);
    }
    $stmt->execute();
    
    $logs = [];
    while ($row = $stmt->fetch_assoc()) {
        $logs[] = $row;
    }
    
    // Format göre dışa aktar
    switch ($format) {
        case 'csv':
            exportAsCSV($logs);
            break;
        case 'json':
            exportAsJSON($logs);
            break;
        case 'txt':
            exportAsTXT($logs);
            break;
        default:
            exportAsCSV($logs);
            break;
    }
}

function exportAsCSV($logs) {
    $filename = 'device_logs_' . date('Y-m-d_H-i-s') . '.csv';
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    $output = fopen('php://output', 'w');
    
    // Başlık satırı
    fputcsv($output, [
        'ID',
        'Cihaz Adı',
        'Cihaz Kodu',
        'Kullanıcı',
        'Seviye',
        'Mesaj',
        'IP Adresi',
        'Tarih'
    ]);
    
    // Veri satırları
    foreach ($logs as $log) {
        fputcsv($output, [
            $log['id'],
            $log['device_name'],
            $log['device_code'],
            $log['user_name'],
            $log['level'],
            $log['message'],
            $log['ip_address'],
            $log['created_at']
        ]);
    }
    
    fclose($output);
}

function exportAsJSON($logs) {
    $filename = 'device_logs_' . date('Y-m-d_H-i-s') . '.json';
    
    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    echo json_encode([
        'export_date' => date('Y-m-d H:i:s'),
        'total_logs' => count($logs),
        'logs' => $logs
    ], JSON_PRETTY_PRINT);
}

function exportAsTXT($logs) {
    $filename = 'device_logs_' . date('Y-m-d_H-i-s') . '.txt';
    
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    echo "Cihaz Logları\n";
    echo "Dışa Aktarma Tarihi: " . date('Y-m-d H:i:s') . "\n";
    echo "Toplam Log Sayısı: " . count($logs) . "\n";
    echo str_repeat("=", 80) . "\n\n";
    
    foreach ($logs as $log) {
        echo "[" . $log['created_at'] . "] ";
        echo "[" . $log['level'] . "] ";
        echo "Cihaz: " . $log['device_name'] . " (" . $log['device_code'] . ") ";
        echo "Kullanıcı: " . $log['user_name'] . "\n";
        echo "Mesaj: " . $log['message'] . "\n";
        echo "IP: " . $log['ip_address'] . "\n";
        echo str_repeat("-", 80) . "\n\n";
    }
}

function clearDeviceLogs() {
    global $con;
    
    $device_id = getParameter('device_id', '');
    $level = getParameter('level', '');
    $date_from = getParameter('date_from', '');
    $date_to = getParameter('date_to', '');
    
    // WHERE koşulları
    $where_conditions = [];
    $params = [];
    
    if (!empty($device_id)) {
        $where_conditions[] = "device_id = ?";
        $params[] = $device_id;
    }
    
    if (!empty($level)) {
        $where_conditions[] = "level = ?";
        $params[] = $level;
    }
    
    if (!empty($date_from)) {
        $where_conditions[] = "created_at >= ?";
        $params[] = $date_from . ' 00:00:00';
    }
    
    if (!empty($date_to)) {
        $where_conditions[] = "created_at <= ?";
        $params[] = $date_to . ' 23:59:59';
    }
    
    $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
    
    // Logları sil
    $sql = "DELETE FROM device_logs $where_clause";
    
    $stmt = $con->prepare($sql);
    if (!empty($params)) {
        $stmt->bind_param(str_repeat('s', count($params)), ...$params);
    }
    
    if ($stmt->execute()) {
        $deleted_rows = $stmt->affected_rows;
        echo json_encode([
            'success' => true,
            'message' => "$deleted_rows log kaydı silindi"
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'error' => 'Loglar silinemedi'
        ]);
    }
}
?>
