<?php
// include/functions.php - Common functions for all modules
require_once dirname(__DIR__) . '/config.php';

// Password hashing wrapper
function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}

// Verify password
function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

// Get user by credentials
function authenticateUser($username, $password, $role) {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND role = ? AND status = 'active'");
    $stmt->execute([$username, $role]);
    $user = $stmt->fetch();
    
    if($user && verifyPassword($password, $user['password'])) {
        return $user;
    }
    return false;
}

// Set user session
function setUserSession($user) {
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['user_role'] = $user['role'];
    $_SESSION['user_name'] = $user['full_name'];
    $_SESSION['login_time'] = time();
}

// Check session timeout
function checkSessionTimeout() {
    if(isset($_SESSION['login_time']) && (time() - $_SESSION['login_time'] > SESSION_TIMEOUT)) {
        session_destroy();
        redirect('index.php?msg=session_expired');
    }
    $_SESSION['login_time'] = time();
}

// Upload file handler
function uploadFile($file, $subfolder = '') {
    $targetDir = UPLOAD_PATH . $subfolder;
    if(!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }
    
    $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9\._-]/', '', basename($file['name']));
    $targetPath = $targetDir . $fileName;
    
    if(move_uploaded_file($file['tmp_name'], $targetPath)) {
        return $subfolder . $fileName;
    }
    return false;
}

// Generate CSRF token
function generateCSRFToken() {
    if(!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Verify CSRF token
function verifyCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
?>