<?php
session_start();
require_once "inc/db.php";

// --- Auto-login from cookies if session not set ---
if (!isset($_SESSION['adminid']) && isset($_COOKIE['adminid'], $_COOKIE['adminrole'], $_COOKIE['adminname'])) {
    $_SESSION['adminid'] = $_COOKIE['adminid'];
    $_SESSION['adminrole'] = $_COOKIE['adminrole'];
    $_SESSION['adminname'] = $_COOKIE['adminname'];
}

// --- Load session data ---
$adminId = $_SESSION['adminid'] ?? null;
$adminRole = $_SESSION['adminrole'] ?? null;
$adminName = $_SESSION['adminname'] ?? null;

// --- Check login ---
if (!$adminId || !$adminRole || !$adminName) {
    alertAndRedirect('Please log in first.', 'index.php');
}

// --- Role-based access control ---
if (strtolower($adminRole) !== 'admin') {
    alertAndRedirect('Access denied. You do not have Admin privileges.', 'login.php');
}

// --- Check status in DB ---
$stmt = $conn->prepare("SELECT status FROM users WHERE id = ?");
$stmt->bind_param("i", $adminId);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    $user = $result->fetch_assoc();
    if (strtolower($user['status']) !== 'active') {
        clearSessionAndCookies();
        alertAndRedirect('Your account has been deactivated. Please contact support.', 'login.php');
    }
} else {
    clearSessionAndCookies();
    alertAndRedirect('Account not found. Please login again.', 'index.php');
}

// --- Show welcome toast once ---
if (!isset($_SESSION['welcome_shown'])) {
    setSessionMessage('success', 'Welcome, Admin!');
    $_SESSION['welcome_shown'] = true;
}

// --- Helper Functions ---
function setSessionMessage($type, $text)
{
    $_SESSION['message'] = [
        'type' => $type,
        'text' => $text
    ];
}

function redirectTo($url)
{
    echo "<script>window.location.href = '$url';</script>";
    exit();
}

function clearSessionAndCookies()
{
    session_unset();
    session_destroy();
    setcookie('adminid', '', time() - 3600, '/');
    setcookie('adminrole', '', time() - 3600, '/');
    setcookie('adminname', '', time() - 3600, '/');
}

function alertAndRedirect($message, $url)
{
    echo "<script>alert('$message'); window.location.href = '$url';</script>";
    exit();
}
?>
