<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "includes/header.php";

$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, language 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, language) VALUES('', 'es-MX')");
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    echo "Form submitted"; // Add this line to confirm form submission

    if (isset($_POST["submit"])) {
        $newKey = $_POST["key"]; // No validation/sanitization here for demonstration purposes
        $language = $_POST["language"];

        // Use prepared statements to prevent SQL injection
        $stmt = $db->prepare("UPDATE " . $table_name . " SET key = :newKey, language = :language WHERE id = 1");
        $stmt->bindValue(':newKey', $newKey, SQLITE3_TEXT);
        $stmt->bindValue(':language', $language, SQLITE3_TEXT);
        $stmt->execute();

        header("Location: tmdb_api.php");
        exit();
    
    } elseif (isset($_POST["deleteCache"])) {
        // Specify the path to your JSON cache file
        $cacheFilePath = "./api/cache/combined_cache.json";

        // Check if the cache file exists and delete it
        if (file_exists($cacheFilePath)) {
            unlink($cacheFilePath); // Delete the cache file
        }

        // Redirect and exit
        header("Location: tmdb_api.php");
        exit();
    }
}

$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>';
} 

?>
<div class="card border-left-primary shadow h-100 card shadow mb-4">
    <div class="card-header py-3">
        <div class="card-body">
            <div class="card mb-4">
                <div class="card-header bg-primary py-3">
                    <h4 align="center" class="m-0 font-weight-bold text-blue">
                        <i class="fa fa-key" style="font-size:20px"></i>   
                        Get Your tMDB API Key 
                    </h4>
                </div>
                <div class="card-body">
                    <!-- Add instructions here -->
                    <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; text-decoration: underline;">https://www.themoviedb.org/</a></li>
                        <li>Sign in or create an account if you don't have one.</li>
                        <li>To register for an API key, click the <a href="https://www.themoviedb.org/settings/api" target="_blank" style="font-weight: bold; color: #007bff; text-decoration: underline;">API link</a> from within your account settings page.</li>
                        <li>
                            Please note that the API registration process is not optimized for mobile devices so you should access these pages on a desktop computer and browser
                        </li>
                        <li>Generate a new API key and copy it.</li>
                    </ol>
                    <p>
                        Paste the copied API key into the field below and select your preferred language from the dropdown menu, then click the "Save Settings" button.
                    </p>
                    <!-- End of instructions -->

                    <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="<?= $rowU['key']; ?>" type="text" />
                            </div>
                        </div>
                        <div class="form-group mb-3">
                            <label class="control-label text-primary" for="language">
                                <strong>Select Language:</strong>
                            </label>
                            <select class="form-control" id="language" name="language">
    <option value="en-US" <?= ($rowU['language'] == 'en-US') ? 'selected' : '' ?>>English</option>
    <option value="ar-AE" <?= ($rowU['language'] == 'ar-AE') ? 'selected' : '' ?>>Arabic (United Arab Emirates)</option>
    <option value="ar-SA" <?= ($rowU['language'] == 'ar-SA') ? 'selected' : '' ?>>Arabic (Saudi Arabia)</option>
    <option value="de-DE" <?= ($rowU['language'] == 'de-DE') ? 'selected' : '' ?>>German (Germany)</option>
    <option value="de-CH" <?= ($rowU['language'] == 'de-CH') ? 'selected' : '' ?>>German (Switzerland)</option>
    <option value="de-AT" <?= ($rowU['language'] == 'de-AT') ? 'selected' : '' ?>>German (Austria)</option>
    <option value="fr-FR" <?= ($rowU['language'] == 'fr-FR') ? 'selected' : '' ?>>French (France)</option>
    <option value="fr-CA" <?= ($rowU['language'] == 'fr-CA') ? 'selected' : '' ?>>French (Canada)</option>
    <option value="ms-MY" <?= ($rowU['language'] == 'ms-MY') ? 'selected' : '' ?>>Malay (Malaysia)</option>
    <option value="ms-SG" <?= ($rowU['language'] == 'ms-SG') ? 'selected' : '' ?>>Malay (Singapore)</option>
    <option value="zh-CN" <?= ($rowU['language'] == 'zh-CN') ? 'selected' : '' ?>>Chinese (China)</option>
    <option value="zh-HK" <?= ($rowU['language'] == 'zh-HK') ? 'selected' : '' ?>>Chinese (Hong Kong)</option>
    <option value="zh-TW" <?= ($rowU['language'] == 'zh-TW') ? 'selected' : '' ?>>Chinese (Taiwan)</option>
    <option value="pt-PT" <?= ($rowU['language'] == 'pt-PT') ? 'selected' : '' ?>>Portuguese (Portugal)</option>
    <option value="pt-BR" <?= ($rowU['language'] == 'pt-BR') ? 'selected' : '' ?>>Portuguese (Brazil)</option>
    <option value="es-ES" <?= ($rowU['language'] == 'es-ES') ? 'selected' : '' ?>>Spanish (Spain)</option>
    <option value="es-MX" <?= ($rowU['language'] == 'es-MX') ? 'selected' : '' ?>>Spanish (Mexico)</option>
</select>

                        </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="fas fa-save"></i>&nbsp;&nbsp;</span>
                                    <span class="text">Save Settings</span>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                <!-- Add the "Delete Cache" button -->
                <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="fas fa-trash"></i>&nbsp;&nbsp;</span>
                            <span class="text">Delete Cache</span>
                        </button>
                    </div>
                </form>
            </div>
            <!-- ============================================================== -->
            <!-- End Container fluid  -->
            <!-- ============================================================== -->
        </div>
        <!-- ============================================================== -->
        <!-- End Page wrapper  -->
        <!-- ============================================================== -->
    </div>
</div>
</div>
<?php include "includes/functions.php"; ?>

