<?php
// FILE: /digitalpremium/pages/configuraciones.php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['id_usuario'])) {
    header("Location: /digitalpremium/login.php");
    exit();
}

require_once '../config/db.php';
$page_title = "Configuración del Sistema - DigitalPremium";
include_once '../includes/header.php';

$id_usuario_sesion = $_SESSION['id_usuario'];
$rol = strtolower($_SESSION['rol'] ?? '');

$canViewAdvanced = in_array($rol, ['admin','superadmin'], true); // quién ve las configuraciones
$canEdit         = ($rol === 'superadmin');                      // quién puede guardar

/* CSRF token para el form de guardado */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* ============ CARGA DE CONFIGS SOLO SI HAY PERMISO DE VER ============ */
$grouped_configs = [];
if ($canViewAdvanced) {
    // Configs por usuario
    $stmt_user_cfg = $pdo->prepare("SELECT * FROM configuraciones WHERE id_usuario = ? ORDER BY grupo_config, orden_grupo, nombre_visible");
    $stmt_user_cfg->execute([$id_usuario_sesion]);
    $user_cfg_rows = $stmt_user_cfg->fetchAll(PDO::FETCH_ASSOC);

    // Configs globales
    $stmt_global_cfg = $pdo->prepare("SELECT * FROM configuraciones WHERE id_usuario IS NULL ORDER BY grupo_config, orden_grupo, nombre_visible");
    $stmt_global_cfg->execute();
    $global_cfg_rows = $stmt_global_cfg->fetchAll(PDO::FETCH_ASSOC);

    if (empty($user_cfg_rows) && empty($global_cfg_rows)) {
        echo '<div class="alert alert-danger container-custom mt-4">Error: No se encontraron configuraciones. Contacte al administrador.</div>';
        include_once '../includes/footer.php';
        exit();
    }

    // Mapear y unir por clave (usuario tiene prioridad visual)
    $userMap = []; foreach ($user_cfg_rows as $r) $userMap[$r['clave_config']] = $r;
    $globalMap = []; foreach ($global_cfg_rows as $r) $globalMap[$r['clave_config']] = $r;

    $allKeys = array_unique(array_merge(array_keys($globalMap), array_keys($userMap)));
    $merged = [];
    foreach ($allKeys as $k) {
        if (isset($userMap[$k])) {
            $row = $userMap[$k];
            $row['_scope'] = 'user';
            $row['_valor_global'] = $globalMap[$k]['valor_config'] ?? null;
        } else {
            $row = $globalMap[$k];
            $row['_scope'] = 'global';
            $row['_valor_global'] = $row['valor_config'];
        }
        if (empty($row['grupo_config'])) $row['grupo_config'] = 'General';
        $merged[] = $row;
    }

    foreach ($merged as $config_item) {
        $grouped_configs[$config_item['grupo_config']][] = $config_item;
    }
}

/* ============ DATOS DE MEMBRESÍA (para todos) ============ */
$stmt_user = $pdo->prepare("SELECT fecha_fin_membresia, nombre_completo FROM usuarios WHERE id_usuario = ?");
$stmt_user->execute([$id_usuario_sesion]);
$user_data = $stmt_user->fetch(PDO::FETCH_ASSOC);

$membership_end_date = $user_data['fecha_fin_membresia'] ?? null;
$days_left = 'N/A';
if ($membership_end_date) {
    $current_date = new DateTime();
    $end_date = new DateTime($membership_end_date);
    $days_left = ($end_date > $current_date) ? $current_date->diff($end_date)->days : 'Vencida';
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($page_title); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
    :root {
        --primary-color: #007bff; --secondary-color:#6c757d; --success-color:#28a745; --danger-color:#dc3545;
        --warning-color:#ffc107; --info-color:#17a2b8; --light-bg:#f8f9fa; --dark-text:#343a40;
    }
    body{background:#f0f2f5;font-family:'Inter',sans-serif;color:#343a40;font-size:.95rem;min-height:100vh;display:flex;flex-direction:column}
    .main-content{flex-grow:1;padding-bottom:90px}
    .container-custom{max-width:960px;margin-left:auto;margin-right:auto;padding:0 1.5rem}
    .page-header{margin-top:2.5rem;margin-bottom:2rem;padding-bottom:1rem;border-bottom:1px solid #e9ecef;text-align:center}
    .page-title{font-size:2.5rem;font-weight:700;color:#212529;display:inline-flex;align-items:center}
    .page-title i{font-size:1.1em;color:#6a6ee0;margin-right:.75rem}
    .card{border:none;box-shadow:0 .8rem 1.8rem rgba(0,0,0,.08);border-radius:1rem;background:#fff}
    .card-header{background:#f8f9fa !important;border-bottom:1px solid #e9ecef;padding:1.5rem 2rem;border-top-left-radius:1rem;border-top-right-radius:1rem}
    .form-label{font-weight:600;color:#495057}
    .form-control,.form-select{border-radius:.6rem;border:1px solid #ced4da;font-size:.9rem;padding:.75rem 1rem}
    .form-control:focus,.form-select:focus{border-color:#6a6ee0;box-shadow:0 0 0 .2rem rgba(106,110,224,.25)}
    .form-text{font-size:.85rem;color:#6c757d !important;margin-top:.4rem}
    .btn-save-sticky{position:fixed;bottom:0;left:0;width:100%;padding:1.25rem 0;background:#fff;border-top:1px solid #e9ecef;box-shadow:0 -.5rem 1rem rgba(0,0,0,.08);z-index:1000;display:flex;justify-content:center;align-items:center}
    .btn-save-sticky .btn-wrapper{max-width:960px;width:100%;display:flex;justify-content:flex-end;padding:0 1.5rem;gap:.5rem}
    .btn-success-main{background:#28a745;border:#28a745;color:#fff;font-weight:700;padding:1rem 2.5rem;border-radius:.6rem;font-size:1.05rem;transition:.2s;box-shadow:0 .3rem .8rem rgba(40,167,69,.2)}
    .btn-success-main[disabled]{opacity:.6;cursor:not-allowed}
    .tools-card{margin-top:3.5rem;margin-bottom:2.5rem !important;border:1px solid #d1e7dd;background:#d4edda;box-shadow:0 .5rem 1rem rgba(40,167,69,.1)}
    .membership-card{margin-top:2.5rem;margin-bottom:2.5rem;border:1px solid #cce5ff;background:#e0f2ff;box-shadow:0 .5rem 1rem rgba(0,123,255,.1)}
    .membership-card .card-header{background:#007bff !important;color:#fff !important}
    .password-card{margin-top:2.5rem;margin-bottom:2.5rem;border:1px solid #ffecb5;background:#fff8e1;box-shadow:0 .5rem 1rem rgba(255,193,7,.1)}
    @media (max-width: 991.98px){
        .container-custom{padding:0 1rem}
        .btn-save-sticky{padding:1rem 1rem;justify-content:center}
        .btn-save-sticky .btn-wrapper{padding:0;justify-content:center}
        .btn-success-main{padding:.8rem 1.8rem;font-size:.95rem}
    }
</style>
</head>
<body>

<div class="main-content">
    <div class="container-custom">
        <header class="page-header">
            <h1 class="page-title"><i class="fas fa-cog me-2"></i>Configuración del Sistema</h1>
            <?php if ($canViewAdvanced): ?>
                <div class="mt-2">
                    <span class="badge bg-primary-subtle text-primary border border-primary-subtle">
                        <?php echo ($canEdit ? 'Modo SUPER ADMIN' : 'Modo ADMIN (solo lectura)'); ?>
                    </span>
                </div>
            <?php endif; ?>
        </header>

        <?php if (isset($_GET['mensaje'])): ?>
            <div class="alert alert-<?php echo htmlspecialchars($_GET['tipo'] ?? 'info'); ?> alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars(urldecode($_GET['mensaje'])); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- ======= Sección visible para TODOS: Membresía ======= -->
        <div class="card shadow-sm mb-4 membership-card">
            <div class="card-header py-3">
                <h5 class="mb-0"><i class="fas fa-crown me-2"></i>Información de Membresía</h5>
            </div>
            <div class="card-body">
                <div class="row mb-2">
                    <div class="col-sm-4"><p class="membership-info mb-0"><strong>Usuario:</strong></p></div>
                    <div class="col-sm-8"><p class="membership-info mb-0"><?php echo htmlspecialchars($user_data['nombre_completo'] ?? 'N/A'); ?></p></div>
                </div>
                <div class="row mb-2">
                    <div class="col-sm-4"><p class="membership-info mb-0"><strong>Fecha Fin Membresía:</strong></p></div>
                    <div class="col-sm-8"><p class="membership-info mb-0"><?php echo $membership_end_date ? htmlspecialchars(date('d/m/Y', strtotime($membership_end_date))) : 'N/A'; ?></p></div>
                </div>
                <div class="row">
                    <div class="col-sm-4"><p class="membership-info mb-0"><strong>Días Restantes:</strong></p></div>
                    <div class="col-sm-8"><p class="membership-info mb-0 <?php echo ($days_left === 'Vencida') ? 'text-danger fw-bold' : 'text-success fw-bold'; ?>"><?php echo htmlspecialchars($days_left); ?></p></div>
                </div>
            </div>
        </div>

        <!-- ======= Sección visible para TODOS: Cambiar contraseña ======= -->
        <div class="card shadow-sm mb-4 password-card">
            <div class="card-header py-3">
                <h5 class="mb-0"><i class="fas fa-key me-2"></i>Cambiar Contraseña</h5>
            </div>
            <div class="card-body">
                <form id="passwordForm" action="/digitalpremium/actions/usuario_controlador.php" method="POST" autocomplete="off">
                    <input type="hidden" name="accion" value="cambiar_contrasena">
                    <input type="hidden" name="id_usuario" value="<?php echo (int)$_SESSION['id_usuario']; ?>">
                    <div class="mb-3 row align-items-center">
                        <label for="current_password" class="col-sm-4 col-form-label fw-medium">Contraseña Actual:</label>
                        <div class="col-sm-8"><input type="password" class="form-control" id="current_password" name="current_password" required></div>
                    </div>
                    <div class="mb-3 row align-items-center">
                        <label for="new_password" class="col-sm-4 col-form-label fw-medium">Nueva Contraseña:</label>
                        <div class="col-sm-8"><input type="password" class="form-control" id="new_password" name="new_password" required></div>
                    </div>
                    <div class="mb-3 row align-items-center">
                        <label for="confirm_new_password" class="col-sm-4 col-form-label fw-medium">Confirmar Nueva Contraseña:</label>
                        <div class="col-sm-8"><input type="password" class="form-control" id="confirm_new_password" name="confirm_new_password" required></div>
                    </div>
                    <div class="text-end">
                        <button type="submit" class="btn btn-warning"><i class="fas fa-save me-2"></i>Guardar Nueva Contraseña</button>
                    </div>
                </form>
            </div>
        </div>

        <?php if ($canViewAdvanced): ?>
        <!-- ======= Sección SOLO para ADMIN y SUPER ADMIN: Configuraciones ======= -->
        <form id="configForm" action="/digitalpremium/actions/configuracion_controlador.php" method="POST" autocomplete="off">
            <input type="hidden" name="accion" value="guardar_configuraciones">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">

            <?php foreach ($grouped_configs as $grupo_nombre => $configs_en_grupo): ?>
                <div class="card shadow-sm mb-4">
                    <div class="card-header py-3">
                        <h5 class="mb-0"><i class="fas fa-layer-group me-2"></i><?php echo htmlspecialchars($grupo_nombre); ?></h5>
                    </div>
                    <div class="card-body">
                        <?php
                        $first_item_in_group = true;
                        foreach ($configs_en_grupo as $config):
                            if (!$first_item_in_group) echo '<hr class="my-3">';
                            $first_item_in_group = false;

                            $clave = htmlspecialchars((string)$config['clave_config']);
                            $valor_raw = (string)$config['valor_config'];
                            $valor = htmlspecialchars($valor_raw);
                            $tipo_input = $config['tipo_input'];
                            $opciones_select_json = $config['opciones_select'];
                            $descripcion = $config['descripcion_config'] ?? '';
                            $disabledAttr = $canEdit ? '' : ' disabled';
                        ?>
                        <div class="mb-3 row align-items-center">
                            <label for="config_<?php echo $clave; ?>" class="col-sm-4 col-form-label fw-medium">
                                <?php echo htmlspecialchars($config['nombre_visible']); ?>:
                                <div class="text-muted small mt-1"><code><?php echo $clave; ?></code></div>
                            </label>
                            <div class="col-sm-8">
                                <?php
                                    $inputId = 'config_' . $clave;
                                    if ($tipo_input === 'number') {
                                        echo "<input type='number' class='form-control' id='{$inputId}' name='config[{$clave}]' value='{$valor}' step='1'{$disabledAttr}>";
                                    } elseif ($tipo_input === 'textarea') {
                                        echo "<textarea class='form-control' id='{$inputId}' name='config[{$clave}]' rows='3'{$disabledAttr}>{$valor}</textarea>";
                                    } elseif ($tipo_input === 'select') {
                                        $opciones = json_decode($opciones_select_json, true);
                                        if (is_array($opciones)) {
                                            echo "<select class='form-select' id='{$inputId}' name='config[{$clave}]'{$disabledAttr}>";
                                            foreach ($opciones as $val_opcion => $texto_opcion) {
                                                $sel = ((string)$val_opcion === $valor_raw) ? 'selected' : '';
                                                echo "<option value='" . htmlspecialchars((string)$val_opcion) . "' {$sel}>" . htmlspecialchars((string)$texto_opcion) . "</option>";
                                            }
                                            echo "</select>";
                                        } else {
                                            echo "<input type='text' class='form-control is-invalid' value='Error: opciones inválidas para {$clave}' disabled>";
                                        }
                                    } else {
                                        echo "<input type='text' class='form-control' id='{$inputId}' name='config[{$clave}]' value='{$valor}'{$disabledAttr}>";
                                    }

                                    if (!empty($descripcion)) {
                                        echo "<small class='form-text text-muted'>" . htmlspecialchars($descripcion) . "</small>";
                                    }
                                ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </form>

        <!-- Herramientas de datos (solo admin/superadmin) -->
        <div class="card shadow-lg mb-5 tools-card">
            <div class="card-header" style="background:#28a745;color:#fff">
                <h5 class="mb-0"><i class="fas fa-tools me-2"></i>Herramientas de Datos</h5>
            </div>
            <div class="card-body">
                <h5 class="card-title" style="color:#155724">Importar Cuentas y Perfiles desde Excel</h5>
                <p class="card-text" style="color:#155724">
                    Carga masiva de cuentas maestras y perfiles vendidos usando una plantilla de Excel.
                </p>
                <div class="d-grid gap-2 d-md-block">
                    <a href="importar_excel.php" class="btn btn-primary btn-lg me-md-2 mb-2 mb-md-0">
                        <i class="fas fa-file-import me-2"></i> Ir a Importar Excel
                    </a>
                    <a href="/digitalpremium/assets/templates/plantilla_importacion.xlsx" download="plantilla_importacion_digitalpremium.xlsx" class="btn btn-outline-success btn-lg">
                        <i class="fas fa-download me-2"></i> Descargar Plantilla Excel
                    </a>
                </div>
            </div>
        </div>
        <?php endif; // fin canViewAdvanced ?>

    </div>
</div>

<?php if ($canViewAdvanced): ?>
<!-- Barra fija inferior solo para admin/superadmin -->
<div class="btn-save-sticky">
    <div class="btn-wrapper">
        <?php if ($canEdit): ?>
            <button type="submit" form="configForm" class="btn btn-success-main" id="btnSave">
                <i class="fas fa-save me-2"></i>Guardar Cambios
            </button>
        <?php else: ?>
            <button type="button" class="btn btn-success-main" id="btnSave" disabled data-bs-toggle="tooltip" data-bs-title="Solo el SUPER ADMIN puede guardar">
                <i class="fas fa-lock me-2"></i>Guardar Cambios
            </button>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Limpiar mensajes de la URL
    if (window.location.search.includes('mensaje=')) {
        setTimeout(function() {
            var currentUrl = new URL(window.location.href);
            currentUrl.searchParams.delete('mensaje');
            currentUrl.searchParams.delete('tipo');
            window.history.replaceState({ path: currentUrl.href }, '', currentUrl.href);
        }, 5000);
    }

    // Tooltips (para el botón bloqueado de admin)
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    <?php if ($canEdit): ?>
    // Detectar cambios (solo superadmin)
    const form = document.getElementById('configForm');
    const btnSave = document.getElementById('btnSave');
    let isDirty = false;
    function markDirty(){
        isDirty = true;
        btnSave.disabled = false;
        window.onbeforeunload = () => "Tienes cambios sin guardar.";
    }
    form?.querySelectorAll('input, textarea, select').forEach(el => {
        el.addEventListener('change', markDirty);
        el.addEventListener('input', markDirty);
    });
    form?.addEventListener('submit', function(){
        btnSave.disabled = true;
        window.onbeforeunload = null;
    });
    <?php endif; ?>
});
</script>
</body>
</html>
