<?php
/**
 * Updated config.php for Exam Management System
 * Compatible with existing settings + New Publishing Workflow
 * 
 * @author MiniMax Agent
 * @date 2025-11-13
 */

// Prevent direct access
if (!defined('ACCESS_ALLOWED')) {
    define('ACCESS_ALLOWED', true);
}

// =====================================
// DATABASE CONFIGURATION (Keep your existing settings)
// =====================================

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'report_system');
define('DB_CHARSET', 'utf8mb4');

// Connect to MySQL database with error handling
try {
    $conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
    
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    
    // Set character set
    $conn->set_charset(DB_CHARSET);
    
} catch (Exception $e) {
    if ($conn === false) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    $conn = null;
}

// =====================================
// USER ROLES (Updated for compatibility)
// =====================================

// Keep your existing role definitions but add the new ones
define('ROLE_SUPER_ADMIN', 0);
define('ROLE_ADMIN', 1);
define('ROLE_TEACHER', 2);
define('ROLE_STUDENT', 3);
define('ROLE_PARENT', 4);
define('ROLE_STAFF', 5);

// Add new role constants for publishing workflow (same values, different names)
define('NEW_ROLE_SUPER_ADMIN', 0);
define('NEW_ROLE_ADMIN', 1);
define('NEW_ROLE_TEACHER', 2);
define('NEW_ROLE_STUDENT', 3);
define('NEW_ROLE_PARENT', 4);
define('NEW_ROLE_STAFF', 5);

// Role compatibility mapping
if (!function_exists('getRoleCompatibility')) {
function getRoleCompatibility($role) {
    return $role; // Your existing roles match the workflow requirements
}
}

// =====================================
// APPLICATION CONFIGURATION
// =====================================

define('APP_NAME', 'Exam Management System');
define('APP_VERSION', '1.0.0');
define('TIMEZONE', 'Africa/Kampala');
define('DATE_FORMAT', 'Y-m-d H:i:s');

date_default_timezone_set(TIMEZONE);

// =====================================
// SECURITY CONFIGURATION
// =====================================

// Only set session configuration if no session is currently active
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_only_cookies', 1);
    ini_set('session.cookie_secure', 0);
    ini_set('session.cookie_samesite', 'Strict');
}

define('SESSION_TIMEOUT', 3600); // 1 hour

// =====================================
// ERROR HANDLING
// =====================================

define('DISPLAY_ERRORS', 1); // Set to 0 in production
define('LOG_ERRORS', 1);
define('ERROR_LOG_FILE', __DIR__ . '/logs/error.log');

if (DISPLAY_ERRORS) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
}

// =====================================
// PUBLISHING WORKFLOW CONFIGURATION
// =====================================

// Exam status constants for publishing workflow
define('EXAM_STATUS_DRAFT', 'Draft');
define('EXAM_STATUS_PENDING_REVIEW', 'Pending Review');
define('EXAM_STATUS_CHANGES_REQUESTED', 'Changes Requested');
define('EXAM_STATUS_PUBLISHED', 'Published');

// Subject status constants
define('SUBJECT_STATUS_DRAFT', 'Draft');
define('SUBJECT_STATUS_CAPTURED', 'Captured');
define('SUBJECT_STATUS_PUBLISHED', 'Published');

define('MAX_UPLOAD_SIZE', 10 * 1024 * 1024); // 10MB

// =====================================
// UTILITY FUNCTIONS
// =====================================

/**
 * Check if user has required role (updated for compatibility)
 */
if (!function_exists('check_user_role')) {
function check_user_role($required_role) {
    // Handle both old and new role constants
    $user_role = $_SESSION['role'] ?? null;
    
    // Convert new role format to old if needed
    $old_role = null;
    switch($required_role) {
        case 2: $old_role = ROLE_TEACHER; break;    // NEW_ROLE_TEACHER
        case 1: $old_role = ROLE_ADMIN; break;      // NEW_ROLE_ADMIN
        default: $old_role = $required_role; break; // Use as-is
    }
    
    if (!$user_role || $user_role != $old_role) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Access denied']);
        exit;
    }
}
}

/**
 * Check if user is logged in
 */
if (!function_exists('check_login')) {
function check_login() {
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['school_id'])) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Not authenticated']);
        exit;
    }
}
}

/**
 * Check role access (compatible with your existing system)
 */
if (!function_exists('check_role_access')) {
function check_role_access($required_role) {
    if (!isset($_SESSION["id"]) || !isset($_SESSION["school_id"])) {
        header("Location: login.php");
        exit;
    }
    
    $current_user_school_id = $_SESSION["school_id"];
    $user_role = $_SESSION["role"];
    
    // Handle role compatibility
    $compatible_role = getRoleCompatibility($required_role);
    
    if ($user_role != $compatible_role) {
        http_response_code(403);
        die("Access denied. You do not have permission to access this page.");
    }
}
}

/**
 * Sanitize output for HTML display
 */
if (!function_exists('escapeHtml')) {
function escapeHtml($text) {
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
}

/**
 * Log error to file
 */
if (!function_exists('logError')) {
function logError($message, $context = []) {
    if (!LOG_ERRORS) return;
    
    if (!is_dir(__DIR__ . '/logs')) {
        mkdir(__DIR__ . '/logs', 0755, true);
    }
    
    $log_entry = [
        'timestamp' => date(DATE_FORMAT),
        'message' => $message,
        'context' => $context,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
    ];
    
    $log_line = json_encode($log_entry) . "\n";
    file_put_contents(ERROR_LOG_FILE, $log_line, FILE_APPEND | LOCK_EX);
}
}

/**
 * Get current school ID from session
 */
if (!function_exists('get_current_school_id')) {
function get_current_school_id() {
    return $_SESSION['school_id'] ?? null;
}
}

/**
 * Get current user ID from session
 */
if (!function_exists('get_current_user_id')) {
function get_current_user_id() {
    return $_SESSION['user_id'] ?? null;
}
}

/**
 * Check if database connection is working
 */
if (!function_exists('isDatabaseConnected')) {
function isDatabaseConnected() {
    global $conn;
    return ($conn && $conn->ping());
}
}

// =====================================
// INITIALIZATION
// =====================================

/**
 * Start session with configured settings
 */
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Set session timeout
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > SESSION_TIMEOUT)) {
    session_unset();
    session_destroy();
    session_start();
}
$_SESSION['LAST_ACTIVITY'] = time();

// Create logs directory if it doesn't exist
if (!is_dir(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0755, true);
}

// =====================================
// DEVELOPMENT HELPERS
// =====================================

/**
 * Helper function to debug variables
 */
if (!function_exists('debug')) {
function debug($var, $label = 'Debug') {
    if (DISPLAY_ERRORS) {
        echo "<pre><strong>$label:</strong> ";
        print_r($var);
        echo "</pre>";
    }
}
}

/**
 * Helper function to check database connection
 */
if (!function_exists('testDatabaseConnection')) {
function testDatabaseConnection() {
    global $conn;
    if ($conn && $conn->ping()) {
        return ['status' => 'success', 'message' => 'Database connected successfully'];
    } else {
        return ['status' => 'error', 'message' => 'Database connection failed'];
    }
}
}

// Log successful configuration load
if (function_exists('logError')) {
    logError("Configuration loaded successfully", ['config_file' => __FILE__]);
}

?>
