<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

function startSession() {
    if (session_status() === PHP_SESSION_NONE) {
        session_name(SESSION_NAME);
        session_set_cookie_params(SESSION_LIFETIME);
        session_start();
    }
}

function isLoggedIn() {
    startSession();
    return isset($_SESSION['kkn_user_id']) && isset($_SESSION['kkn_role']);
}

function getUser() {
    startSession();
    return $_SESSION['kkn_user'] ?? null;
}

function getRole() {
    startSession();
    return $_SESSION['kkn_role'] ?? null;
}

function requireLogin($role = null) {
    if (!isLoggedIn()) {
        header('Location: ' . BASE_URL . '/kkn-login?msg=login_required');
        exit;
    }
    if ($role && getRole() !== $role && getRole() !== 'admin') {
        header('Location: ' . BASE_URL . '/kkn-dashboard?msg=access_denied');
        exit;
    }
}

function login($username_or_email, $password) {
    // Cek admin hardcode
    if ($username_or_email === ADMIN_USER && password_verify($password, '$2y$10$8K1p/a0dR1xqM8K3oEnW2.HxqR5y0vW1sGlQ8JYkHOq5zFjsP.tTW')) {
        startSession();
        $_SESSION['kkn_user_id'] = 0;
        $_SESSION['kkn_role']    = 'admin';
        $_SESSION['kkn_user']    = ['id'=>0,'nama'=>'Admin LPPM','role'=>'admin','email'=>SMTP_USER];
        return true;
    }

    // Cek dari database
    $user = fetch(
        "SELECT u.*, 
                COALESCE(d.nama, m.nama) as nama,
                d.id as dpl_id, m.id as mhs_id
         FROM kkn_users u
         LEFT JOIN kkn_dpl d ON d.user_id = u.id
         LEFT JOIN kkn_mahasiswa m ON m.user_id = u.id
         WHERE (u.username = ? OR u.email = ?) AND u.status = 'active'",
        [$username_or_email, $username_or_email]
    );

    if ($user && password_verify($password, $user['password'])) {
        startSession();
        $_SESSION['kkn_user_id'] = $user['id'];
        $_SESSION['kkn_role']    = $user['role'];
        $_SESSION['kkn_user']    = $user;
        // Update last login
        query("UPDATE kkn_users SET last_login = NOW() WHERE id = ?", [$user['id']]);
        return true;
    }
    return false;
}

function logout() {
    startSession();
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time()-42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
    }
    session_destroy();
    $url = BASE_URL . '/kkn-login';
    header('Location: ' . $url);
    header('Cache-Control: no-cache, no-store, must-revalidate');
    echo '<!DOCTYPE html><html><head>'
        .'<meta http-equiv="refresh" content="0;url=' . $url . '">'
        .'<script>window.location.replace("' . $url . '");</script>'
        .'</head><body></body></html>';
    exit;
}

function generateToken() {
    return bin2hex(random_bytes(32));
}
