<?php
// functions.php - Secure Admin Authentication System

// Database connection with error handling
if (!function_exists('db_connect')) {
    function db_connect() {
        static $conn;
        if (!$conn) {
            $conn = new mysqli('127.0.0.1', 'db_username', 'db_password', 'mabati');
            if ($conn->connect_error) {
                error_log("Database connection failed: " . $conn->connect_error);
                die("System maintenance in progress. Please try again later.");
            }
            $conn->set_charset("utf8mb4");
        }
        return $conn;
    }
}

// Session security initialization
if (!function_exists('secure_session_start')) {
    function secure_session_start() {
        $session_name = 'mabati_admin_session';
        $secure = true; // Set to true if using HTTPS
        $httponly = true; // Prevent JavaScript access
        
        ini_set('session.use_only_cookies', 1);
        ini_set('session.cookie_httponly', 1);
        ini_set('session.cookie_secure', $secure ? 1 : 0);
        
        session_name($session_name);
        session_start();
        session_regenerate_id(true); // Prevent session fixation
    }
}

// Superadmin verification
if (!function_exists('is_superadmin')) {
    function is_superadmin() {
        if (empty($_SESSION['user_id'])) return false;
        
        $conn = db_connect();
        $stmt = $conn->prepare("SELECT id, role_id FROM admin_users 
                               WHERE id = ? AND username = 'superadmin' AND is_active = 1");
        $stmt->bind_param("i", $_SESSION['user_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();
        
        return ($user['id'] ?? 0) === 1 && ($user['role_id'] ?? 0) === 1;
    }
}

// Secure login function
if (!function_exists('admin_login')) {
    function admin_login($username, $password) {
        $conn = db_connect();
        
        $stmt = $conn->prepare("SELECT id, username, password_hash, role_id 
                               FROM admin_users 
                               WHERE username = ? AND is_active = 1 LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($user = $result->fetch_assoc()) {
            if (password_verify($password, $user['password_hash'])) {
                // Password is correct, start secure session
                secure_session_start();
                
                $_SESSION = array(); // Clear existing session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role_id'] = $user['role_id'];
                $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
                $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                $_SESSION['last_activity'] = time();
                
                // Update last login
                $update = $conn->prepare("UPDATE admin_users 
                                         SET last_login = NOW() 
                                         WHERE id = ?");
                $update->bind_param("i", $user['id']);
                $update->execute();
                $update->close();
                
                return true;
            }
        }
        
        // Failed login attempt logging
        error_log("Failed login attempt for username: $username");
        return false;
    }
}

// Session validation
if (!function_exists('validate_admin_session')) {
    function validate_admin_session() {
        if (empty($_SESSION['user_id']) || 
            $_SESSION['ip_address'] !== $_SERVER['REMOTE_ADDR'] || 
            $_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) {
            session_destroy();
            return false;
        }
        
        // Session timeout (30 minutes)
        if (time() - $_SESSION['last_activity'] > 1800) {
            session_destroy();
            return false;
        }
        
        $_SESSION['last_activity'] = time(); // Update activity time
        return true;
    }
}

// Password hashing function
if (!function_exists('hash_admin_password')) {
    function hash_admin_password($password) {
        return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
    }
}