<?php
// CoreFlux/app/bootstrap.php

// --- 1. Define Core Path Constants ---
define('ROOT_PATH', dirname(dirname(__FILE__)));
define('FS_APP_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'app');
define('FS_CORE_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'core');
define('FS_PUBLIC_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'public');
define('FS_STORAGE_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'storage');
define('FS_VENDOR_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'vendor');
define('FS_CONFIG_PATH', FS_APP_PATH . DIRECTORY_SEPARATOR . 'config');

// --- 2. Load Composer's Autoloader ---
require_once FS_VENDOR_PATH . DIRECTORY_SEPARATOR . 'autoload.php';

// --- 3. Load Environment Variables ---
use Dotenv\Dotenv;
if (file_exists(ROOT_PATH . DIRECTORY_SEPARATOR . '.env')) {
    $dotenv = Dotenv::createImmutable(ROOT_PATH);
    $dotenv->load();
}

// --- 4. Load Core Configuration ---
$appConfig = require_once FS_CONFIG_PATH . DIRECTORY_SEPARATOR . 'app.php';
$databaseConfig = require_once FS_CONFIG_PATH . DIRECTORY_SEPARATOR . 'database.php';
$maintenanceConfig = require_once FS_CONFIG_PATH . DIRECTORY_SEPARATOR . 'maintenance.php';

// Core Constants
define('APP_URL', $appConfig['url']);
define('APP_NAME', $appConfig['name']);
define('MEDIA_URL', APP_URL . '/media');
define('CURRENCY', $appConfig['freight']['default_currency'] ?? 'USD');

// Contact & Brand Constants
define('COMPANY_NAME', APP_NAME);
define('SALES_PHONE', $appConfig['contact']['sales_phone']);
define('SUPPORT_PHONE', $appConfig['contact']['support_phone']);
define('WHATSAPP_NUMBER', $appConfig['contact']['whatsapp']);
define('COMPANY_ADDRESS', $appConfig['contact']['address']);

// Email Constants
define('CONTACT_EMAIL', $appConfig['contact']['general_email']);
define('SALES_EMAIL', $appConfig['contact']['sales_email']);
define('SUPPORT_EMAIL', $appConfig['contact']['support_email']);
define('PROJECTS_EMAIL', $appConfig['contact']['projects_email']);

// --- 5. Define SMTP Constants ---
if (isset($appConfig['mail'])) {
    define('MAIL_HOST', $appConfig['mail']['host']);
    define('MAIL_PORT', $appConfig['mail']['port']);
    define('MAIL_USERNAME', $appConfig['mail']['username']);
    define('MAIL_PASSWORD', $appConfig['mail']['password']);
    define('MAIL_ENCRYPTION', $appConfig['mail']['encryption']); 
    define('MAIL_FROM_EMAIL', $appConfig['mail']['from_email']);
    define('MAIL_FROM_NAME', $appConfig['mail']['from_name']);
}

// --- 6. Define Freight & Logistics Constants ---
if(isset($appConfig['freight'])) {
    define('DEFAULT_WEIGHT_UNIT', $appConfig['freight']['default_weight_unit'] ?? 'KG');
}

// --- 7. Initialize Database ---
use Core\Database\Connection;

try {
    Connection::init($databaseConfig);
} catch (Exception $e) {
    // http_response_code(500);
    // die("<h1>500 Internal Server Error</h1><p>Database connection failed: " . $e->getMessage() . "</p>");
    
    Core\Response::abort(500);
}