<?php
// ============================================
// BACKEND PHP - Gestión de settings.json y media
// ============================================

// Crear carpeta media si no existe
if (!file_exists('media')) {
    mkdir('media', 0755, true);
}
if (!file_exists('temp')) {
    mkdir('temp', 0755, true);
}

// Bases del explorador de archivos (almacenamiento local)
if (!file_exists('media/explorer/files')) {
    mkdir('media/explorer/files', 0755, true);
}
if (!file_exists('media/explorer/trash')) {
    mkdir('media/explorer/trash', 0755, true);
}
if (!file_exists('media/pwa')) {
    mkdir('media/pwa', 0755, true);
}
if (!file_exists('logs')) {
    mkdir('logs', 0755, true);
}
if (!file_exists('storage/users')) {
    mkdir('storage/users', 0700, true);
}
if (!file_exists('media/explorer/users')) {
    mkdir('media/explorer/users', 0755, true);
}
if (!file_exists('media/explorer/departments')) {
    mkdir('media/explorer/departments', 0755, true);
}

// Ruta al archivo de configuración
$settingsFile = 'settings.json';
$settingsBackupFile = 'settings.json.bak';

require __DIR__ . '/settings_helpers.php';
require_once __DIR__ . '/grid_default_settings.php';

$defaultSettings = grid_app_default_settings();

$gridSettingsRecoveryAlert = false;
$gridSettingsPersistFailed = false;
$settings = grid_load_settings_with_recovery($settingsFile, $settingsBackupFile, $defaultSettings, $gridSettingsRecoveryAlert, $gridSettingsPersistFailed);

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . $host . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . '/';

/** Raíz del proyecto (index.php); las APIs en includes/ usan esto en lugar de __DIR__. */
if (!defined('GRID_ROOT')) {
    define('GRID_ROOT', dirname(__DIR__));
}

function isMobile() {
    return preg_match('/(android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i', $_SERVER['HTTP_USER_AGENT'] ?? '');
}

