<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

check_role('administrador');

$user = get_logged_in_user();
$page_title = 'Configuración de Institución';

// Get current institution settings
$stmt = $pdo->query("SELECT * FROM institution_settings LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

// If no settings exist, create default ones
if (!$settings) {
    $pdo->exec("INSERT INTO institution_settings (institution_name) VALUES ('Bolsa de Trabajo')");
    $stmt = $pdo->query("SELECT * FROM institution_settings LIMIT 1");
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
    // Validate CSRF token
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $message = 'Token de seguridad inválido o caducado. Por favor, inténtelo de nuevo.';
        $message_type = 'danger';
    } else {
    try {
        // Handle logo upload
        $logo_path = $settings['institution_logo'] ?? null;
        if (isset($_FILES['institution_logo']) && $_FILES['institution_logo']['error'] === UPLOAD_ERR_OK) {
            // More secure file validation with fallback
            if (class_exists('finfo')) {
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $mime_type = $finfo->file($_FILES['institution_logo']['tmp_name']);
            } elseif (function_exists('mime_content_type')) {
                $mime_type = mime_content_type($_FILES['institution_logo']['tmp_name']);
            } else {
                $mime_type = $_FILES['institution_logo']['type'];
            }
            
            $upload_dir = BASE_PATH . '/uploads/institution/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $file_extension = strtolower(pathinfo($_FILES['institution_logo']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];

            if (in_array($file_extension, $allowed_extensions) && in_array($mime_type, ['image/jpeg', 'image/png', 'image/gif'])) {
                $filename = 'institution_logo_' . time() . '.' . $file_extension;
                $target_path = $upload_dir . $filename;

                if (move_uploaded_file($_FILES['institution_logo']['tmp_name'], $target_path)) {
                    // Delete old logo if exists
                    if ($logo_path && file_exists(BASE_PATH . '/' . $logo_path)) {
                        unlink(BASE_PATH . '/' . $logo_path);
                    }
                    $logo_path = 'uploads/institution/' . $filename;
                } else {
                    throw new Exception('Error al subir el logo');
                }
            } else {
                throw new Exception('Tipo de archivo no permitido. Solo se permiten JPG, PNG y GIF.');
            }
        }

        // Handle favicon upload
        $favicon_path = $settings['favicon'] ?? null;
        if (isset($_FILES['favicon']) && $_FILES['favicon']['error'] === UPLOAD_ERR_OK) {
            // Fallback for mime type detection
            if (class_exists('finfo')) {
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $mime_type = $finfo->file($_FILES['favicon']['tmp_name']);
            } elseif (function_exists('mime_content_type')) {
                $mime_type = mime_content_type($_FILES['favicon']['tmp_name']);
            } else {
                $mime_type = $_FILES['favicon']['type'];
            }

            $upload_dir = BASE_PATH . '/uploads/institution/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $file_extension = strtolower(pathinfo($_FILES['favicon']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['ico', 'png', 'jpg', 'jpeg', 'svg'];

            if (in_array($file_extension, $allowed_extensions) && in_array($mime_type, ['image/vnd.microsoft.icon', 'image/x-icon', 'image/png', 'image/jpeg', 'image/svg+xml'])) {
                $filename = 'favicon_' . time() . '.' . $file_extension;
                $target_path = $upload_dir . $filename;

                if (move_uploaded_file($_FILES['favicon']['tmp_name'], $target_path)) {
                    // Delete old favicon if exists
                    if ($favicon_path && file_exists(BASE_PATH . '/' . $favicon_path)) {
                        unlink(BASE_PATH . '/' . $favicon_path);
                    }
                    $favicon_path = 'uploads/institution/' . $filename;
                } else {
                    throw new Exception('Error al subir el favicon');
                }
            } else {
                throw new Exception('Tipo de archivo no permitido. Solo se permiten ICO, PNG, JPG, JPEG y SVG.');
            }
        }

        // Update settings
        $stmt = $pdo->prepare("UPDATE institution_settings SET
            institution_name = ?,
            institution_logo = ?,
            institution_description = ?,
            institution_address = ?,
            institution_phone = ?,
            institution_email = ?,
            institution_website = ?,
            contact_person = ?,
            contact_email = ?,
            contact_phone = ?,
            primary_color = ?,
            secondary_color = ?,
            accent_color = ?,
            success_color = ?,
            warning_color = ?,
            danger_color = ?,
            info_color = ?,
            light_bg_color = ?,
            dark_text_color = ?,
            sidebar_bg_color = ?,
            navbar_bg_color = ?,
            card_bg_color = ?,
            border_color = ?,
            shadow_color = ?,
            hover_bg_color = ?,
            active_bg_color = ?,
            favicon = ?,
            updated_at = NOW()
            WHERE id = ?");

        $stmt->execute([
            $_POST['institution_name'],
            $logo_path,
            $_POST['institution_description'],
            $_POST['institution_address'],
            $_POST['institution_phone'],
            $_POST['institution_email'],
            $_POST['institution_website'],
            $_POST['contact_person'],
            $_POST['contact_email'],
            $_POST['contact_phone'],
            $_POST['primary_color'],
            $_POST['secondary_color'],
            $_POST['accent_color'],
            $_POST['success_color'],
            $_POST['warning_color'],
            $_POST['danger_color'],
            $_POST['info_color'],
            $_POST['light_bg_color'],
            $_POST['dark_text_color'],
            $_POST['sidebar_bg_color'] ?? '#27538C',
            $_POST['navbar_bg_color'] ?? '#FFFFFF',
            $_POST['card_bg_color'] ?? '#FFFFFF',
            $_POST['border_color'] ?? '#E9ECEF',
            $_POST['shadow_color'] ?? 'rgba(0,0,0,0.1)',
            $_POST['hover_bg_color'] ?? '#F8F9FA',
            $_POST['active_bg_color'] ?? '#E9ECEF',
            $favicon_path,
            $settings['id']
        ]);

        $message = 'Configuración actualizada exitosamente.';
        $message_type = 'success';

        // Refresh settings
        $stmt = $pdo->query("SELECT * FROM institution_settings LIMIT 1");
        $settings = $stmt->fetch(PDO::FETCH_ASSOC);

    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_colors'])) {
    // Handle color reset
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $message = 'Token de seguridad inválido o caducado. Por favor, inténtelo de nuevo.';
        $message_type = 'danger';
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE institution_settings SET
                primary_color = DEFAULT, secondary_color = DEFAULT, accent_color = DEFAULT,
                success_color = DEFAULT, warning_color = DEFAULT, danger_color = DEFAULT,
                info_color = DEFAULT, light_bg_color = DEFAULT, dark_text_color = DEFAULT,
                sidebar_bg_color = DEFAULT, navbar_bg_color = DEFAULT, card_bg_color = DEFAULT,
                border_color = DEFAULT, shadow_color = DEFAULT, hover_bg_color = DEFAULT,
                active_bg_color = DEFAULT
                WHERE id = ?");
            $stmt->execute([$settings['id']]);

            $message = 'Los colores del tema han sido restablecidos a los valores por defecto.';
            $message_type = 'success';

            // Refresh settings
            $stmt = $pdo->query("SELECT * FROM institution_settings LIMIT 1");
            $settings = $stmt->fetch(PDO::FETCH_ASSOC);

        } catch (Exception $e) {
            $message = 'Error: ' . $e->getMessage();
            $message_type = 'danger';
        }
    }
}

ob_start();
?>

<?php if ($message): ?>
    <div class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
        <i class="fas fa-<?= $message_type == 'success' ? 'check-circle' : 'exclamation-triangle' ?> me-2"></i>
        <?= $message ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header p-2">
        <ul class="nav nav-tabs" id="settingsTabs" role="tablist">
            <li class="nav-item" role="presentation"><a class="nav-link active" id="general-tab" href="#general" data-bs-toggle="tab" data-bs-target="#general" role="tab" aria-controls="general" aria-selected="true">Información General</a></li>
            <li class="nav-item" role="presentation"><a class="nav-link" id="theme-tab" href="#theme" data-bs-toggle="tab" data-bs-target="#theme" role="tab" aria-controls="theme" aria-selected="false">Personalización y Tema</a></li>
            <li class="nav-item" role="presentation"><a class="nav-link" id="contact-tab" href="#contact" data-bs-toggle="tab" data-bs-target="#contact" role="tab" aria-controls="contact" aria-selected="false">Persona de Contacto</a></li>
        </ul>
    </div>
    <div class="card-body">
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= get_csrf_token() ?>">
            <div class="tab-content">
                <!-- General Information Tab -->
                <div class="tab-pane active" id="general">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label for="institution_name" class="form-label">Nombre de la Institución *</label>
                                <input type="text" class="form-control" id="institution_name" name="institution_name" value="<?= htmlspecialchars($settings['institution_name'] ?? '') ?>" required>
                            </div>
                            <div class="mb-3">
                                <label for="institution_description" class="form-label">Descripción</label>
                                <textarea class="form-control" id="institution_description" name="institution_description" rows="3"><?= htmlspecialchars($settings['institution_description'] ?? '') ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="institution_address" class="form-label">Dirección</label>
                                <input type="text" class="form-control" id="institution_address" name="institution_address" value="<?= htmlspecialchars($settings['institution_address'] ?? '') ?>">
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="institution_phone" class="form-label">Teléfono</label>
                                    <input type="text" class="form-control" id="institution_phone" name="institution_phone" value="<?= htmlspecialchars($settings['institution_phone'] ?? '') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="institution_email" class="form-label">Email</label>
                                    <input type="email" class="form-control" id="institution_email" name="institution_email" value="<?= htmlspecialchars($settings['institution_email'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="institution_website" class="form-label">Sitio Web</label>
                                <input type="url" class="form-control" id="institution_website" name="institution_website" value="<?= htmlspecialchars($settings['institution_website'] ?? '') ?>">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="institution_logo" class="form-label">Logo de la Institución</label>
                                <input type="file" class="form-control" id="institution_logo" name="institution_logo" accept="image/*" onchange="previewImage(this, 'logo-preview')">
                                <div class="form-text">Formatos: JPG, PNG, GIF. Máx: 2MB.</div>
                                <div class="mt-2">
                                    <label class="form-label">Vista Previa / Actual:</label>
                                    <img id="logo-preview" src="<?= $settings['institution_logo'] ? url($settings['institution_logo']) : url('assets/img/logo-placeholder.png') ?>" class="img-fluid rounded border p-1" style="max-height: 150px;" alt="Logo Preview">
                                </div>
                            </div>
                            <hr>
                            <div class="mb-3">
                                <label for="favicon" class="form-label">Favicon</label>
                                <input type="file" class="form-control" id="favicon" name="favicon" accept=".ico,.png,.jpg,.jpeg,.svg" onchange="previewImage(this, 'favicon-preview')">
                                <div class="form-text">Formatos: ICO, PNG, JPG, SVG. Recomendado: 32x32px.</div>
                                <div class="mt-2">
                                    <label class="form-label">Vista Previa / Actual:</label>
                                    <img id="favicon-preview" src="<?= $settings['favicon'] ? url($settings['favicon']) : url('assets/img/favicon-placeholder.png') ?>" class="img-fluid rounded border p-1" style="max-height: 32px; max-width: 32px;" alt="Favicon Preview">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Theme Customization Tab -->
                <div class="tab-pane" id="theme">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5>Colores del Tema</h5>
                        <button type="submit" name="reset_colors" class="btn btn-sm btn-outline-danger" onclick="return confirm('¿Estás seguro de que quieres restablecer todos los colores a sus valores por defecto?')"><i class="fas fa-undo"></i> Restablecer Colores</button>
                    </div>
                    <p class="text-muted small">Personaliza la paleta de colores del sistema para que coincida con la identidad de tu institución.</p>
                    <div class="row">
                        <?php
                        $colors = [
                            'primary_color' => ['label' => 'Color Primario', 'default' => '#27538C', 'description' => 'Botones principales, enlaces, elementos destacados'],
                            'secondary_color' => ['label' => 'Color Secundario', 'default' => '#204473', 'description' => 'Estados hover, gradientes, elementos secundarios'],
                            'accent_color' => ['label' => 'Color de Acento', 'default' => '#9BABBF', 'description' => 'Barras laterales, bordes, elementos decorativos'],
                            'success_color' => ['label' => 'Color de Éxito', 'default' => '#28A745', 'description' => 'Mensajes de éxito, indicadores positivos'],
                            'warning_color' => ['label' => 'Color de Advertencia', 'default' => '#FFC107', 'description' => 'Alertas, mensajes de precaución'],
                            'danger_color' => ['label' => 'Color de Peligro', 'default' => '#DC3545', 'description' => 'Errores, elementos críticos, eliminación'],
                            'info_color' => ['label' => 'Color de Información', 'default' => '#17A2B8', 'description' => 'Mensajes informativos, ayuda'],
                            'light_bg_color' => ['label' => 'Fondo Claro', 'default' => '#F2F2F2', 'description' => 'Fondos de tarjetas, áreas secundarias'],
                            'dark_text_color' => ['label' => 'Texto Oscuro', 'default' => '#212426', 'description' => 'Texto principal, encabezados'],
                            'sidebar_bg_color' => ['label' => 'Login', 'default' => '#27538C', 'description' => 'Color de fondo de la barra lateral'],
                            'navbar_bg_color' => ['label' => 'Fondo de Barra Superior', 'default' => '#FFFFFF', 'description' => 'Color de fondo de la barra de navegación'],
                            'card_bg_color' => ['label' => 'Fondo de Tarjetas', 'default' => '#FFFFFF', 'description' => 'Color de fondo de las tarjetas'],
                            'border_color' => ['label' => 'Color de Bordes', 'default' => '#E9ECEF', 'description' => 'Bordes de elementos, separadores'],
                            'shadow_color' => ['label' => 'Color de Sombras', 'default' => 'rgba(0,0,0,0.1)', 'description' => 'Sombras de elementos (formato RGBA)'],
                            'hover_bg_color' => ['label' => 'Fondo al Pasar Mouse', 'default' => '#F8F9FA', 'description' => 'Color de fondo en elementos hover'],
                            'active_bg_color' => ['label' => 'Fondo Activo', 'default' => '#E9ECEF', 'description' => 'Color de fondo en elementos activos'],
                        ];
                        ?>
                        <?php foreach ($colors as $key => $color): ?>
                            <div class="col-md-6 col-lg-4">
                                <div class="mb-3">
                                    <label for="<?= $key ?>" class="form-label">
                                        <?= $color['label'] ?>
                                        <?php if (isset($color['description'])): ?>
                                            <small class="text-muted d-block"><?= $color['description'] ?></small>
                                        <?php endif; ?>
                                    </label>
                                    <div class="input-group color-picker-wrapper">
                                        <input type="color" class="form-control form-control-color" id="<?= $key ?>" name="<?= $key ?>" value="<?= htmlspecialchars($settings[$key] ?? $color['default']) ?>" oninput="updateColorPreview(this)">
                                        <span class="input-group-text color-preview" style="background-color: <?= htmlspecialchars($settings[$key] ?? $color['default']) ?>;"></span>
                                        <input type="text" class="form-control" value="<?= htmlspecialchars($settings[$key] ?? $color['default']) ?>" oninput="updateColorFromText(this)" style="max-width: 100px;">
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Contact Person Tab -->
                <div class="tab-pane" id="contact">
                    <h5>Persona de Contacto de la Institución</h5>
                    <p class="text-muted">Esta información puede ser mostrada en el pie de página o en la sección de contacto del sitio público.</p>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="contact_person" class="form-label">Nombre</label>
                                <input type="text" class="form-control" id="contact_person" name="contact_person" value="<?= htmlspecialchars($settings['contact_person'] ?? '') ?>">
                            </div>
                            <div class="mb-3">
                                <label for="contact_email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="contact_email" name="contact_email" value="<?= htmlspecialchars($settings['contact_email'] ?? '') ?>">
                            </div>
                            <div class="mb-3">
                                <label for="contact_phone" class="form-label">Teléfono</label>
                                <input type="text" class="form-control" id="contact_phone" name="contact_phone" value="<?= htmlspecialchars($settings['contact_phone'] ?? '') ?>">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card-footer text-end">
                <a href="dashboard.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Volver al Dashboard
                </a>
                <button type="submit" name="save_settings" class="btn btn-primary">
                    <i class="fas fa-save"></i> Guardar Configuración
                </button>
            </div>
        </form>
    </div>
</div>

<style>
    .color-picker-wrapper .form-control-color {
        max-width: 80px;
    }
    .color-preview {
        width: 40px;
        height: 38px;
        border-top-right-radius: .25rem;
        border-bottom-right-radius: .25rem;
        border: 1px solid #ced4da;
        border-left: none;
    }
    .form-control-color {
        padding: .375rem;
    }
</style>

<script>
    function previewImage(input, previewId) {
        const file = input.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.getElementById(previewId);
                preview.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    }

    function updateColorPreview(input) {
        const preview = input.nextElementSibling;
        if (preview && preview.classList.contains('color-preview')) {
            preview.style.backgroundColor = input.value;
        }
        // Also update the text input
        const textInput = input.parentElement.nextElementSibling;
        if (textInput && textInput.tagName === 'INPUT' && textInput.type === 'text') {
            textInput.value = input.value;
        }
    }

    function updateColorFromText(input) {
        const colorInput = input.previousElementSibling.querySelector('input[type="color"]');
        if (colorInput) {
            colorInput.value = input.value;
            updateColorPreview(colorInput);
        }
    }

    // Activate the correct tab if there was a server-side error
    document.addEventListener('DOMContentLoaded', function() {
        const tabLinks = document.querySelectorAll('#settingsTabs a[data-bs-toggle="tab"]');
        const lastTab = localStorage.getItem('lastSettingsTab');

        if (lastTab) {
            const tabEl = document.querySelector('a[href="' + lastTab + '"]');
            if(tabEl) {
                new bootstrap.Tab(tabEl).show();
            }
        }

        tabLinks.forEach(el => {
            el.addEventListener('shown.bs.tab', event => {
                localStorage.setItem('lastSettingsTab', event.target.getAttribute('href'));
            });
        });
    });
</script>

<?php
$content = ob_get_clean();
include BASE_PATH . '/includes/layout.php';
?>