<?php
declare(strict_types=1);

// Configuración inicial
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();

// Manejo de sesión seguro
if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_lifetime' => 86400,
        'cookie_secure' => true,
        'cookie_httponly' => true,
        'use_strict_mode' => true
    ]);
}

// Verificación de sesión mejorada
require_once __DIR__.'/functions.php';
$log_check = $db->select('user', '*', 'id = :id', '', [':id' => 1]);
$loggedinuser = $log_check[0]['username'] ?? null;

if (!isset($_SESSION['name']) || $_SESSION['name'] !== $loggedinuser) {
    ob_end_clean();
    header("Location: index.php");
    exit();
}

// 1. CONFIGURACIÓN DE WIDGETS
$jsondata = file_get_contents(__DIR__."/api/page.json");
$arrayData = json_decode($jsondata, true);
$json = $arrayData['app'] ?? ['selected_option' => 'image.php'];

if (isset($_POST['submit_widget'])) {
    $replacementData = ['app' => ['selected_option' => $_POST["selected_option"]]];
    file_put_contents(__DIR__."/api/page.json", json_encode($replacementData, JSON_PRETTY_PRINT));
    $_SESSION['backgroundMessage'] = '<div class="alert alert-success">Tipo de fondo actualizado!</div>';
    ob_end_clean();
    header("Location: ".strtok($_SERVER['REQUEST_URI'], '?'));
    exit();
}

// 2. CONFIGURACIÓN DE MARQUESINA
$configFile = __DIR__.'/api/config.txt';
$marquesinaStatus = 'activo';
$marquesinaTexto = 'Texto predeterminado de marquesina';

if (file_exists($configFile)) {
    $configContent = file_get_contents($configFile);
    $configLines = explode("\n", $configContent);
    $marquesinaStatus = trim($configLines[0] ?? 'activo');
    $marquesinaTexto = trim($configLines[1] ?? 'Texto predeterminado de marquesina');
}

if (isset($_POST['submit_marquee'])) {
    $newStatus = $_POST['status'] === 'activo' ? 'activo' : 'inactivo';
    $newText = htmlspecialchars($_POST['texto'] ?? '', ENT_QUOTES, 'UTF-8');

    if (file_put_contents($configFile, $newStatus."\n".$newText)) {
        $_SESSION['marqueeMessage'] = '<div class="alert alert-success">Marquesina actualizada!</div>';
    } else {
        $_SESSION['marqueeMessage'] = '<div class="alert alert-danger">Error al actualizar la marquesina.</div>';
    }
    ob_end_clean();
    header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
    exit();
}

// 3. CONFIGURACIÓN DE ANUNCIOS MANUALES
$db_path = __DIR__.'/api/ads.db';

try {
    $db = new SQLite3($db_path);
    $db->exec('CREATE TABLE IF NOT EXISTS ads (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT,
        url TEXT,
        created_on TEXT
    )');

    if (isset($_POST['submit_ad'])) {
        $title = htmlspecialchars($_POST['title'] ?? '', ENT_QUOTES, 'UTF-8');
        $url = filter_var($_POST['url'] ?? '', FILTER_VALIDATE_URL);

        if ($url) {
            $stmt = $db->prepare('INSERT INTO ads (title, url, created_on) VALUES (:title, :url, :created_on)');
            $stmt->bindValue(':title', $title, SQLITE3_TEXT);
            $stmt->bindValue(':url', $url, SQLITE3_TEXT);
            $stmt->bindValue(':created_on', date('Y-m-d H:i:s'), SQLITE3_TEXT);

            if ($stmt->execute()) {
                $_SESSION['adMessage'] = '<div class="alert alert-success">Anuncio agregado!</div>';
            } else {
                $_SESSION['adMessage'] = '<div class="alert alert-danger">Error al guardar el anuncio.</div>';
            }
        } else {
            $_SESSION['adMessage'] = '<div class="alert alert-danger">URL inválida. Introduce una URL válida.</div>';
        }
        ob_end_clean();
        header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
        exit();
    }

    $ads = [];
    $result = $db->query('SELECT url FROM ads ORDER BY created_on DESC LIMIT 5');
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $ads[] = $row['url'];
    }
} catch (Exception $e) {
    $_SESSION['adMessage'] = '<div class="alert alert-danger">Error con la base de datos de anuncios: '.htmlspecialchars($e->getMessage()).'</div>';
}

// 4. CONFIGURACIÓN DE FONDO
$dbPath = __DIR__.'/api/.background.db';
$currentImageUrl = '';

try {
    $dbBackground = new SQLite3($dbPath);
    $dbBackground->exec("CREATE TABLE IF NOT EXISTS background_image (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT)");

    $result = $dbBackground->query("SELECT url FROM background_image ORDER BY id DESC LIMIT 1");
    if ($result) {
        $row = $result->fetchArray(SQLITE3_ASSOC);
        $currentImageUrl = $row ? $row['url'] : '';
    }

    if (isset($_POST['submit_background'])) {
        $newImageUrl = filter_var($_POST['image_url'] ?? '', FILTER_SANITIZE_URL);

        if (filter_var($newImageUrl, FILTER_VALIDATE_URL)) {
            $dbBackground->exec("DELETE FROM background_image");
            $stmt = $dbBackground->prepare("INSERT INTO background_image (url) VALUES (:url)");
            $stmt->bindValue(':url', $newImageUrl, SQLITE3_TEXT);

            if ($stmt->execute()) {
                $_SESSION['backgroundMessage'] = '<div class="alert alert-success">Imagen de fondo actualizada!</div>';
            } else {
                $_SESSION['backgroundMessage'] = '<div class="alert alert-danger">Error al guardar la nueva imagen.</div>';
            }
        } else {
            $_SESSION['backgroundMessage'] = '<div class="alert alert-danger">URL inválida. Introduce una URL válida.</div>';
        }
        ob_end_clean();
        header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
        exit();
    }
} catch (Exception $e) {
    $_SESSION['backgroundMessage'] = '<div class="alert alert-danger">Error con la base de datos de fondo: '.htmlspecialchars($e->getMessage()).'</div>';
}

// Incluir header después de toda la lógica de procesamiento
include(__DIR__.'/includes/header.php');

// Mensajes de sesión
$backgroundMessage = $_SESSION['backgroundMessage'] ?? '';
$adMessage = $_SESSION['adMessage'] ?? '';
$marqueeMessage = $_SESSION['marqueeMessage'] ?? '';
unset($_SESSION['backgroundMessage'], $_SESSION['adMessage'], $_SESSION['marqueeMessage']);
?>

<!-- MODAL PARA MARQUESINA -->
<div class="modal fade" id="marqueeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title"><i class="fas fa-edit"></i> Editar Texto de Marquesina</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body"> 
                    <div class="form-group">
                        <label>Estado</label>
                        <select class="form-control" name="status">
                            <option value="activo" <?= $marquesinaStatus === 'activo' ? 'selected' : '' ?>>Activo</option>
                            <option value="inactivo" <?= $marquesinaStatus === 'inactivo' ? 'selected' : '' ?>>Inactivo</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Texto</label>
                        <textarea class="form-control" name="texto" rows="3"><?= htmlspecialchars($marquesinaTexto) ?></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" name="submit_marquee" class="btn btn-primary">Guardar Cambios</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- MODAL PARA ANUNCIOS -->
<div class="modal fade" id="adsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="fas fa-plus"></i> Agregar Anuncio</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Título</label>
                        <input type="text" class="form-control" name="title" required>
                    </div>
                    <div class="form-group">
                        <label>URL de la Imagen</label>
                        <input type="url" class="form-control" name="url" placeholder="Ingresa el link de la imagen aquí" required>
                        <small class="text-muted">Formatos: JPG, PNG, GIF, WEBP</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" name="submit_ad" class="btn btn-success">Agregar Anuncio</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- MODAL PARA CAMBIAR FONDO -->
<div class="modal fade" id="backgroundModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="fas fa-image"></i> Cambiar Fondo</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body"> 
                    <div class="form-group">
                        <label>URL de la Imagen</label>
                        <input type="url" class="form-control" name="image_url" 
                               placeholder="Ingresa el link de tu imagen de fondo" 
                               value="<?= htmlspecialchars($currentImageUrl) ?>" required>
                        <?php if ($currentImageUrl): ?>
                            <div class="mt-2">
                                <small>Vista previa actual:</small>
                                <img src="<?= htmlspecialchars($currentImageUrl) ?>" 
                                     class="img-thumbnail mt-2" 
                                     style="max-width: 100%; max-height: 200px;"
                                     onerror="this.style.display='none'">
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" name="submit_background" class="btn btn-primary">
                        <i class="fas fa-save"></i> Guardar Cambios
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- CONTENIDO PRINCIPAL -->
<div class="container-fluid">
    <div class="mx-auto" style="max-width: 600px;">
        <h1 class="title-outside-card mb-1">Tipos de Fondo</h1>
        <div class="card border-left-primary shadow h-100 card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-sync-alt"></i> Reinicie la app para aplicar cambios
                </h6>
            </div>
            <div class="card-body">
                <?= $backgroundMessage ?>
                <?= $adMessage ?>
                <?= $marqueeMessage ?>
                <form method="post">
                    <div class="form-group">
                        <label>Selecciona una opción</label>
                        <select class="form-control" name="selected_option">
                            <option value="tmdb.php" <?= $json['selected_option'] == 'tmdb.php' ? 'selected' : '' ?>>Anuncios TMDB</option>
                            <option value="ads.php" <?= $json['selected_option'] == 'ads.php' ? 'selected' : '' ?>>Anuncios Manuales</option>
                            <option value="image.php" <?= $json['selected_option'] == 'image.php' ? 'selected' : '' ?>>Fondo con Marquesina</option>
                        </select>
                    </div>
                    <div class="text-center mt-3">
                        <button type="submit" name="submit_widget" class="btn btn-primary">
                            <i class="fas fa-check"></i> Aplicar Cambios
                        </button>
                    </div>
                </form>

                <!-- PREVISUALIZACIONES -->
                <div class="mt-4">
                    <?php
                    $basePath = dirname($_SERVER['SCRIPT_NAME']);
                    $apiPath = $basePath . '/api';
                    $widgets = [
                        'tmdb.php' => 'Anuncios TMDB',
                        'ads.php' => 'Anuncios Manuales', 
                        'image.php' => 'Fondo con Marquesina'
                    ];

                    foreach ($widgets as $file => $label) {
                        $isSelected = $json['selected_option'] === $file;
                        echo '
                        <div class="border rounded p-3 mb-3 bg-light">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h5 class="mb-0">'.htmlspecialchars($label).'
                                '.($isSelected ? '<span class="badge badge-success ml-2">✔️Activo</span>' : '').'</h5>
                                <div>';
                        
                        if ($file === 'image.php') {
                            echo '
                                    <button class="btn btn-sm btn-primary mr-1" data-toggle="modal" data-target="#marqueeModal">
                                        <i class="fas fa-edit"></i> Cambiar Texto
                                    </button>
                                    <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#backgroundModal">
                                        <i class="fas fa-image"></i> Cambiar Fondo
                                    </button>';
                        } elseif ($file === 'ads.php') {
                            echo '
                                <a href="ads.php" class="btn btn-sm btn-primary">
                                    <i class="fas fa-edit"></i> Editar
                                </a>
                                <button class="btn btn-sm btn-success" data-toggle="modal" data-target="#adsModal">
                                    <i class="fas fa-plus"></i> Agregar
                                </button>';
                        }
                        
                        echo '
                                </div>
                            </div>
                            <iframe src="'.htmlspecialchars($apiPath.'/'.$file).'" style="width:100%; height:200px; border:0;"></iframe>
                        </div>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            setTimeout(function() {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            }, 3000);
        });
    });
</script>

<?php 
include(__DIR__.'/includes/footer.php');
require __DIR__.'/includes/boxbr.php';
ob_end_flush();
?>