<?php
include('includes/header.php');

// --- CONFIGURACIONES (tu código actual) ---
$widgetFile = './api/page.json';
$configFile = './api/config.txt';
$adsDbFile = './api/ads.db';
$backgroundDbFile = './api/.background.db';

$widgetData = json_decode(file_get_contents($widgetFile), true);
$selectedOption = $widgetData['app']['selected_option'] ?? 'tmdb.php';

if(isset($_POST['submit_widget'])) {
    $widgetData['app']['selected_option'] = $_POST['selected_option'];
    file_put_contents($widgetFile, json_encode($widgetData, JSON_PRETTY_PRINT));
    echo "<script>window.location.href='widgets.php?status=1&message=Tipo de fondo actualizado';</script>";
    exit;
}

$marqueeStatus = 'activo';
$marqueeTexto = 'Texto predeterminado de marquesina';
if(file_exists($configFile)) {
    list($marqueeStatus, $marqueeTexto) = array_map('trim', explode("\n", file_get_contents($configFile)));
}

if(isset($_POST['submit_marquee'])) {
    $newStatus = $_POST['status'] === 'activo' ? 'activo' : 'inactivo';
    $newText = $_POST['texto'];
    file_put_contents($configFile, $newStatus."\n".$newText);
    echo "<script>window.location.href='widgets.php?status=1&message=Marquesina actualizada';</script>";
    exit;
}

$ads = [];
try {
    $db = new SQLite3($adsDbFile);
    $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);
            $stmt->bindValue(':url',$url);
            $stmt->bindValue(':created_on', date('Y-m-d H:i:s'));
            $stmt->execute();
            echo "<script>window.location.href='widgets.php?status=1&message=Anuncio agregado';</script>";
            exit;
        } else {
            echo "<script>window.location.href='widgets.php?status=0&message=URL inválida';</script>";
            exit;
        }
    }

    $result = $db->query('SELECT * FROM ads ORDER BY created_on DESC');
    while($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $ads[] = $row;
    }

} catch(Exception $e) {
    echo "<script>window.location.href='widgets.php?status=0&message=Error en DB de anuncios';</script>";
    exit;
}

$currentImageUrl = '';
try {
    $dbBackground = new SQLite3($backgroundDbFile);
    $dbBackground->exec("CREATE TABLE IF NOT EXISTS background_image (id INTEGER PRIMARY KEY, url TEXT)");
    $res = $dbBackground->query("SELECT url FROM background_image ORDER BY id DESC LIMIT 1");
    $row = $res->fetchArray(SQLITE3_ASSOC);
    $currentImageUrl = $row['url'] ?? '';

    if(isset($_POST['submit_background'])) {
        $newUrl = filter_var($_POST['image_url'], FILTER_SANITIZE_URL);
        if(filter_var($newUrl, FILTER_VALIDATE_URL)) {
            $dbBackground->exec("DELETE FROM background_image");
            $stmt = $dbBackground->prepare("INSERT INTO background_image (url) VALUES (:url)");
            $stmt->bindValue(':url', $newUrl);
            $stmt->execute();
            echo "<script>window.location.href='widgets.php?status=1&message=Fondo actualizado';</script>";
            exit;
        } else {
            echo "<script>window.location.href='widgets.php?status=0&message=URL inválida';</script>";
            exit;
        }
    }
} catch(Exception $e) {
    echo "<script>window.location.href='widgets.php?status=0&message=Error en DB de fondo';</script>";
    exit;
}

$basePath = dirname($_SERVER['SCRIPT_NAME']);
$apiPath = $basePath . '/api';
$widgets = [
    'tmdb.php' => 'Anuncios TMDB',
    'ads.php' => 'Anuncios Manuales',
    'image.php' => 'Fondo con Marquesina'
];
?>

<!-- SELECCIÓN DE WIDGET -->
<div class="container-fluid pt-4 px-4">
    <div class="row mb-4">
        <div class="col-12">
            <div class="card bg-secondary text-light p-3">
                <form method="post" class="d-flex align-items-center">
                    <label class="me-2 mb-0 fw-bold">Selecciona una opción:</label>
                    <select class="form-select me-2 bg-dark text-light border-0" name="selected_option" style="max-width:300px;">
                        <?php foreach($widgets as $file => $label): ?>
                            <option value="<?= $file ?>" <?= $selectedOption === $file ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" name="submit_widget" class="btn btn-primary">
                        <i class="fas fa-check"></i> Aplicar Cambios
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- CARDS DE WIDGETS -->
<div class="container-fluid pt-2 px-4">
    <div class="row g-4">
        <?php foreach($widgets as $file => $label): 
            $isActive = $selectedOption === $file;
        ?>
        <div class="col-12 col-md-6 col-lg-4">
            <div class="bg-secondary rounded h-100 p-4 d-flex flex-column">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0"><?= htmlspecialchars($label) ?> <?= $isActive?'<span class="badge bg-success ms-2">✔️Activo</span>':'' ?></h5>
                    <div>
                        <?php if($file === 'image.php'): ?>
                            <button class="btn btn-sm btn-warning text-dark me-1" data-bs-toggle="modal" data-bs-target="#marqueeModal">
                                <i class="fas fa-edit"></i> Texto
                            </button>
                            <button class="btn btn-sm btn-info text-dark" data-bs-toggle="modal" data-bs-target="#backgroundModal">
                                <i class="fas fa-image"></i> Fondo
                            </button>
                        <?php elseif($file === 'ads.php'): ?>
                            <a href="ads.php" class="btn btn-sm btn-primary me-1">
                                <i class="fas fa-edit"></i> Editar
                            </a>
                            <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#adsModal">
                                <i class="fas fa-plus"></i> Agregar
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
                <iframe src="<?= htmlspecialchars($apiPath.'/'.$file) ?>" style="width:100%; height:200px; border:0; background:#121212;"></iframe>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- MODALES (usa los mismos que te pasé antes) -->
<!-- MODALES COMPLETOS -->

<!-- Modal Marquesina -->
<div class="modal fade" id="marqueeModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content bg-dark text-light">
      <div class="modal-header bg-warning text-dark">
        <h5 class="modal-title">Editar Texto de Marquesina</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <div class="mb-2">
            <label class="form-label">Estado</label>
            <select name="status" class="form-select bg-secondary text-light border-0">
              <option value="activo" <?= $marqueeStatus === 'activo' ? 'selected' : '' ?>>Activo</option>
              <option value="inactivo" <?= $marqueeStatus === 'inactivo' ? 'selected' : '' ?>>Inactivo</option>
            </select>
          </div>
          <div class="mb-2">
            <label class="form-label">Texto</label>
            <textarea name="texto" class="form-control bg-secondary text-light border-0" rows="3"><?= htmlspecialchars($marqueeTexto) ?></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" name="submit_marquee" class="btn btn-warning text-dark">Guardar Cambios</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal Fondo -->
<div class="modal fade" id="backgroundModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content bg-dark text-light">
      <div class="modal-header bg-info text-dark">
        <h5 class="modal-title">Cambiar Fondo</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <label class="form-label">URL de la Imagen</label>
          <input type="url" name="image_url" class="form-control bg-secondary text-light border-0" 
                 placeholder="Ingresa el link de tu imagen de fondo" 
                 value="<?= htmlspecialchars($currentImageUrl) ?>" required>
          <?php if($currentImageUrl): ?>
            <div class="mt-2">
              <small class="text-muted">Vista previa actual:</small>
              <img src="<?= htmlspecialchars($currentImageUrl) ?>" 
                   class="img-thumbnail mt-2" 
                   style="max-width:100%; max-height:200px; filter:brightness(0.8);" 
                   onerror="this.style.display='none'">
            </div>
          <?php endif; ?>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" name="submit_background" class="btn btn-info text-dark">Guardar Cambios</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal Ads -->
<div class="modal fade" id="adsModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content bg-dark text-light">
      <div class="modal-header bg-success text-dark">
        <h5 class="modal-title">Agregar Anuncio</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <div class="mb-2">
            <label class="form-label">Título</label>
            <input type="text" name="title" class="form-control bg-secondary text-light border-0" required>
          </div>
          <div class="mb-2">
            <label class="form-label">URL de la Imagen</label>
            <input type="url" name="url" class="form-control bg-secondary text-light border-0" 
                   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-bs-dismiss="modal">Cancelar</button>
          <button type="submit" name="submit_ad" class="btn btn-success">Agregar Anuncio</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
<?php include('includes/footer.php'); ?>