<?php
/**
 * MediFlash SOS+ Configuration
 * Main configuration file for the application
 */

// Database configuration
define('DB_HOST', $_ENV['DB_HOST'] ?? 'localhost');
define('DB_NAME', $_ENV['DB_NAME'] ?? 'mediflash_sos');
define('DB_USER', $_ENV['DB_USER'] ?? 'root');
define('DB_PASS', $_ENV['DB_PASS'] ?? '');
define('DB_CHARSET', 'utf8mb4');

// Application settings
define('APP_NAME', 'MediFlash SOS+');
define('APP_VERSION', '1.0.0');
define('APP_ENV', $_ENV['APP_ENV'] ?? 'development');
define('APP_DEBUG', $_ENV['APP_DEBUG'] ?? true);
define('APP_URL', $_ENV['APP_URL'] ?? 'http://localhost:5000');

// Security settings
define('JWT_SECRET', $_ENV['JWT_SECRET'] ?? 'mediflash-secret-key-change-in-production');
define('HASH_ALGO', PASSWORD_DEFAULT);
define('SESSION_LIFETIME', 3600 * 24 * 7); // 1 week

// Economic model configuration - Fixed values as per specifications
define('SERVICE_FEE', 500); // FCFA - MediFlash service fee
define('DELIVERY_MIN', 600); // FCFA - Minimum delivery fee  
define('DELIVERY_PER_KM', 100); // FCFA per km - Distance-based delivery fee
define('PHARMACY_BONUS_FROM_DELIVERY', 100); // FCFA - Bonus for pharmacy from delivery fee

// Operational settings
define('MAX_DELIVERY_DISTANCE', 50); // km - Maximum delivery distance
define('ORDER_TIMEOUT', 120); // seconds - Pharmacy response timeout
define('DEFAULT_LOCATION', [5.3364, -4.0267]); // Abidjan coordinates
define('MAP_ZOOM_DEFAULT', 13);

// File upload settings
define('UPLOAD_MAX_SIZE', 10 * 1024 * 1024); // 10MB
define('UPLOAD_ALLOWED_TYPES', ['image/jpeg', 'image/png', 'application/pdf']);
define('UPLOAD_PATH', __DIR__ . '/../storage/uploads/');

// API settings
define('API_RATE_LIMIT', 100); // requests per minute
define('API_VERSION', 'v1');

// Email/SMS configuration (for notifications)
define('MAIL_HOST', $_ENV['MAIL_HOST'] ?? 'smtp.gmail.com');
define('MAIL_PORT', $_ENV['MAIL_PORT'] ?? 587);
define('MAIL_USERNAME', $_ENV['MAIL_USERNAME'] ?? '');
define('MAIL_PASSWORD', $_ENV['MAIL_PASSWORD'] ?? '');
define('MAIL_FROM', $_ENV['MAIL_FROM'] ?? 'noreply@mediflash.ci');
define('MAIL_FROM_NAME', $_ENV['MAIL_FROM_NAME'] ?? 'MediFlash SOS+');

define('SMS_API_KEY', $_ENV['SMS_API_KEY'] ?? '');
define('SMS_API_URL', $_ENV['SMS_API_URL'] ?? '');

// External services
define('MAPS_API_KEY', $_ENV['MAPS_API_KEY'] ?? '');
define('PAYMENT_API_KEY', $_ENV['PAYMENT_API_KEY'] ?? '');

// Logging
define('LOG_LEVEL', $_ENV['LOG_LEVEL'] ?? 'info');
define('LOG_PATH', __DIR__ . '/../storage/logs/');

// Cache settings
define('CACHE_ENABLED', $_ENV['CACHE_ENABLED'] ?? false);
define('CACHE_DRIVER', $_ENV['CACHE_DRIVER'] ?? 'file');
define('CACHE_TTL', 3600); // 1 hour

// Error handling
if (APP_ENV === 'production') {
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', LOG_PATH . 'php_errors.log');
} else {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
}

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

// Session configuration
ini_set('session.cookie_lifetime', SESSION_LIFETIME);
ini_set('session.cookie_secure', APP_ENV === 'production' ? 1 : 0);
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);

// CORS settings for API
define('CORS_ALLOWED_ORIGINS', $_ENV['CORS_ALLOWED_ORIGINS'] ?? '*');
define('CORS_ALLOWED_METHODS', 'GET,POST,PUT,DELETE,OPTIONS');
define('CORS_ALLOWED_HEADERS', 'Content-Type,Authorization,X-Requested-With');

// Create necessary directories
$directories = [
    __DIR__ . '/../storage',
    __DIR__ . '/../storage/logs',
    __DIR__ . '/../storage/uploads',
    __DIR__ . '/../storage/cache',
    __DIR__ . '/../storage/sessions'
];

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

// Helper function to get configuration values from database
function getConfigValue($key, $default = null) {
    static $config_cache = null;
    
    if ($config_cache === null) {
        try {
            $db = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
                DB_USER,
                DB_PASS,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            
            $stmt = $db->query("SELECT `key`, `value` FROM settings");
            $config_cache = [];
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $config_cache[$row['key']] = $row['value'];
            }
        } catch (Exception $e) {
            // If database is not available, use default values
            $config_cache = [
                'SERVICE_FEE' => SERVICE_FEE,
                'DELIVERY_MIN' => DELIVERY_MIN,
                'DELIVERY_PER_KM' => DELIVERY_PER_KM,
                'PHARMACY_BONUS_FROM_DELIVERY' => PHARMACY_BONUS_FROM_DELIVERY
            ];
        }
    }
    
    return $config_cache[$key] ?? $default;
}

// Update economic constants from database if available
if (function_exists('getConfigValue')) {
    define('SERVICE_FEE_CURRENT', (int)getConfigValue('SERVICE_FEE', SERVICE_FEE));
    define('DELIVERY_MIN_CURRENT', (int)getConfigValue('DELIVERY_MIN', DELIVERY_MIN));
    define('DELIVERY_PER_KM_CURRENT', (int)getConfigValue('DELIVERY_PER_KM', DELIVERY_PER_KM));
    define('PHARMACY_BONUS_CURRENT', (int)getConfigValue('PHARMACY_BONUS_FROM_DELIVERY', PHARMACY_BONUS_FROM_DELIVERY));
}

// Auto-loading function for classes
spl_autoload_register(function ($className) {
    $baseDir = __DIR__ . '/../app/';
    $file = $baseDir . str_replace('\\', '/', $className) . '.php';
    
    if (file_exists($file)) {
        require $file;
    }
});
?>
