<?php
ini_set('display_errors', 0);
include ('includes/header.php');

?>
<style>
  .custom-button {
    padding: 10px 20px;
  }
    #url-form {
        display: none;
    }
    .custom-input {
        color: blue;
    }

    /* Estilos para preview de ads */
    .ads-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 25px;
        margin: 20px 0;
    }

    .ads-option {
        border: 3px solid #444;
        border-radius: 12px;
        padding: 20px;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #2a2a2a;
        text-align: center;
    }

    .ads-option:hover {
        border-color: #007bff;
        transform: translateY(-5px);
        box-shadow: 0 8px 20px rgba(0,123,255,0.3);
    }

    .ads-option.selected {
        border-color: #28a745;
        background: #1a3a1a;
        box-shadow: 0 0 20px rgba(40,167,69,0.4);
    }

    .ads-option input[type="radio"] {
        display: none;
    }

    .ads-preview-img {
        width: 100%;
        height: 320px;
        object-fit: contain;
        border-radius: 8px;
        margin-bottom: 15px;
        background: #000;
        border: 2px solid #555;
    }

    .ads-label {
        font-weight: bold;
        font-size: 18px;
        color: #fff;
        display: block;
        margin-top: 10px;
    }

    .ads-description {
        font-size: 13px;
        color: #aaa;
        margin-top: 8px;
        line-height: 1.4;
    }

    .selected-indicator {
        display: none;
        color: #28a745;
        font-weight: bold;
        margin-top: 10px;
        font-size: 16px;
    }

    .ads-option.selected .selected-indicator {
        display: block;
    }

    .ctinput label {
        color: #fff;
    }

</style>

<div class="col-xl-6 col-lg-8 mx-auto ctmain-form">
    <div class="modal fade" id="how2" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <a href="https://www.tvsportguide.com/page/widget/"><button type="button" class="btn btn-primary">Go to webpage</button></a>
                </div>
            </div>
        </div>
    </div>

    <div class="card-body">
        <div class="card ctcard">
            <div class="card-header">
                enter>
                    <h2><i class="fa fa-file-image-o"></i> Advert's Settings</h2>
                </center>
            </div>
            <div class="card-body">

                <?php
                $db = new SQLite3('./api/.db_ads.db');

                if (!$db) {
                    die("Database connection error.");
                }

                // Crear tabla si no existe
                $query = "CREATE TABLE IF NOT EXISTS adsstatus (id INTEGER PRIMARY KEY, adstype TEXT)";
                if (!$db->exec($query)) {
                    echo "Error creating table: " . $db->lastErrorMsg() . "<br>";
                }

                // Comprobar si ya hay registros
                $query = "SELECT COUNT(*) FROM adsstatus";
                $result = $db->querySingle($query);

                // Obtener el valor actual seleccionado
                $currentAd = '';
                if ($result > 0) {
                    $currentQuery = "SELECT adstype FROM adsstatus WHERE id = 1";
                    $currentAd = $db->querySingle($currentQuery);
                }

                // Procesar formulario
                if ($_SERVER["REQUEST_METHOD"] == "POST") {
                    $ad_item = $_POST["ad_item"];

                    if (empty($ad_item)) {
                        die("Please select an ad item.");
                    }

                    if ($result === 0) {
                        $updateQuery = "INSERT INTO adsstatus (adstype) VALUES (:ad_item)";
                    } else {
                        $updateQuery = "UPDATE adsstatus SET adstype = :ad_item WHERE id = 1";
                    }

                    $stmt = $db->prepare($updateQuery);
                    $stmt->bindValue(':ad_item', $ad_item, SQLITE3_TEXT);

                    if ($stmt->execute()) {
                        echo "<div class='alert alert-success'>Ad item '$ad_item' has been successfully updated.</div>";
                        $currentAd = $ad_item; // Actualizar el valor actual
                    } else {
                        echo "<div class='alert alert-danger'>Error updating record: " . $db->lastErrorMsg() . "</div>";
                    }
                }

                // Definir las opciones de ads con sus imágenes
                $adsOptions = [
                    'ads1' => [
                        'name' => 'Ads v1',
                        'image' => 'assets/ads-previews/ads1.jpg',
                        'description' => 'Banner superior con animación'
                    ],
                    'ads2' => [
                        'name' => 'Ads v2',
                        'image' => 'assets/ads-previews/ads2.jpg',
                        'description' => 'Banner lateral derecho'
                    ],
                    'ads3' => [
                        'name' => 'Ads v3',
                        'image' => 'assets/ads-previews/ads3.jpg',
                        'description' => 'Banner inferior flotante'
                    ],
                    'ads4' => [
                        'name' => 'Ads v4 TXT',
                        'image' => 'assets/ads-previews/ads4.jpg',
                        'description' => 'Popup center screen'
                    ],
                    'ads5' => [
                        'name' => 'Ads v5 Manual',
                        'image' => 'assets/ads-previews/ads5.jpg',
                        'description' => 'Banner en grid layout'
                    ]
                ];
                ?>

                <form method="POST" action="" id="adsForm">
                    <div class="ctinput">
                        <label style="font-size: 18px; margin-bottom: 15px; display: block;">
                            <i class="fa fa-image"></i> Select an Ad Design:
                        </label>
                        
                        <div class="ads-grid">
                            <?php foreach ($adsOptions as $value => $data): ?>
                                <label class="ads-option <?php echo ($currentAd === $value) ? 'selected' : ''; ?>" for="<?php echo $value; ?>">
                                    <input type="radio" 
                                           name="ad_item" 
                                           id="<?php echo $value; ?>" 
                                           value="<?php echo $value; ?>"
                                           <?php echo ($currentAd === $value) ? 'checked' : ''; ?>
                                           required>
                                    
                                    <img src="<?php echo $data['image']; ?>" 
                                         alt="<?php echo $data['name']; ?>" 
                                         class="ads-preview-img"
                                         onerror="this.src='assets/ads-previews/default.jpg';">
                                    
                                    <span class="ads-label"><?php echo $data['name']; ?></span>
                                    <span class="ads-description"><?php echo $data['description']; ?></span>
                                    <span class="selected-indicator">✓ Selected</span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <input type="submit" name="submit" value="UPDATE AD DESIGN" class="ctbtn ctuserbtn">
                </form>

                <?php
                $db->close();
                ?>

            </div>
        </div>
    </div>
</div>

<script>
// Script para actualizar la selección visual
document.querySelectorAll('.ads-option').forEach(option => {
    option.addEventListener('click', function() {
        // Remover selección de todos
        document.querySelectorAll('.ads-option').forEach(opt => {
            opt.classList.remove('selected');
        });
        // Agregar selección al clickeado
        this.classList.add('selected');
    });
});
</script>

<?php include ('includes/footer.php');?>

</body>
</html>
