<?php 
include 'koneksi.php';

// ========== SESSION CHECK DIPERKUAT ==========
if(!isset($_SESSION['user'])) {
    header("Location: index.php?error=session_expired");
    exit();
}

// Cek apakah session sudah terlalu lama (30 menit = 1800 detik)
if(isset($_SESSION['login_time']) && (time() - $_SESSION['login_time'] > 1800)) {
    session_destroy();
    header("Location: index.php?error=session_timeout");
    exit();
}

// Update last activity
$_SESSION['login_time'] = time();

// Cek IP address (opsional, untuk keamanan)
if(isset($_SESSION['ip_address']) && $_SESSION['ip_address'] != $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    header("Location: index.php?error=ip_mismatch");
    exit();
}

$user = $_SESSION['user'];
$role = $user['role'];
$unit = $user['unit'];
$user_id = $user['id'];

// ========== FUNGSI FILTER BERDASARKAN ROLE ==========
function getFilterCondition($role, $unit, $user_id) {
    if($role == 'Super Admin') {
        return "1=1";
    } elseif($role == 'Pimpinan') {
        return "1=1";
    } elseif($role == 'Kepala') {
        return "unit = '$unit'";
    } elseif($role == 'Guru') {
        return "teacher_id = '$user_id'";
    }
    return "1=1";
}

$filter = getFilterCondition($role, $unit, $user_id);

// ========== STATISTIK DASHBOARD ==========

// Total Guru
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $total_guru = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE role='Guru'"))['total'];
} elseif($role == 'Kepala') {
    $total_guru = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE role='Guru' AND unit='$unit'"))['total'];
} else {
    $total_guru = 0;
}

// Total Siswa
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $total_siswa = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM students"))['total'];
} elseif($role == 'Kepala') {
    $total_siswa = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM students WHERE unit='$unit'"))['total'];
} elseif($role == 'Guru') {
    $total_siswa = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM students WHERE unit='$unit'"))['total'];
} else {
    $total_siswa = 0;
}

// Total Kelas
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $total_kelas = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM classes"))['total'];
} elseif($role == 'Kepala') {
    $total_kelas = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM classes WHERE unit='$unit'"))['total'];
} else {
    $total_kelas = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM classes WHERE unit='$unit'"))['total'];
}

// Total Jurnal
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $total_jurnal = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM teaching_journals"))['total'];
} elseif($role == 'Kepala') {
    $total_jurnal = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM teaching_journals tj JOIN classes c ON tj.class_id=c.id WHERE c.unit='$unit'"))['total'];
} elseif($role == 'Guru') {
    $total_jurnal = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM teaching_journals WHERE teacher_id='$user_id'"))['total'];
} else {
    $total_jurnal = 0;
}

// Total Supervisi
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $total_supervisi = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM supervisions"))['total'];
} elseif($role == 'Kepala') {
    $total_supervisi = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM supervisions s JOIN users u ON s.teacher_id=u.id WHERE u.unit='$unit'"))['total'];
} elseif($role == 'Guru') {
    $total_supervisi = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM supervisions WHERE teacher_id='$user_id'"))['total'];
} else {
    $total_supervisi = 0;
}

// Absensi Hari Ini
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $hadir_hari_ini = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM attendance WHERE date=CURDATE() AND status='Hadir'"))['total'];
} elseif($role == 'Kepala') {
    $hadir_hari_ini = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM attendance a JOIN students s ON a.student_id=s.id WHERE a.date=CURDATE() AND a.status='Hadir' AND s.unit='$unit'"))['total'];
} elseif($role == 'Guru') {
    $hadir_hari_ini = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM attendance WHERE date=CURDATE() AND status='Hadir' AND teacher_id='$user_id'"))['total'];
} else {
    $hadir_hari_ini = 0;
}

// Data untuk chart Jurnal
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $chart_query = "SELECT DATE(date) as tgl, COUNT(*) as total FROM teaching_journals GROUP BY DATE(date) ORDER BY tgl DESC LIMIT 7";
} elseif($role == 'Kepala') {
    $chart_query = "SELECT DATE(tj.date) as tgl, COUNT(*) as total FROM teaching_journals tj JOIN classes c ON tj.class_id=c.id WHERE c.unit='$unit' GROUP BY DATE(tj.date) ORDER BY tgl DESC LIMIT 7";
} elseif($role == 'Guru') {
    $chart_query = "SELECT DATE(date) as tgl, COUNT(*) as total FROM teaching_journals WHERE teacher_id='$user_id' GROUP BY DATE(date) ORDER BY tgl DESC LIMIT 7";
} else {
    $chart_query = "SELECT DATE(date) as tgl, COUNT(*) as total FROM teaching_journals GROUP BY DATE(date) ORDER BY tgl DESC LIMIT 7";
}

$chart_data = mysqli_query($conn, $chart_query);
$jurnal_labels = [];
$jurnal_values = [];
while($row = mysqli_fetch_assoc($chart_data)) {
    $jurnal_labels[] = date('d M', strtotime($row['tgl']));
    $jurnal_values[] = $row['total'];
}
$jurnal_labels = array_reverse($jurnal_labels);
$jurnal_values = array_reverse($jurnal_values);

// Data untuk chart Pencapaian Target (untuk Guru)
if($role == 'Guru') {
    $target_query = "SELECT keterangan_target, COUNT(*) as total FROM teaching_journals WHERE teacher_id='$user_id' GROUP BY keterangan_target LIMIT 5";
    $target_data = mysqli_query($conn, $target_query);
    $target_labels = [];
    $target_values = [];
    while($row = mysqli_fetch_assoc($target_data)) {
        $target_labels[] = substr($row['keterangan_target'], 0, 20);
        $target_values[] = $row['total'];
    }
}

// Aktivitas Terbaru
if($role == 'Super Admin' || $role == 'Pimpinan') {
    $aktivitas_query = "SELECT 'Jurnal Mengajar' as activity, tj.date as waktu, u.full_name FROM teaching_journals tj JOIN users u ON tj.teacher_id=u.id ORDER BY tj.date DESC LIMIT 5";
} elseif($role == 'Kepala') {
    $aktivitas_query = "SELECT 'Jurnal Mengajar' as activity, tj.date as waktu, u.full_name FROM teaching_journals tj JOIN users u ON tj.teacher_id=u.id JOIN classes c ON tj.class_id=c.id WHERE c.unit='$unit' ORDER BY tj.date DESC LIMIT 5";
} elseif($role == 'Guru') {
    $aktivitas_query = "SELECT 'Jurnal Mengajar' as activity, date as waktu, 'Anda' as full_name FROM teaching_journals WHERE teacher_id='$user_id' ORDER BY date DESC LIMIT 5";
} else {
    $aktivitas_query = "SELECT 'Jurnal Mengajar' as activity, tj.date as waktu, u.full_name FROM teaching_journals tj JOIN users u ON tj.teacher_id=u.id ORDER BY tj.date DESC LIMIT 5";
}
$aktivitas = mysqli_query($conn, $aktivitas_query);

// Notifikasi
$notifikasi = [];
if($role == 'Kepala') {
    $cek_supervisi = mysqli_query($conn, "SELECT COUNT(*) as total FROM supervisions s JOIN users u ON s.teacher_id=u.id WHERE u.unit='$unit' AND s.schedule_date = CURDATE()");
    $supervisi_hari_ini = mysqli_fetch_assoc($cek_supervisi)['total'];
    if($supervisi_hari_ini > 0) {
        $notifikasi[] = "📅 Ada $supervisi_hari_ini jadwal supervisi hari ini!";
    }
    
    $cek_jurnal = mysqli_query($conn, "SELECT COUNT(DISTINCT teacher_id) as total FROM teaching_journals WHERE date = CURDATE()");
    $guru_isi_jurnal = mysqli_fetch_assoc($cek_jurnal)['total'];
    $total_guru_unit = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE role='Guru' AND unit='$unit'"))['total'];
    $guru_belum_jurnal = $total_guru_unit - $guru_isi_jurnal;
    if($guru_belum_jurnal > 0) {
        $notifikasi[] = "⚠️ $guru_belum_jurnal guru belum mengisi jurnal hari ini!";
    }
} elseif($role == 'Guru') {
    $cek_supervisi = mysqli_query($conn, "SELECT COUNT(*) as total FROM supervisions WHERE teacher_id='$user_id' AND schedule_date = CURDATE()");
    $supervisi_hari_ini = mysqli_fetch_assoc($cek_supervisi)['total'];
    if($supervisi_hari_ini > 0) {
        $notifikasi[] = "📅 Anda memiliki jadwal supervisi hari ini!";
    }
    
    $cek_jurnal = mysqli_query($conn, "SELECT COUNT(*) as total FROM teaching_journals WHERE teacher_id='$user_id' AND date = CURDATE()");
    $sudah_jurnal = mysqli_fetch_assoc($cek_jurnal)['total'];
    if($sudah_jurnal == 0) {
        $notifikasi[] = "📝 Anda belum mengisi jurnal mengajar hari ini!";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard - SIM ISTIQLAL</title>
    <link rel="stylesheet" href="assets/css/theme-istiqlal-green.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .content-wrapper { background: #f1f8f9; }
        .small-box { border-radius: 20px; overflow: hidden; transition: all 0.3s ease; }
        .small-box:hover { transform: translateY(-5px); }
        .welcome-card { background: linear-gradient(135deg, #0e362a 0%, #2d6a4f 100%); border-radius: 20px; padding: 20px; color: white; margin-bottom: 20px; }
        .notification-badge { position: absolute; top: -5px; right: -5px; background: red; color: white; border-radius: 50%; padding: 2px 6px; font-size: 10px; }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php include 'sidebar.php'; ?>

    <!-- Navbar -->
    <nav class="main-header navbar navbar-expand navbar-white navbar-light">
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" data-widget="pushmenu" href="#"><i class="fas fa-bars"></i></a>
            </li>
        </ul>
        <ul class="navbar-nav ml-auto">
            <li class="nav-item dropdown">
                <a class="nav-link" data-toggle="dropdown" href="#">
                    <i class="fas fa-bell"></i>
                    <?php if(count($notifikasi) > 0): ?>
                        <span class="notification-badge"><?= count($notifikasi) ?></span>
                    <?php endif; ?>
                </a>
                <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
                    <span class="dropdown-item dropdown-header">Notifikasi</span>
                    <div class="dropdown-divider"></div>
                    <?php if(count($notifikasi) > 0): ?>
                        <?php foreach($notifikasi as $notif): ?>
                            <a href="#" class="dropdown-item"><?= $notif ?></a>
                            <div class="dropdown-divider"></div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <a href="#" class="dropdown-item">Tidak ada notifikasi</a>
                    <?php endif; ?>
                </div>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link" data-toggle="dropdown" href="#">
                    <i class="fas fa-user-circle"></i> <?= $user['full_name'] ?>
                    <i class="fas fa-chevron-down"></i>
                </a>
                <div class="dropdown-menu dropdown-menu-right">
                    <a href="ganti_password.php" class="dropdown-item"><i class="fas fa-key"></i> Ganti Password</a>
                    <div class="dropdown-divider"></div>
                    <a href="logout.php" class="dropdown-item text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
                </div>
            </li>
        </ul>
    </nav>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <div class="content-header">
            <div class="container-fluid">
                <div class="welcome-card">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h2 class="mb-0">Selamat Datang, <?= htmlspecialchars($user['full_name']) ?>!</h2>
                            <p class="mb-0 mt-2">
                                <i class="fas fa-tag"></i> Role: <?= $user['role'] ?> | 
                                <i class="fas fa-building"></i> Unit: <?= $user['unit'] ?> |
                                <i class="fas fa-clock"></i> Login: <?= date('d-m-Y H:i:s') ?>
                            </p>
                            <p class="mb-0 mt-2">
                                <i class="fas fa-info-circle"></i> 
                                <?php
                                if($role == 'Super Admin') echo "Anda memiliki akses penuh ke seluruh aplikasi.";
                                elseif($role == 'Pimpinan') echo "Anda dapat melihat seluruh data dan melakukan monitoring.";
                                elseif($role == 'Kepala') echo "Anda dapat mengelola data di unit $unit.";
                                else echo "Anda dapat mengelola jurnal, nilai, dan absensi untuk kelas yang Anda ajar.";
                                ?>
                            </p>
                        </div>
                        <div class="col-md-4 text-center">
                            <i class="fas fa-chalkboard-user fa-4x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="container-fluid">
                <!-- Stats Cards -->
                <div class="row">
                    <?php if($role == 'Super Admin' || $role == 'Pimpinan' || $role == 'Kepala'): ?>
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3><?= $total_guru ?></h3>
                                <p>Total Guru</p>
                            </div>
                            <div class="icon"><i class="fas fa-chalkboard-user"></i></div>
                            <?php if($role == 'Super Admin'): ?>
                                <a href="kelola_user.php" class="small-box-footer">Detail <i class="fas fa-arrow-circle-right"></i></a>
                            <?php elseif($role == 'Kepala'): ?>
                                <a href="kelola_user.php?role=Guru" class="small-box-footer">Detail <i class="fas fa-arrow-circle-right"></i></a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3><?= $total_siswa ?></h3>
                                <p>Total Siswa</p>
                            </div>
                            <div class="icon"><i class="fas fa-user-graduate"></i></div>
                            <?php if($role != 'Guru'): ?>
                                <a href="kelola_siswa.php" class="small-box-footer">Detail <i class="fas fa-arrow-circle-right"></i></a>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if($role == 'Super Admin' || $role == 'Pimpinan' || $role == 'Kepala'): ?>
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3><?= $total_kelas ?></h3>
                                <p>Total Kelas</p>
                            </div>
                            <div class="icon"><i class="fas fa-school"></i></div>
                            <a href="kelola_kelas.php" class="small-box-footer">Detail <i class="fas fa-arrow-circle-right"></i></a>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-danger">
                            <div class="inner">
                                <h3><?= $hadir_hari_ini ?></h3>
                                <p>Hadir Hari Ini</p>
                            </div>
                            <div class="icon"><i class="fas fa-user-check"></i></div>
                            <?php if($role == 'Guru'): ?>
                                <a href="absensi_siswa.php" class="small-box-footer">Input Absensi <i class="fas fa-arrow-circle-right"></i></a>
                            <?php else: ?>
                                <a href="monitoring.php" class="small-box-footer">Monitoring <i class="fas fa-arrow-circle-right"></i></a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Charts -->
                <div class="row">
                    <div class="col-md-<?= ($role == 'Guru') ? '7' : '8' ?>">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">
                                    <i class="fas fa-chart-line text-primary"></i> Statistik Jurnal Mengajar (7 Hari Terakhir)
                                </h5>
                            </div>
                            <div class="card-body">
                                <canvas id="jurnalChart" style="height: 300px;"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    <?php if($role == 'Guru' && !empty($target_labels)): ?>
                    <div class="col-md-5">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">
                                    <i class="fas fa-chart-pie text-success"></i> Pencapaian Target Pembelajaran
                                </h5>
                            </div>
                            <div class="card-body">
                                <canvas id="targetChart" style="height: 300px;"></canvas>
                            </div>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">
                                    <i class="fas fa-chart-pie text-success"></i> Statistik Aktivitas
                                </h5>
                            </div>
                            <div class="card-body">
                                <canvas id="aktivitasChart" style="height: 300px;"></canvas>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Recent Activity -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">
                                    <i class="fas fa-history"></i> Aktivitas Terbaru
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr><th>Waktu</th><th>Aktivitas</th><th>User</th><th>Status</th></tr>
                                        </thead>
                                        <tbody>
                                            <?php while($log = mysqli_fetch_assoc($aktivitas)): ?>
                                            <tr>
                                                <td><?= date('d-m-Y', strtotime($log['waktu'])) ?></td>
                                                <td><i class="fas fa-book"></i> <?= $log['activity'] ?></td>
                                                <td><?= htmlspecialchars($log['full_name']) ?></td>
                                                <td><span class="badge badge-success">Berhasil</span></td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="main-footer">
        <strong>&copy; <?= date('Y') ?> SIM ISTIQLAL - Sistem Administrasi Guru</strong>
    </footer>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script>
// Jurnal Chart
new Chart(document.getElementById('jurnalChart'), {
    type: 'line',
    data: {
        labels: <?= json_encode($jurnal_labels) ?>,
        datasets: [{
            label: 'Jumlah Jurnal',
            data: <?= json_encode($jurnal_values) ?>,
            borderColor: '#2d6a4f',
            backgroundColor: 'rgba(45, 106, 79, 0.1)',
            tension: 0.4,
            fill: true
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        plugins: { legend: { position: 'top' } },
        scales: { y: { beginAtZero: true } }
    }
});

<?php if($role == 'Guru' && !empty($target_labels)): ?>
// Target Chart
new Chart(document.getElementById('targetChart'), {
    type: 'pie',
    data: {
        labels: <?= json_encode($target_labels) ?>,
        datasets: [{
            data: <?= json_encode($target_values) ?>,
            backgroundColor: ['#10b981', '#f59e0b', '#ef4444', '#3b82f6', '#8b5cf6']
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'bottom' } }
    }
});
<?php else: ?>
// Aktivitas Chart
new Chart(document.getElementById('aktivitasChart'), {
    type: 'doughnut',
    data: {
        labels: ['Jurnal', 'Supervisi', 'Absensi', 'Nilai'],
        datasets: [{
            data: [<?= $total_jurnal ?>, <?= $total_supervisi ?>, <?= $hadir_hari_ini ?>, 0],
            backgroundColor: ['#3b82f6', '#f59e0b', '#10b981', '#ef4444']
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'bottom' } }
    }
});
<?php endif; ?>
</script>
</body>
</html>