<?php
/**
 * Authentication System
 * Research Survey Management System
 */

require_once __DIR__ . '/../config/app.php';

/**
 * Start secure session
 */
function startSession() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
}

/**
 * Authenticate user with username and password
 */
function authenticateUser($username, $password) {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :uname OR email = :uemail LIMIT 1");
    $stmt->execute(['uname' => $username, 'uemail' => $username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password_hash'])) {
        // Update last login
        $stmt = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE user_id = :id");
        $stmt->execute(['id' => $user['user_id']]);
        
        // Create session
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', time() + SESSION_TIMEOUT);
        
        $stmt = $pdo->prepare("INSERT INTO user_sessions (user_id, session_token, ip_address, user_agent, expires_at) 
                               VALUES (:user_id, :token, :ip, :ua, :expires)");
        $stmt->execute([
            'user_id' => $user['user_id'],
            'token' => $token,
            'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
            'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'expires' => $expires
        ]);
        
        $_SESSION['user_id'] = $user['user_id'];
        $_SESSION['session_token'] = $token;
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['user_name'] = $user['full_name'];
        
        return $user;
    }
    
    return false;
}

/**
 * Check if user is logged in
 */
function isLoggedIn() {
    startSession();
    
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['session_token'])) {
        return false;
    }
    
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT u.*, us.expires_at, us.is_active 
                           FROM user_sessions us 
                           JOIN users u ON us.user_id = u.user_id 
                           WHERE us.session_token = :token 
                           AND us.user_id = :user_id 
                           AND us.is_active = 1 
                           AND us.expires_at > NOW()
                           AND u.is_active = 1
                           LIMIT 1");
    $stmt->execute([
        'token' => $_SESSION['session_token'],
        'user_id' => $_SESSION['user_id']
    ]);
    
    $session = $stmt->fetch();
    
    if ($session) {
        // Update last activity
        $stmt = $pdo->prepare("UPDATE user_sessions SET last_activity = NOW() WHERE session_token = :token");
        $stmt->execute(['token' => $_SESSION['session_token']]);
        
        $_SESSION['user_role'] = $session['role'];
        $_SESSION['user_name'] = $session['full_name'];
        return $session;
    }
    
    // Session expired or invalid
    logoutUser();
    return false;
}

/**
 * Require authentication - redirect if not logged in
 */
function requireAuth() {
    if (!isLoggedIn()) {
        header('Location: ' . BASE_URL . '/pages/login.php');
        exit;
    }
}

/**
 * Check if user has specific role
 */
function hasRole($roles) {
    if (!isLoggedIn()) {
        return false;
    }
    
    if (is_array($roles)) {
        return in_array($_SESSION['user_role'], $roles);
    }
    
    return $_SESSION['user_role'] === $roles;
}

/**
 * Require specific role
 */
function requireRole($roles) {
    requireAuth();
    if (!hasRole($roles)) {
        header('HTTP/1.0 403 Forbidden');
        die('Access denied. Insufficient permissions.');
    }
}

/**
 * Get current user data
 */
function getCurrentUser() {
    if (!isLoggedIn()) {
        return null;
    }
    
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT user_id, username, email, full_name, role, department, avatar_url, last_login 
                           FROM users WHERE user_id = :id");
    $stmt->execute(['id' => $_SESSION['user_id']]);
    return $stmt->fetch();
}

/**
 * Logout user
 */
function logoutUser() {
    startSession();
    
    if (isset($_SESSION['session_token'])) {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE user_sessions SET is_active = 0 WHERE session_token = :token");
        $stmt->execute(['token' => $_SESSION['session_token']]);
    }
    
    $_SESSION = [];
    session_destroy();
}

/**
 * Log audit event
 */
function logAudit($action, $entityType, $entityId = null, $oldValue = null, $newValue = null) {
    if (!isset($_SESSION['user_id'])) {
        return;
    }
    
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("INSERT INTO audit_log (user_id, action_type, entity_type, entity_id, old_value, new_value, ip_address, user_agent) 
                           VALUES (:user_id, :action, :entity, :entity_id, :old_val, :new_val, :ip, :ua)");
    $stmt->execute([
        'user_id' => $_SESSION['user_id'],
        'action' => $action,
        'entity' => $entityType,
        'entity_id' => $entityId,
        'old_val' => $oldValue ? json_encode($oldValue) : null,
        'new_val' => $newValue ? json_encode($newValue) : null,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
        'ua' => $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
}