<?php
/**
 * Authentication Functions
 */

if (!defined('APP_NAME')) die('Direct access not permitted');

// Start session only if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Login function
function login($username, $password) {
    try {
        $pdo = getDB();
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1");
        $stmt->execute([$username, $username]);
        $user = $stmt->fetch();
        
        if ($user && password_verify($password, $user['password_hash'])) {
            if (!$user['is_active']) {
                return ['success' => false, 'error' => 'Account is deactivated.'];
            }
            session_regenerate_id(true);
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['full_name'] = $user['full_name'];
            // Update last login
            $upd = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
            $upd->execute([$user['id']]);
            return ['success' => true, 'role' => $user['role']];
        }
        return ['success' => false, 'error' => 'Invalid credentials.'];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function isAdmin() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

function isDoctor() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'doctor';
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: /kent/login.php');
        exit;
    }
}

function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        die('Access denied. Admin only.');
    }
}

function getCurrentUser() {
    if (!isLoggedIn()) return null;
    try {
        $pdo = getDB();
        $stmt = $pdo->prepare("SELECT id, username, email, full_name, role, is_active, profile_picture, created_at, last_login FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        return $stmt->fetch();
    } catch (Exception $e) {
        return null;
    }
}

function logout() {
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"]);
    }
    session_destroy();
    header('Location: /kent/login.php');
    exit;
}
?>