<?php
error_reporting(0);
include "includes/header.php";

// Leer tipo de anuncio actual desde JSON
$jsonFilePath = 'includes/ad_type.json';
$jsonData = json_decode(file_get_contents($jsonFilePath), true);
$currentAdType = $jsonData['adType'] ?? 'manual';

// Conexión SQLite
$db = new SQLite3("./api/.bet_tmdb.db");
$table_name = "api_key";
$db->exec("CREATE TABLE IF NOT EXISTS " . $table_name . " (id INTEGER PRIMARY KEY, key TEXT)");

$rows = $db->query("SELECT COUNT(*) as count FROM " . $table_name);
$row = $rows->fetchArray();
$numRows = $row["count"];

if ($numRows == 0) {
    $db->exec("INSERT INTO " . $table_name . "(key) VALUES('')");
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (isset($_POST["submit"])) {
        $newKey = $_POST["key"];

        $stmt = $db->prepare("UPDATE " . $table_name . " SET key = :newKey WHERE id = 1");
        $stmt->bindValue(':newKey', $newKey, SQLITE3_TEXT);
        if ($stmt->execute()) {
            $successMessage = 'API key updated successfully.';
        } else {
            $errorMessage = 'Error updating the API key.';
        }

        // Refrescar datos JSON
        $jsonData = json_decode(file_get_contents($jsonFilePath), true);
        $currentAdType = $jsonData['adType'] ?? 'manual';
    } elseif (isset($_POST["deleteCache"])) {
        $cacheFilePath = "./api/cache/combined_cache.json";
        if (file_exists($cacheFilePath)) {
            if (unlink($cacheFilePath)) {
                $successMessage = 'Cache deleted successfully.';
            } else {
                $errorMessage = 'Failed to delete cache file.';
            }
        } else {
            $errorMessage = 'Cache file does not exist.';
        }
    }
}


$res = $db->query("SELECT * FROM " . $table_name . " WHERE id = 1");
$rowU = $res->fetchArray();

if (empty($rowU['key'])) {
    echo '<div class="alert alert-warning" role="alert">
        You must add your tMDB API key before using the app. Follow the instructions below to add your API key.
    </div>';
}
?>

<link rel="stylesheet" href="css/slider.css">
<div class="col-md-12 mx-auto">
    <div class="card-body">
    <?php if (!empty($successMessage)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?= $successMessage ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
<?php endif; ?>

<?php if (!empty($errorMessage)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?= $errorMessage ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
<?php endif; ?>

        <div class="card bg-dark text-white">
            <div class="card-header bg-dark py-3">
               <!-- <div id="slider-container" data-ad-type="<?php echo $currentAdType; ?>" style="display: flex; align-items: center; justify-content: center;">
                    <span style="margin-right: 20px; font-size: 24px;">Manual Ads</span>
                    <label class="switch">
                        <input type="checkbox" id="pageSlider">
                        <span class="slider round"></span>
                    </label>
                    <span style="margin-left: 20px; font-size: 24px;">tMDB Ads</span>
                </div>
                <center>
                    <h5>Advert Type Selector</h5>
                </center>-->
            </div>
            <div class="card-body">
                <p style="font-size: 16px;">
                    To use this application, you need to have a tMDB API key. Follow these steps to obtain your API key:
                </p>
                <ol>
                    <li>Visit the tMDB website at <a href="https://www.themoviedb.org" target="_blank" style="font-weight: bold; color: #007bff;">https://www.themoviedb.org/</a></li>
                    <li>Sign in or create an account if you don't have one.</li>
                    <li>Click the <a href="https://www.themoviedb.org/settings/api" target="_blank" style="font-weight: bold; color: #007bff;">API link</a> to register for an API key.</li>
                    <li>Note: Use a desktop browser for the registration process.</li>
                    <li>Generate a new API key and copy it.</li>
                </ol>
                <p>Paste the copied API key into the field below and click "Save Settings".</p>

                <!-- Formulario para guardar API Key -->
                <form method="post">
                    <div class="form-group mb-3">
                        <label class="control-label text-primary" for="key"><strong>Api key:</strong></label>
                        <div class="input-group">
                            <input class="form-control" id="key" name="key" value="<?= htmlspecialchars($rowU['key']) ?>" type="text" />
                        </div>
                    </div>
                    <div align="center" class="form-group mb-3">
                        <br>
                        <div>
                            <button class="btn btn-success" name="submit" type="submit">
                                <span class="icon text-white-50"><i class="fa fa-save"></i>&nbsp;&nbsp;</span>
                                <span class="text">Save Settings</span>
                            </button>
                        </div>
                    </div>
                </form>

                <!-- Formulario para borrar caché -->
                <form method="post">
                    <div align="center" class="form-group mb-3">
                        <button class="btn btn-danger" name="deleteCache" type="submit">
                            <span class="icon text-white-50"><i class="fa fa-trash"></i>&nbsp;&nbsp;</span>
                            <span class="text">Delete Cache</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Script para cambiar tipo de anuncios -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    var sliderContainer = document.getElementById('slider-container');
    var currentAdType = sliderContainer.getAttribute('data-ad-type');
    var slider = document.getElementById('pageSlider');
    slider.checked = (currentAdType === 'tmdb');
    slider.addEventListener('change', function () {
        var adType = this.checked ? 'tmdb' : 'manual';
        updateAdType(adType, this.checked);
    });
});

function updateAdType(adType, isChecked) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'ad_type.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onload = function () {
        window.location.href = isChecked ? 'tmdb_api.php' : 'ads.php';
    };
    xhr.send('adType=' + adType);
}
</script>
<?php include "includes/functions.php"; ?>
