<?php

// Private runtime configuration.
// Este archivo no debe versionarse ni incluirse en ZIPs públicos.
$privateConfigPath = __DIR__ . '/private_config.php';

if (file_exists($privateConfigPath)) {
    require_once $privateConfigPath;
}

// Google Maps backend key.
// Usada por endpoints PHP: api/geo/maps_suggest.php, maps_place.php y backfill.
if (!defined('GOOGLE_MAPS_API_KEY')) {
    define(
        'GOOGLE_MAPS_API_KEY',
        defined('ICYLAB_GOOGLE_MAPS_SERVER_KEY') ? trim((string) ICYLAB_GOOGLE_MAPS_SERVER_KEY) : ''
    );
}

// Google Maps frontend key.
// Sólo usar si se implementa mapa visual en navegador.
if (!defined('GOOGLE_MAPS_BROWSER_KEY')) {
    define(
        'GOOGLE_MAPS_BROWSER_KEY',
        defined('ICYLAB_GOOGLE_MAPS_BROWSER_KEY') ? trim((string) ICYLAB_GOOGLE_MAPS_BROWSER_KEY) : ''
    );
}

// Google Maps Map ID.
// Sólo usar si se implementa gmp-map / Advanced Markers.
if (!defined('GOOGLE_MAPS_MAP_ID')) {
    define(
        'GOOGLE_MAPS_MAP_ID',
        defined('ICYLAB_GOOGLE_MAPS_MAP_ID') ? trim((string) ICYLAB_GOOGLE_MAPS_MAP_ID) : ''
    );
}

define('APP_NAME', 'ICYLAB OS');
define('APP_URL', 'https://app.icylab.cl');
define('APP_ENV', 'production');

// Polyfills mínimos para servidores PHP sin extensión mbstring.
// Evita errores fatales en navegación, usuarios, clientes, productos y embudo.
if (!function_exists('mb_strlen')) {
    function mb_strlen($string, $encoding = null) {
        return strlen((string)$string);
    }
}
if (!function_exists('mb_substr')) {
    function mb_substr($string, $start, $length = null, $encoding = null) {
        $string = (string)$string;
        return $length === null ? substr($string, $start) : substr($string, $start, $length);
    }
}
if (!function_exists('mb_strtolower')) {
    function mb_strtolower($string, $encoding = null) {
        return strtolower((string)$string);
    }
}



// Runtime secrets.
// Las credenciales reales deben vivir en core/private_config.php o variables de entorno.
if (!defined('DB_HOST')) {
    define('DB_HOST', defined('ICYLAB_DB_HOST') ? ICYLAB_DB_HOST : (getenv('ICYLAB_DB_HOST') ?: 'localhost'));
}
if (!defined('DB_NAME')) {
    define('DB_NAME', defined('ICYLAB_DB_NAME') ? ICYLAB_DB_NAME : (getenv('ICYLAB_DB_NAME') ?: ''));
}
if (!defined('DB_USER')) {
    define('DB_USER', defined('ICYLAB_DB_USER') ? ICYLAB_DB_USER : (getenv('ICYLAB_DB_USER') ?: ''));
}
if (!defined('DB_PASS')) {
    define('DB_PASS', defined('ICYLAB_DB_PASS') ? ICYLAB_DB_PASS : (getenv('ICYLAB_DB_PASS') ?: ''));
}

if (!defined('GOOGLE_CLIENT_ID')) {
    define('GOOGLE_CLIENT_ID', defined('ICYLAB_GOOGLE_CLIENT_ID') ? ICYLAB_GOOGLE_CLIENT_ID : (getenv('ICYLAB_GOOGLE_CLIENT_ID') ?: ''));
}
if (!defined('GOOGLE_CLIENT_SECRET')) {
    define('GOOGLE_CLIENT_SECRET', defined('ICYLAB_GOOGLE_CLIENT_SECRET') ? ICYLAB_GOOGLE_CLIENT_SECRET : (getenv('ICYLAB_GOOGLE_CLIENT_SECRET') ?: ''));
}
if (!defined('GOOGLE_ALLOWED_DOMAIN')) {
    define('GOOGLE_ALLOWED_DOMAIN', defined('ICYLAB_GOOGLE_ALLOWED_DOMAIN') ? ICYLAB_GOOGLE_ALLOWED_DOMAIN : (getenv('ICYLAB_GOOGLE_ALLOWED_DOMAIN') ?: 'icylab.cl'));
}

if (!defined('CLICKUP_API_TOKEN')) {
    define('CLICKUP_API_TOKEN', defined('ICYLAB_CLICKUP_API_TOKEN') ? ICYLAB_CLICKUP_API_TOKEN : (getenv('ICYLAB_CLICKUP_API_TOKEN') ?: ''));
}

if (!defined('FACTO_API_BASE_URL')) {
    define('FACTO_API_BASE_URL', defined('ICYLAB_FACTO_API_BASE_URL') ? ICYLAB_FACTO_API_BASE_URL : (getenv('ICYLAB_FACTO_API_BASE_URL') ?: 'https://api-billing.koywe.com/V1'));
}
if (!defined('FACTO_CLIENT_ID')) {
    define('FACTO_CLIENT_ID', defined('ICYLAB_FACTO_CLIENT_ID') ? ICYLAB_FACTO_CLIENT_ID : (getenv('ICYLAB_FACTO_CLIENT_ID') ?: ''));
}
if (!defined('FACTO_CLIENT_SECRET')) {
    define('FACTO_CLIENT_SECRET', defined('ICYLAB_FACTO_CLIENT_SECRET') ? ICYLAB_FACTO_CLIENT_SECRET : (getenv('ICYLAB_FACTO_CLIENT_SECRET') ?: ''));
}
if (!defined('FACTO_USERNAME')) {
    define('FACTO_USERNAME', defined('ICYLAB_FACTO_USERNAME') ? ICYLAB_FACTO_USERNAME : (getenv('ICYLAB_FACTO_USERNAME') ?: ''));
}
if (!defined('FACTO_PASSWORD')) {
    define('FACTO_PASSWORD', defined('ICYLAB_FACTO_PASSWORD') ? ICYLAB_FACTO_PASSWORD : (getenv('ICYLAB_FACTO_PASSWORD') ?: ''));
}


// SMTP / Notificaciones.
// Configurar preferentemente en core/private_config.php o variables de entorno.
if (!defined('SMTP_HOST')) {
    define('SMTP_HOST', defined('ICYLAB_SMTP_HOST') ? ICYLAB_SMTP_HOST : (getenv('ICYLAB_SMTP_HOST') ?: ''));
}
if (!defined('SMTP_PORT')) {
    define('SMTP_PORT', defined('ICYLAB_SMTP_PORT') ? (int) ICYLAB_SMTP_PORT : (int) (getenv('ICYLAB_SMTP_PORT') ?: 587));
}
if (!defined('SMTP_SECURE')) {
    define('SMTP_SECURE', defined('ICYLAB_SMTP_SECURE') ? ICYLAB_SMTP_SECURE : (getenv('ICYLAB_SMTP_SECURE') ?: 'tls'));
}
if (!defined('SMTP_USERNAME')) {
    define('SMTP_USERNAME', defined('ICYLAB_SMTP_USERNAME') ? ICYLAB_SMTP_USERNAME : (getenv('ICYLAB_SMTP_USERNAME') ?: ''));
}
if (!defined('SMTP_PASSWORD')) {
    define('SMTP_PASSWORD', defined('ICYLAB_SMTP_PASSWORD') ? ICYLAB_SMTP_PASSWORD : (getenv('ICYLAB_SMTP_PASSWORD') ?: ''));
}
if (!defined('SMTP_EHLO_DOMAIN')) {
    define('SMTP_EHLO_DOMAIN', defined('ICYLAB_SMTP_EHLO_DOMAIN') ? ICYLAB_SMTP_EHLO_DOMAIN : (getenv('ICYLAB_SMTP_EHLO_DOMAIN') ?: 'app.icylab.cl'));
}
if (!defined('NOTIFICATIONS_EMAIL_FROM')) {
    define('NOTIFICATIONS_EMAIL_FROM', defined('ICYLAB_NOTIFICATIONS_EMAIL_FROM') ? ICYLAB_NOTIFICATIONS_EMAIL_FROM : (getenv('ICYLAB_NOTIFICATIONS_EMAIL_FROM') ?: 'no-reply@app.icylab.cl'));
}
if (!defined('NOTIFICATIONS_EMAIL_FROM_NAME')) {
    define('NOTIFICATIONS_EMAIL_FROM_NAME', defined('ICYLAB_NOTIFICATIONS_EMAIL_FROM_NAME') ? ICYLAB_NOTIFICATIONS_EMAIL_FROM_NAME : (getenv('ICYLAB_NOTIFICATIONS_EMAIL_FROM_NAME') ?: 'ICYLAB OS'));
}

function get_system_modules($only_active = false) {
    $pdo = db();
    
    // 1. Leer la configuración guardada por el Admin
    $stmt = $pdo->query("SELECT modules_config FROM system_settings WHERE id = 1");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $saved_config = [];
    if ($row && !empty($row['modules_config'])) {
        $saved_config = json_decode($row['modules_config'], true) ?: [];
    }

    $modules_dir = __DIR__ . '/../modules/';
    $modules = [];
    
    // 2. Metadatos por defecto (Si el Admin nunca los ha modificado)
    $known_metadata = [
        'calendar'    => ['title' => 'Calendario', 'icon' => 'calendar-days', 'section' => 'Empresa', 'order' => 5],
        'operations'  => ['title' => 'Producción', 'icon' => 'flask-conical', 'section' => 'Operación', 'order' => 10],
        'quality'     => ['title' => 'Calidad', 'icon' => 'shield-check', 'section' => 'Operación', 'order' => 20],
        'stock'       => ['title' => 'Stock', 'icon' => 'boxes', 'section' => 'Operación', 'order' => 30],
        'dispatch'    => ['title' => 'Despacho', 'icon' => 'truck', 'section' => 'Operación', 'order' => 40],
        'commercial'  => ['title' => 'Dashboard Com.', 'icon' => 'line-chart', 'section' => 'Comercial', 'order' => 50],
        'crm'         => ['title' => 'CRM', 'icon' => 'briefcase-business', 'section' => 'Comercial', 'order' => 60],
        'customers'   => ['title' => 'Clientes', 'icon' => 'users', 'section' => 'Comercial', 'order' => 70],
        'products'    => ['title' => 'Productos', 'icon' => 'package', 'section' => 'Comercial', 'order' => 80],
        'billing'     => ['title' => 'Facturacion', 'icon' => 'file-text', 'section' => 'Finanzas', 'order' => 90],
        'notifications' => ['title' => 'Notificaciones', 'icon' => 'bell', 'section' => 'Empresa', 'order' => 100]
    ];

    if (is_dir($modules_dir)) {
        // Ignoramos archivos del sistema y módulos maestros (dashboard/admin)
        $dirs = array_diff(scandir($modules_dir), ['..', '.', '.DS_Store', 'dashboard', 'admin']);
        
        foreach ($dirs as $dir) {
            if (is_dir($modules_dir . '/' . $dir)) {
                
                $mod_data = $known_metadata[$dir] ?? [
                    'title' => ucfirst(str_replace('_', ' ', $dir)),
                    'icon' => 'folder',
                    'section' => 'Otros Módulos',
                    'order' => 99 // Al final de la lista
                ];
                
                // 3. Sobrescribir con la BD si el Admin hizo cambios
                if (isset($saved_config[$dir])) {
                    $mod_data['title'] = $saved_config[$dir]['title'];
                    $mod_data['icon'] = $saved_config[$dir]['icon'];
                    $mod_data['section'] = $saved_config[$dir]['section'];
                    $mod_data['order'] = (int)$saved_config[$dir]['order'];
                    $mod_data['is_active'] = (int)$saved_config[$dir]['is_active'];
                } else {
                    $mod_data['is_active'] = 1; // Módulos nuevos son activos por defecto
                }
                
                // 4. Filtrar si se solicitó ocultar los inactivos
                if ($only_active && $mod_data['is_active'] === 0) {
                    continue;
                }
                
                $modules[$dir] = $mod_data;
            }
        }
    }
    
    // 5. Ordenar por el campo 'order' ascendente
    uasort($modules, function($a, $b) {
        return $a['order'] <=> $b['order'];
    });
    
    return $modules;
}