<?php
// Include database configuration
require_once __DIR__ . '/database.php';

// Include security utilities
require_once __DIR__ . '/../includes/file_handler.php';
require_once __DIR__ . '/../includes/security.php';
require_once __DIR__ . '/../includes/hr_analytics.php';
require_once __DIR__ . '/../includes/excel_exporter.php';
require_once __DIR__ . '/../includes/excel_generator.php';

// Initialize security manager and secure session
$security = SecurityManager::getInstance();
$security->initializeSecureSession();
$security->addSecurityHeaders();

// Site configuration
define('SITE_NAME', 'Recruitment Portal');
define('SITE_URL', 'http://localhost/recruit');
define('UPLOAD_PATH', __DIR__ . '/../uploads/');
define('UPLOAD_URL', SITE_URL . '/uploads/');

// Create uploads directory if it doesn't exist with secure permissions
if (!file_exists(UPLOAD_PATH)) {
    mkdir(UPLOAD_PATH, 0755, true);
    mkdir(UPLOAD_PATH . 'profiles/', 0755, true);
    mkdir(UPLOAD_PATH . 'logos/', 0755, true);
    mkdir(UPLOAD_PATH . 'resumes/', 0755, true);
    mkdir(UPLOAD_PATH . 'certificates/', 0755, true);
    mkdir(UPLOAD_PATH . 'documents/', 0755, true);
    
    // Add .htaccess to prevent direct script execution
    $htaccessContent = "Options -ExecCGI\n";
    $htaccessContent .= "AddHandler cgi-script .php .pl .py .jsp .asp .sh .cgi\n";
    $htaccessContent .= "<Files ~ \"\\.(php|pl|py|jsp|asp|sh|cgi)$\">\n";
    $htaccessContent .= "    Order allow,deny\n";
    $htaccessContent .= "    Deny from all\n";
    $htaccessContent .= "</Files>\n";
    
    file_put_contents(UPLOAD_PATH . '.htaccess', $htaccessContent);
}

// Helper functions
function sanitize($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

function redirect($url) {
    header("Location: " . $url);
    exit();
}

function isLoggedIn($user_type = null) {
    if ($user_type) {
        return isset($_SESSION['user_type']) && $_SESSION['user_type'] === $user_type;
    }
    return isset($_SESSION['user_id']) && isset($_SESSION['user_type']);
}

function requireLogin($user_type = null) {
    if (!isLoggedIn($user_type)) {
        redirect(SITE_URL . '/auth/login.php');
    }
    
    // Additional security: verify the user exists in database
    if (isset($_SESSION['user_id']) && isset($_SESSION['user_type'])) {
        validateUserSession();
    }
}

function validateUserSession() {
    static $validated = false;
    
    // Only validate once per request to avoid performance issues
    if ($validated) return;
    
    // Skip validation if essential session data is missing to avoid false positives
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type'])) {
        return;
    }
    
    // Skip validation for newly created sessions (within first 30 seconds)
    if (isset($_SESSION['login_time']) && (time() - $_SESSION['login_time']) < 30) {
        $validated = true;
        return;
    }
    
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        $user_id = $_SESSION['user_id'];
        $user_type = $_SESSION['user_type'];
        
        $user_exists = false;
        $expected_email = $_SESSION['user_email'] ?? null;
        
        // Validate based on user type
        switch ($user_type) {
            case 'candidate':
                $stmt = $db->prepare("SELECT id, email, first_name, last_name FROM candidates WHERE id = ?");
                $stmt->execute([$user_id]);
                $user = $stmt->fetch();
                
                if ($user) {
                    // For candidates, be more lenient with email validation during the initial session
                    if (!$expected_email || $user['email'] === $expected_email || 
                        (isset($_SESSION['login_time']) && (time() - $_SESSION['login_time']) < 300)) {
                        $user_exists = true;
                        // Update session with fresh data
                        $_SESSION['user_email'] = $user['email'];
                        $_SESSION['first_name'] = $user['first_name'];
                        $_SESSION['last_name'] = $user['last_name'];
                    }
                }
                break;
                
            case 'company':
                $stmt = $db->prepare("SELECT cu.id, cu.email, cu.name FROM company_users cu WHERE cu.id = ?");
                $stmt->execute([$user_id]);
                $user = $stmt->fetch();
                
                if ($user) {
                    // If we have an expected email, check it matches. Otherwise, just verify user exists
                    if (!$expected_email || $user['email'] === $expected_email) {
                        $user_exists = true;
                        $_SESSION['user_email'] = $user['email'];
                    }
                }
                break;
                
            case 'admin':
                $stmt = $db->prepare("SELECT id, email, username FROM admins WHERE id = ?");
                $stmt->execute([$user_id]);
                $user = $stmt->fetch();
                
                if ($user) {
                    // If we have an expected email, check it matches. Otherwise, just verify user exists
                    if (!$expected_email || $user['email'] === $expected_email) {
                        $user_exists = true;
                        $_SESSION['user_email'] = $user['email'];
                    }
                }
                break;
        }
        
        // If user doesn't exist, force logout
        if (!$user_exists) {
            error_log("Session validation failed for user_id: $user_id, user_type: $user_type, expected_email: $expected_email");
            session_destroy();
            redirect(SITE_URL . '/auth/login.php?message=Session expired. Please log in again.');
        }
        
        // IP address validation (less strict - only check if both IPs are set)
        $current_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $session_ip = $_SESSION['user_ip'] ?? null;
        
        // Only validate IP if both are known and different
        if ($session_ip && $current_ip !== 'unknown' && $session_ip !== $current_ip) {
            error_log("IP address mismatch for user_id: $user_id. Session IP: $session_ip, Current IP: $current_ip");
            session_destroy();
            redirect(SITE_URL . '/auth/login.php?message=Security alert: Session ended due to suspicious activity. Please log in again.');
        }
        
        $validated = true;
        
    } catch (Exception $e) {
        error_log("Session validation error: " . $e->getMessage());
        // Don't force logout on database errors, but log the issue
    }
}

function formatDate($date) {
    return date('M d, Y', strtotime($date));
}

function formatDateTime($datetime) {
    return date('M d, Y g:i A', strtotime($datetime));
}

function generateCSRFToken() {
    $security = SecurityManager::getInstance();
    return $security->generateSecureCSRFToken();
}

function validateCSRFToken($token) {
    $security = SecurityManager::getInstance();
    return $security->validateCSRFToken($token);
}

function validatePasswordComplexity($password) {
    $errors = [];
    
    // Minimum length
    if (strlen($password) < 8) {
        $errors[] = 'Password must be at least 8 characters long';
    }
    
    // Maximum length
    if (strlen($password) > 128) {
        $errors[] = 'Password must not exceed 128 characters';
    }
    
    // Must contain uppercase letter
    if (!preg_match('/[A-Z]/', $password)) {
        $errors[] = 'Password must contain at least one uppercase letter';
    }
    
    // Must contain lowercase letter
    if (!preg_match('/[a-z]/', $password)) {
        $errors[] = 'Password must contain at least one lowercase letter';
    }
    
    // Must contain digit
    if (!preg_match('/[0-9]/', $password)) {
        $errors[] = 'Password must contain at least one number';
    }
    
    // Must contain special character
    if (!preg_match('/[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?]/', $password)) {
        $errors[] = 'Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)';
    }
    
    return $errors;
}

function isPasswordStrong($password) {
    return empty(validatePasswordComplexity($password));
}
?>