<?php
// ============================================================
// SESSION PROTECTION + SWEETALERT2 FIX VERSION
// ============================================================

include "lib/conn.php";
session_start();

// ============================================================
// 🚫 CEGAH REDIRECT LOOP
// ============================================================
// Jika file ini dipanggil di halaman login/logout, abaikan validasi session
$current_file = basename($_SERVER['PHP_SELF']);
if (in_array($current_file, ['login.php', 'logout.php'])) {
    return;
}

// ============================================================
// 🔒 CEK STATUS LOGIN
// ============================================================
if (!isset($_SESSION['login_user']) || empty($_SESSION['login_user'])) {
    echo "
    <!DOCTYPE html>
    <html lang='id'>
    <head>
      <meta charset='UTF-8'>
      <meta name='viewport' content='width=device-width, initial-scale=1.0'>
      <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
      <title>Sesi Habis</title>
    </head>
    <body>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'warning',
            title: 'Sesi Habis!',
            text: 'Silakan login kembali untuk melanjutkan.',
            confirmButtonColor: '#3085d6'
        }).then(() => {
            window.location = 'login.php';
        });
    });
    </script>
    </body>
    </html>";
    exit;
}

// ============================================================
// 🧭 JIKA LOGIN VALID, AMBIL DATA USER DAN PEGAWAI
// ============================================================
$user_check  = $_SESSION['login_user'];
$level_check = $_SESSION['level'];

// Ambil data user dari tabel users
$ses_sql = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$user_check' LIMIT 1");
$row = mysqli_fetch_assoc($ses_sql);

// Jika user tidak ditemukan (data sudah dihapus di DB)
if (!$row) {
    session_destroy();
    echo "
    <!DOCTYPE html>
    <html lang='id'>
    <head>
      <meta charset='UTF-8'>
      <meta name='viewport' content='width=device-width, initial-scale=1.0'>
      <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
      <title>Akun Tidak Ditemukan</title>
    </head>
    <body>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'error',
            title: 'Akun Tidak Ditemukan!',
            text: 'Data pengguna Anda tidak valid. Silakan login ulang.',
            confirmButtonColor: '#d33'
        }).then(() => {
            window.location = 'login.php';
        });
    });
    </script>
    </body>
    </html>";
    exit;
}

// ============================================================
// 🧑‍💼 Ambil Data Pegawai Terkait
// ============================================================
$sql_akunx = mysqli_query($conn, "
    SELECT pegawai_id AS id, pegawai_nama AS nama
    FROM pegawai 
    WHERE pegawai_id = '{$row['nama_lengkap']}' 
    LIMIT 1
");
$gx = mysqli_fetch_assoc($sql_akunx);

// ============================================================
// 🧱 SET VARIABEL UNTUK HALAMAN LAIN
// ============================================================
$login_session = $gx['nama'] ?? 'User';
$user_id       = $row['nama_lengkap'];
$foto_session  = $row['foto_user'];
$pech          = $row['id_identitas'];
$tokox         = explode(",", $pech);

// ============================================================
// 🧹 CEK VALIDASI TAMBAHAN (DATA PEGAWAI HILANG)
// ============================================================
if (empty($login_session)) {
    session_destroy();
    echo "
    <!DOCTYPE html>
    <html lang='id'>
    <head>
      <meta charset='UTF-8'>
      <meta name='viewport' content='width=device-width, initial-scale=1.0'>
      <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
      <title>Data Pegawai Tidak Ditemukan</title>
    </head>
    <body>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'warning',
            title: 'Data Pegawai Tidak Ditemukan',
            text: 'Silakan login ulang untuk memperbarui sesi Anda.',
            confirmButtonColor: '#3085d6'
        }).then(() => {
            window.location = 'login.php';
        });
    });
    </script>
    </body>
    </html>";
    exit;
}
?>
