<?php
session_start();
require_once 'config/database.php';

// Get user info
$user_id = $_SESSION['user_id'];
$sql = "SELECT username, email, role FROM users WHERE id = $user_id";
$result = $con->query($sql);
$user = $result ? $result->fetch_assoc() : null;

// If user not found, create empty user array to prevent sidebar errors
if (!$user) {
    $user = [
        'username' => 'Unknown',
        'email' => '',
        'role' => 'user'
    ];
}

// Get system logs (admin sees all, user sees only their devices)
if ($user['role'] === 'admin') {
    $logs_sql = "SELECT sl.*, d.name as device_name 
               FROM system_logs sl 
               LEFT JOIN devices d ON sl.device_id = d.id 
               WHERE sl.log_level IN ('ERROR', 'CRITICAL')
               ORDER BY sl.created_at DESC 
               LIMIT 100";
} else {
    $logs_sql = "SELECT sl.*, d.name as device_name 
               FROM system_logs sl 
               LEFT JOIN devices d ON sl.device_id = d.id 
               WHERE sl.log_level IN ('ERROR', 'CRITICAL') AND d.owner_id = $user_id 
               ORDER BY sl.created_at DESC 
               LIMIT 100";
}
$logs_result = $con->query($logs_sql);
$error_logs = $logs_result ? $logs_result->fetch_all(MYSQLI_ASSOC) : [];

// Layout variables
$page_title = 'Hata Logları';
$breadcrumb_title = 'Hata Logları';
$current_page = 'error_logs';
$extra_css = '<link rel="stylesheet" href="assets/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">';
$page_scripts = '<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>';
?>

<?php require_once 'layouts/header.php'; ?>

<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <?php require_once 'layouts/navbar.php'; ?>
    <?php require_once 'layouts/sidebar.php'; ?>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <?php require_once 'layouts/header_dashboard.php'; ?>

        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-exclamation-triangle mr-1"></i>
                                Hata Logları
                            </h3>
                            <div class="card-tools">
                                <button class="btn btn-danger btn-sm" onclick="clearLogs()">
                                    <i class="fas fa-trash"></i> Logları Temizle
                                </button>
                                <button class="btn btn-success btn-sm" onclick="exportLogs()">
                                    <i class="fas fa-download"></i> Export
                                </button>
                            </div>
                        </div>
                        
                        <div class="card-body">
                            <!-- Statistics -->
                            <div class="row mb-4">
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-danger"><i class="fas fa-exclamation-triangle"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Toplam Hata</span>
                                            <span class="info-box-number"><?php echo count($error_logs); ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-warning"><i class="fas fa-exclamation-circle"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Bugün</span>
                                            <span class="info-box-number"><?php echo count(array_filter($error_logs, function($log) { return date('Y-m-d', strtotime($log['created_at'])) == date('Y-m-d'); })); ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-info"><i class="fas fa-microchip"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Etkilen Cihaz</span>
                                            <span class="info-box-number"><?php echo count(array_unique(array_column($error_logs, 'device_id'))); ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-secondary"><i class="fas fa-clock"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Son Hata</span>
                                            <span class="info-box-number"><?php echo $error_logs ? date('H:i', strtotime($error_logs[0]['created_at'])) : '-'; ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Error Logs Table -->
                            <table id="errorLogsTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Tarih</th>
                                        <th>Cihaz</th>
                                        <th>Kategori</th>
                                        <th>Mesaj</th>
                                        <th>Seviye</th>
                                        <th>İşlemler</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($error_logs as $log): ?>
                                    <tr>
                                        <td><?php echo date('d.m.Y H:i:s', strtotime($log['created_at'])); ?></td>
                                        <td><?php echo htmlspecialchars($log['device_name'] ?? 'Bilinmiyor'); ?></td>
                                        <td><?php echo htmlspecialchars($log['category']); ?></td>
                                        <td><?php echo htmlspecialchars($log['message']); ?></td>
                                        <td>
                                            <?php
                                            $level = $log['log_level'] ?? 'info';
                                            $class = [
                                                'CRITICAL' => 'danger',
                                                'ERROR' => 'danger', 
                                                'WARNING' => 'warning',
                                                'INFO' => 'info',
                                                'DEBUG' => 'secondary'
                                            ][$level] ?? 'secondary';
                                            ?>
                                            <span class="badge badge-<?php echo $class; ?>">
                                                <?php echo ucfirst($level); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-info" onclick="viewDetails(<?php echo $log['id']; ?>)">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#errorLogsTable').DataTable({
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "ordering": true,
        "info": true,
        "paging": true,
        "search": true,
        "order": [[0, "desc"]],
        "language": {
            "search": "Ara:",
            "lengthMenu": "Show _MENU_ entries",
            "info": "Showing _START_ to _END_ of _TOTAL_ entries",
            "paginate": {
                "first": "İlk",
                "last": "Son",
                "next": "Sonraki",
                "previous": "Önceki"
            }
        }
    });
});

function clearLogs() {
    if (confirm('Tüm hata loglarını temizlemek istediğinizden emin misiniz?')) {
        alert('Log temizleme özelliği yakında eklenecek!');
    }
}

function exportLogs() {
    alert('Export özelliği yakında eklenecek!');
}

function viewDetails(logId) {
    alert('Hata detayı gösterilecek: ' + logId);
}
</script>

<?php require_once 'layouts/footer.php'; ?>
