<?php
/**
 * Admin Authentication Functions
 * 
 * This file contains functions for admin authentication and session management
 */

// Ensure unified session initialization
if (!defined('TONSUI_LOADED')) {
    define('TONSUI_LOADED', true);
}
// Include centralized session initialization (handles session_start internally)
require_once __DIR__ . '/session_init.php';

/**
 * Check if an admin is currently logged in
 * 
 * @return bool True if admin is logged in, false otherwise
 */
function isAdminLoggedIn() {
    return (
        isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id'])
    ) || (
        isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true
    );
}

/**
 * Get the current logged in admin's ID
 * 
 * @return int|null The admin ID if logged in, null otherwise
 */
function getAdminId() {
    return isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : null;
}

/**
 * Log out the current admin
 * 
 * @return void
 */
function adminLogout() {
    // Clear admin-specific session variables
    unset($_SESSION['admin_id']);
    unset($_SESSION['admin_username']);
    $_SESSION['admin_logged_in'] = false;
    
    // Optional: regenerate session ID for security
    session_regenerate_id(true);
}

/**
 * Authenticate admin using credentials
 * 
 * @param string $username Admin username
 * @param string $password Admin password
 * @param object $pdo PDO database connection
 * @return array Authentication result with success status and message/admin data
 */
function authenticateAdmin($username, $password, $pdo) {
    try {
        // Find admin by username
        $stmt = $pdo->prepare("SELECT id, username, password FROM admins WHERE username = ?");
        $stmt->execute([$username]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$admin) {
            return ['success' => false, 'message' => 'Admin not found'];
        }
        
        // Verify password
        if (password_verify($password, $admin['password'])) {
            // Set session variables
            $_SESSION['admin_id'] = (int)$admin['id'];
            $_SESSION['admin_username'] = $admin['username'];
            $_SESSION['admin_logged_in'] = true;

            // Regenerate session ID for security
            session_regenerate_id(true);

            return [
                'success' => true,
                'admin' => [
                    'id' => (int)$admin['id'],
                    'username' => $admin['username']
                ]
            ];
        } else {
            return ['success' => false, 'message' => 'Invalid password'];
        }
    } catch (PDOException $e) {
        error_log('Admin authentication error: ' . $e->getMessage());
        return ['success' => false, 'message' => 'Database error during authentication'];
    }
}
