<?php
/**
 * Agricultural Information System (AIMS) - Main Configuration
 * Developed by: Musumba Jonathan 21/BCS/010/UMC
 */

// Prevent direct access
defined('AIMS_ACCESS') or define('AIMS_ACCESS', true);

// Load environment variables FIRST
require_once __DIR__ . '/../vendor/autoload.php';

use Dotenv\Dotenv;

// Load .env file
$dotenv = Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();

// Error Reporting based on environment
if ($_ENV['APP_ENV'] === 'production') {
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/error.log');
} else {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
}

// Timezone
date_default_timezone_set($_ENV['APP_TIMEZONE']);

// Application Constants
define('APP_NAME', $_ENV['APP_NAME']);
define('APP_VERSION', $_ENV['APP_VERSION']);
define('APP_URL', $_ENV['APP_URL']);
define('APP_ENV', $_ENV['APP_ENV']);
define('APP_DEBUG', $_ENV['APP_DEBUG'] === 'true');

// Database Constants
define('DB_HOST', $_ENV['DB_HOST']);
define('DB_PORT', $_ENV['DB_PORT']);
define('DB_NAME', $_ENV['DB_NAME']);
define('DB_USER', $_ENV['DB_USER']);
define('DB_PASS', $_ENV['DB_PASS']);
define('DB_CHARSET', $_ENV['DB_CHARSET']);

// Security Constants
define('SESSION_LIFETIME', (int)$_ENV['SESSION_LIFETIME']);
define('SESSION_NAME', $_ENV['SESSION_NAME']);
define('ENCRYPTION_KEY', $_ENV['ENCRYPTION_KEY']);
define('CSRF_TOKEN_NAME', $_ENV['CSRF_TOKEN_NAME']);

// File Upload Constants
define('UPLOAD_PATH', __DIR__ . '/../' . $_ENV['UPLOAD_PATH']);
define('MAX_FILE_SIZE', (int)$_ENV['MAX_FILE_SIZE']);
define('ALLOWED_IMAGE_TYPES', explode(',', $_ENV['ALLOWED_IMAGE_TYPES']));
define('ALLOWED_DOC_TYPES', explode(',', $_ENV['ALLOWED_DOC_TYPES']));

// API Keys
define('OPENAI_API_KEY', $_ENV['OPENAI_API_KEY']);
define('OPENAI_MODEL', $_ENV['OPENAI_MODEL']);
define('AT_USERNAME', $_ENV['AT_USERNAME']);
define('AT_API_KEY', $_ENV['AT_API_KEY']);
define('WEATHER_API_KEY', $_ENV['WEATHER_API_KEY']);

// Pagination
define('ITEMS_PER_PAGE', (int)$_ENV['ITEMS_PER_PAGE']);
define('PRODUCTS_PER_PAGE', (int)$_ENV['PRODUCTS_PER_PAGE']);

// ============================================================================
// SESSION CONFIGURATION - MUST BE BEFORE SESSION START
// ============================================================================
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_samesite', 'Lax');
ini_set('session.cookie_lifetime', SESSION_LIFETIME);
ini_set('session.gc_maxlifetime', SESSION_LIFETIME);

// Enable in production with HTTPS
if (APP_ENV === 'production') {
    ini_set('session.cookie_secure', 1);
}

// Set session name BEFORE starting session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Create necessary directories
$directories = [
    UPLOAD_PATH,
    UPLOAD_PATH . 'products/',
    UPLOAD_PATH . 'profiles/',
    UPLOAD_PATH . 'chat/',
    UPLOAD_PATH . 'documents/',
    __DIR__ . '/../logs/',
    __DIR__ . '/../cache/'
];

foreach ($directories as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
}

// Include required files
require_once __DIR__ . '/constants.php';
require_once __DIR__ . '/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/helpers.php';

// Note: We don't include session.php here anymore since we handle session start above
// Instead, include only the session helper functions
require_once __DIR__ . '/session_helpers.php';

// Autoload classes
spl_autoload_register(function ($class) {
    $prefix = 'App\\';
    $base_dir = __DIR__ . '/../classes/';
    
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    
    if (file_exists($file)) {
        require $file;
    }
});
?>