<?php
// Include koneksi ke database jika belum di-include di file utama
include "../config/koneksi.php";

// Session Guard
if (empty($_SESSION['namauser']) && empty($_SESSION['passuser'])) {
    echo "
    <div class='adm-card text-center py-5' style='max-width: 480px; margin: 40px auto;'>
        <div class='mb-3' style='font-size: 3rem; color: var(--adm-primary);'>
            <i class='fa fa-lock'></i>
        </div>
        <h4 style='color: var(--adm-text); font-weight: 700;' class='mb-2'>Akses Terbatas</h4>
        <p style='color: var(--adm-text-sub); font-size: 0.9rem;' class='mb-4'>
            Anda harus melakukan autentikasi terlebih dahulu untuk mengakses panel administrator.
        </p>
        <a href='../../index.php' class='adm-nav-item active d-inline-flex justify-content-center' style='width: auto; padding: 10px 24px;'>
            <i class='fa fa-sign-in-alt me-2'></i> Login Sekarang
        </a>
    </div>";
    exit();
}

// -------------------------------------------------------------
// PEMBERSIH OTOMATIS (Lazy Cleanup Database)
// Berjalan secara acak (1 banding 100 hit) untuk hapus data > 30 hari
// -------------------------------------------------------------
if (rand(1, 100) === 1) {
    @mysqli_query($konek, "DELETE FROM visitor_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)");
}

// Data Tanggal & Sapaan
$tgl     = date("Y-m-d");
$tanggal = function_exists('tgl_indo') ? tgl_indo($tgl) : date("d F Y");
$nama    = htmlspecialchars($_SESSION['namalengkap'] ?? 'Administrator');
$jam     = (int)date('H');

// Sapaan otomatis berdasarkan waktu
if ($jam >= 5 && $jam < 12) {
    $sapaan = "Selamat Pagi";
} elseif ($jam >= 12 && $jam < 15) {
    $sapaan = "Selamat Siang";
} elseif ($jam >= 15 && $jam < 18) {
    $sapaan = "Selamat Sore";
} else {
    $sapaan = "Selamat Malam";
}

// -------------------------------------------------------------
// QUERY STATISTIK PENGUNJUNG (TRAFFIC ANALYTICS)
// -------------------------------------------------------------
// 1. Total Pengunjung
$q_total = mysqli_query($konek, "SELECT COUNT(*) as total FROM visitor_logs");
$r_total = mysqli_fetch_assoc($q_total);
$total_visitors = number_format($r_total['total'] ?? 0);

// 2. Pengunjung Hari Ini
$q_today = mysqli_query($konek, "SELECT COUNT(*) as total FROM visitor_logs WHERE DATE(created_at) = CURDATE()");
$r_today = mysqli_fetch_assoc($q_today);
$today_visitors = number_format($r_today['total'] ?? 0);

// 3. Pengunjung Bulan Ini
$q_month = mysqli_query($konek, "SELECT COUNT(*) as total FROM visitor_logs WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())");
$r_month = mysqli_fetch_assoc($q_month);
$month_visitors = number_format($r_month['total'] ?? 0);

// 4. Perangkat Paling Banyak Digunakan (Mobile vs Desktop)
$q_device = mysqli_query($konek, "SELECT device, COUNT(*) as jumlah FROM visitor_logs GROUP BY device ORDER BY jumlah DESC LIMIT 1");
$r_device = mysqli_fetch_assoc($q_device);
$top_device = $r_device['device'] ?? 'Desktop';
?>

<!-- Welcome Hero Banner -->
<div class="adm-welcome-hero mb-4">
    <div class="adm-welcome-content">
        <span class="adm-badge-status mb-2">
            <span class="adm-pulse-dot"></span> Sesi Aktif
        </span>
        <h2 class="adm-welcome-title"><?= $sapaan ?>, <?= $nama ?>!</h2>
        <p class="adm-welcome-sub">
            Sistem berjalan normal. Hari ini tanggal <strong style="color: var(--adm-text);"><?= $tanggal ?></strong>.
        </p>
    </div>
    <div class="adm-welcome-illustration">
        <i class="fa fa-shield-alt"></i>
    </div>
</div>

<!-- Quick Overview Cards (System Info & Traffic Summary) -->
<div class="row g-3 mb-4">
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="adm-stat-card">
            <div class="adm-stat-icon red">
                <i class="fa fa-user-shield"></i>
            </div>
            <div class="adm-stat-info">
                <span class="adm-stat-label">Level Akses</span>
                <h5 class="adm-stat-value"><?= ucfirst($_SESSION['leveluser'] ?? 'Admin') ?></h5>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="adm-stat-card">
            <div class="adm-stat-icon blue">
                <i class="fa fa-chart-line"></i>
            </div>
            <div class="adm-stat-info">
                <span class="adm-stat-label">Pengunjung Hari Ini</span>
                <h5 class="adm-stat-value"><?= $today_visitors ?> <small class="text-muted" style="font-size:0.7rem;">hits</small></h5>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="adm-stat-card">
            <div class="adm-stat-icon purple">
                <i class="fa fa-users"></i>
            </div>
            <div class="adm-stat-info">
                <span class="adm-stat-label">Pengunjung Bulan Ini</span>
                <h5 class="adm-stat-value"><?= $month_visitors ?> <small class="text-muted" style="font-size:0.7rem;">hits</small></h5>
            </div>
        </div>
    </div>
    <div class="col-12 col-sm-6 col-xl-3">
        <div class="adm-stat-card">
            <div class="adm-stat-icon green">
                <i class="fa fa-server"></i>
            </div>
            <div class="adm-stat-info">
                <span class="adm-stat-label">Status Server</span>
                <h5 class="adm-stat-value text-success" style="font-size: 0.9rem;">Online <small class="text-muted">(<?= date("H:i") ?> WIB)</small></h5>
            </div>
        </div>
    </div>
</div>

<!-- Grid Konten Utama: Audit Trail & Traffic Logs -->
<div class="row g-4 mb-4">
    
    <!-- Kolom Kiri: History Login Security -->
    <div class="col-12 col-lg-7">
        <div class="adm-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h5 class="fw-bold m-0" style="color: var(--adm-text);">
                        <i class="fa fa-history me-2 text-danger"></i>Aktivitas Login Terakhir
                    </h5>
                    <small style="color: var(--adm-text-sub);">10 percobaan akses terbaru ke panel admin</small>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table align-middle text-nowrap mb-0" style="color: var(--adm-text); border-color: var(--adm-border);">
                    <thead>
                        <tr style="border-bottom: 2px solid var(--adm-border-active); color: var(--adm-text-sub); font-size: 0.8rem; text-transform: uppercase;">
                            <th scope="col" class="py-2">No</th>
                            <th scope="col" class="py-2">User</th>
                            <th scope="col" class="py-2">IP Address</th>
                            <th scope="col" class="py-2">Waktu</th>
                            <th scope="col" class="py-2 text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody style="font-size: 0.85rem;">
                        <?php
                        $no = 1;
                        $query_log = "SELECT * FROM history_login ORDER BY id DESC LIMIT 8";
                        $sql_log   = mysqli_query($konek, $query_log);

                        if ($sql_log && mysqli_num_rows($sql_log) > 0) {
                            while ($row = mysqli_fetch_array($sql_log)) {
                                $status_badge = ($row['status'] == 'Berhasil') 
                                    ? '<span class="adm-badge-status"><span class="adm-pulse-dot"></span> Berhasil</span>'
                                    : '<span class="adm-badge-status red"><span class="adm-pulse-dot red"></span> Gagal</span>';

                                echo "
                                <tr style='border-bottom: 1px solid var(--adm-border);'>
                                    <td class='py-2.5'>{$no}</td>
                                    <td class='py-2.5 fw-semibold'>" . htmlspecialchars($row['username']) . "</td>
                                    <td class='py-2.5'><code style='color: var(--adm-primary);'>" . htmlspecialchars($row['ip_address']) . "</code></td>
                                    <td class='py-2.5'>" . date('d/m/Y H:i', strtotime($row['waktu_login'])) . "</td>
                                    <td class='py-2.5 text-center'>{$status_badge}</td>
                                </tr>";
                                $no++;
                            }
                        } else {
                            echo "<tr><td colspan='5' class='text-center py-4' style='color: var(--adm-text-sub);'>Belum ada riwayat aktivitas login.</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Kolom Kanan: Pengunjung Realtime Website -->
    <div class="col-12 col-lg-5">
        <div class="adm-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h5 class="fw-bold m-0" style="color: var(--adm-text);">
                        <i class="fa fa-globe me-2 text-info"></i>Trafik Website Terakhir
                    </h5>
                    <small style="color: var(--adm-text-sub);">Kunjungan publik ke website secara live</small>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table align-middle text-nowrap mb-0" style="color: var(--adm-text); border-color: var(--adm-border);">
                    <thead>
                        <tr style="border-bottom: 2px solid var(--adm-border-active); color: var(--adm-text-sub); font-size: 0.8rem; text-transform: uppercase;">
                            <th scope="col" class="py-2">IP & Device</th>
                            <th scope="col" class="py-2">Modul / Halaman</th>
                            <th scope="col" class="py-2 text-end">Waktu</th>
                        </tr>
                    </thead>
                    <tbody style="font-size: 0.85rem;">
                        <?php
                        $query_visitor = "SELECT * FROM visitor_logs ORDER BY id DESC LIMIT 8";
                        $sql_visitor   = mysqli_query($konek, $query_visitor);

                        if ($sql_visitor && mysqli_num_rows($sql_visitor) > 0) {
                            while ($v = mysqli_fetch_array($sql_visitor)) {
                                $device_icon = ($v['device'] == 'Mobile') ? 'fa-mobile-alt text-warning' : 'fa-desktop text-primary';
                                $mod_badge   = htmlspecialchars($v['module'] ?? 'home');

                                echo "
                                <tr style='border-bottom: 1px solid var(--adm-border);'>
                                    <td class='py-2.5'>
                                        <div class='d-flex align-items-center gap-2'>
                                            <i class='fa {$device_icon}'></i>
                                            <code>" . htmlspecialchars($v['ip_address']) . "</code>
                                        </div>
                                    </td>
                                    <td class='py-2.5'>
                                        <span class='badge bg-secondary opacity-75 fw-normal' style='font-size: 0.7rem;'>" . $mod_badge . "</span>
                                    </td>
                                    <td class='py-2.5 text-end' style='color: var(--adm-text-sub); font-size:0.8rem;'>
                                        " . date('H:i:s', strtotime($v['created_at'])) . "
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='3' class='text-center py-4' style='color: var(--adm-text-sub);'>Belum ada trafik pengunjung.</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
            
            <div class="mt-3 pt-2 border-top d-flex justify-content-between align-items-center" style="border-color: var(--adm-border) !important;">
                <small style="color: var(--adm-text-sub); font-size:0.75rem;">Total Log: <strong><?= $total_visitors ?></strong> rekaman</small>
                <small style="color: var(--adm-text-sub); font-size:0.75rem;"><i class="fa fa-sync-alt fa-spin me-1"></i> Auto Cleanup 30 Hari</small>
            </div>
        </div>
    </div>

</div>

<!-- CSS TAMBAHAN UNTUK INTEGRASI PEMANTAUAN -->
<style>
/* Hero Banner Beranda */
.adm-welcome-hero {
    background: linear-gradient(135deg, rgba(230, 57, 70, 0.12) 0%, rgba(20, 20, 25, 0.6) 100%);
    border: 1px solid var(--adm-border-active);
    border-radius: var(--adm-radius);
    padding: 28px 32px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    overflow: hidden;
}

.adm-badge-status {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: rgba(16, 185, 129, 0.1);
    color: #10b981;
    border: 1px solid rgba(16, 185, 129, 0.2);
    font-size: 0.75rem;
    font-weight: 600;
    padding: 4px 10px;
    border-radius: 20px;
}

.adm-badge-status.red {
    background: rgba(239, 68, 68, 0.1);
    color: #ef4444;
    border-color: rgba(239, 68, 68, 0.2);
}

.adm-pulse-dot {
    width: 6px;
    height: 6px;
    background: #10b981;
    border-radius: 50%;
    box-shadow: 0 0 8px #10b981;
}

.adm-pulse-dot.red {
    background: #ef4444;
    box-shadow: 0 0 8px #ef4444;
}

.adm-welcome-title {
    color: var(--adm-text);
    font-size: 1.5rem;
    font-weight: 700;
    margin: 4px 0 6px 0;
}

.adm-welcome-sub {
    color: var(--adm-text-sub);
    font-size: 0.9rem;
    margin: 0;
}

.adm-welcome-illustration {
    font-size: 3.5rem;
    color: var(--adm-primary);
    opacity: 0.25;
    margin-left: 20px;
}

/* Stat Cards Mini Overview */
.adm-stat-card {
    background: var(--adm-bg-card);
    border: 1px solid var(--adm-border);
    border-radius: var(--adm-radius);
    padding: 18px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    transition: var(--adm-transition);
}

.adm-stat-card:hover {
    border-color: var(--adm-border-active);
    transform: translateY(-2px);
}

.adm-stat-icon {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    background: var(--adm-bg-hover);
    border: 1px solid var(--adm-border);
    color: var(--adm-text-sub);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.1rem;
    flex-shrink: 0;
}

.adm-stat-icon.red {
    background: rgba(230, 57, 70, 0.1);
    border-color: rgba(230, 57, 70, 0.2);
    color: var(--adm-primary);
}

.adm-stat-icon.green {
    background: rgba(16, 185, 129, 0.1);
    border-color: rgba(16, 185, 129, 0.2);
    color: #10b981;
}

.adm-stat-icon.blue {
    background: rgba(14, 165, 233, 0.1);
    border-color: rgba(14, 165, 233, 0.2);
    color: #0ea5e9;
}

.adm-stat-icon.purple {
    background: rgba(168, 85, 247, 0.1);
    border-color: rgba(168, 85, 247, 0.2);
    color: #a855f7;
}

.adm-stat-label {
    display: block;
    font-size: 0.75rem;
    color: var(--adm-text-sub);
    font-weight: 500;
}

.adm-stat-value {
    margin: 2px 0 0 0;
    color: var(--adm-text);
    font-size: 1.1rem;
    font-weight: 700;
}

/* Card Container */
.adm-card {
    background: var(--adm-bg-card);
    border: 1px solid var(--adm-border);
    border-radius: var(--adm-radius);
}

/* Responsif HP */
@media (max-width: 575.98px) {
    .adm-welcome-hero {
        padding: 20px;
    }
    .adm-welcome-illustration {
        display: none;
    }
    .adm-welcome-title {
        font-size: 1.25rem;
    }
}
</style>