<?php
ini_set('display_errors', 0);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

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

<style>
    /* ===== Thème ESSO4K – même style que la page profil ===== */

    .esso-theme-ads{
        padding: 20px 12px 40px;
    }

    .ads-wrapper{
        max-width: 1100px;
        margin: 0 auto;
    }

    /* Carte principale avec bordure néon (copie du style panel-card-esso) */
    .ads-card{
        border-radius: 28px;
        padding: 28px 30px 34px;
        position: relative;
        background:
            radial-gradient(circle at top, rgba(15,23,42,0.98) 0, #020617 55%, #020617 100%);
        box-shadow: 0 26px 70px rgba(3,7,18,0.95);
        border: 1px solid rgba(148,163,184,0.45);
        color: #e5e7eb;
        overflow: hidden;
    }

    .ads-card::before{
        content:"";
        position:absolute;
        inset:-1px;
        border-radius:inherit;
        background:
            conic-gradient(from 190deg,
                rgba(56,189,248,0.00) 0deg,
                rgba(56,189,248,0.9) 70deg,
                rgba(129,140,248,0.9) 150deg,
                rgba(16,185,129,0.9) 230deg,
                rgba(56,189,248,0.00) 320deg);
        filter: blur(14px);
        opacity:0.95;
        z-index:-1;
    }

    .ads-card h2,
    .ads-card label,
    .ads-card p,
    .ads-card small,
    .ads-card strong{
        color:#e5e7eb !important;
    }

    .ads-card h2{
        font-size: 1.35rem;
        letter-spacing: .12em;
        font-weight: 800;
        text-transform: uppercase;
        margin-bottom: 6px;
        text-align:center;
    }

    .ads-card .subtitle{
        font-size:.9rem;
        opacity:.9;
        text-align:center;
        margin-bottom:18px;
    }

    /* Labels en bleu cyan comme sur la page profil */
    .ads-card label{
        font-size: .85rem;
        text-transform: uppercase;
        letter-spacing: .06em;
        color: #38bdf8 !important;
        margin-bottom: 6px;
        display:block;
        text-align:center;
        font-weight:600;
    }

    .ads-card code{
        color:#a5b4fc;
        background:rgba(15,23,42,0.85);
        border-radius:6px;
        padding:2px 6px;
    }

    .ads-card img{
        background: radial-gradient(circle at center, rgba(15,23,42,0.9), #020617);
        padding:10px;
    }

    /* Select & bouton dans le style sombre / néon */
    .ads-card select{
        width: 100%;
        max-width: 320px;
        margin: 0 auto;
        display:block;
        padding: 10px 14px;
        border-radius: 999px;
        border: 1px solid rgba(148,163,184,.6);
        background: rgba(15,23,42,.95);
        color: #e5e7eb;
        box-shadow: 0 0 0 1px rgba(15,23,42,.6);
        font-size:.9rem;
    }
    .ads-card select:focus{
        border-color:#38bdf8;
        outline:none;
        box-shadow:0 0 0 0.12rem rgba(56,189,248,.45);
    }

    .custom-button{
        background: linear-gradient(90deg,#22c55e,#a3e635);
        color:#022c22;
        text-transform: uppercase;
        font-weight:700;
        border:none;
        border-radius:999px;
        padding:10px 30px;
        margin-top:18px;
        box-shadow:0 10px 30px rgba(22,163,74,.5);
        cursor:pointer;
        transition:transform .2s ease, box-shadow .2s ease, filter .2s ease;
    }
    .custom-button:hover{
        filter:brightness(1.05);
        transform:translateY(-1px);
        box-shadow:0 14px 40px rgba(22,163,74,.6);
    }

    .ads-form{
        display:flex;
        flex-direction:column;
        align-items:center;
        padding-top:10px;
    }

    .ads-feedback{
        margin-top:12px;
        text-align:center;
        font-size:.85rem;
    }
    .ads-feedback.success{
        color:#bbf7d0;
    }
    .ads-feedback.error{
        color:#fecaca;
    }
</style>

<div class="container-fluid esso-theme-ads">
    <div class="ads-wrapper">
        <div class="card border-left-primary shadow h-100 mb-4 ads-card">
            <h2><i class="fa fa-file-image-o"></i> BANNER MODE</h2>
            <div class="subtitle">Choose how banners are loaded in the app: automatic or manual.</div>

            <div class="card-body" style="background:transparent;padding:0;">
                <?php
                $feedback = '';
                $feedbackClass = '';

                $db = new SQLite3('./api/db/.db_ads.db');
                if (!$db) {
                    echo "<div class='ads-feedback error'>Database connection error.</div>";
                } else {
                    $query = "CREATE TABLE IF NOT EXISTS adsstatus (id INTEGER PRIMARY KEY, adstype TEXT)";
                    $db->exec($query);

                    // Get current mode (if exists)
                    $currentType = null;
                    $resType = $db->query("SELECT adstype FROM adsstatus WHERE id = 1");
                    if ($resType) {
                        $rowType = $resType->fetchArray(SQLITE3_ASSOC);
                        if ($rowType && isset($rowType['adstype'])) {
                            $currentType = $rowType['adstype'];
                        }
                    }

                    // Handle submit
                    if ($_SERVER["REQUEST_METHOD"] === "POST") {
                        $ad_item = isset($_POST["ad_item"]) ? trim($_POST["ad_item"]) : '';

                        if ($ad_item === '') {
                            $feedback = "Please select a banner mode.";
                            $feedbackClass = 'error';
                        } else {
                            $count = (int)$db->querySingle("SELECT COUNT(*) FROM adsstatus");

                            if ($count === 0) {
                                $updateQuery = "INSERT INTO adsstatus (id, adstype) VALUES (1, :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()) {
                                $currentType = $ad_item;
                                $feedback = "Banner mode '" . htmlspecialchars($ad_item, ENT_QUOTES, 'UTF-8') . "' updated successfully ✅";
                                $feedbackClass = 'success';

                                // Copy correct allads.php file
                                if ($ad_item === "Manualads") {
                                    $source = "./Manualads/allads.php";
                                } else { // Autoads
                                    $source = "./Autoads/allads.php";
                                }
                                $destination = "./api/allads.php";

                                if (file_exists($source)) {
                                    @copy($source, $destination);
                                } else {
                                    $feedback .= "<br>Warning: 'allads.php' not found in selected folder.";
                                }
                            } else {
                                $feedback = "Error updating mode: " . htmlspecialchars($db->lastErrorMsg(), ENT_QUOTES, 'UTF-8');
                                $feedbackClass = 'error';
                            }
                        }
                    }
                }
                ?>

                <form method="POST" action="" class="ads-form">
                    <label for="ad_item">Choose banner mode</label>
                    <select name="ad_item" id="ad_item">
                        <option value="Autoads"  <?= ($currentType === 'Autoads'  ? 'selected' : '') ?>>Automatic (Auto Banners)</option>
                        <option value="Manualads"<?= ($currentType === 'Manualads'? 'selected' : '') ?>>Manual (From Panel)</option>
                    </select>

                    <input type="submit" name="submit" value="Save Mode" class="custom-button">
                </form>

                <?php if ($feedback): ?>
                    <div class="ads-feedback <?= $feedbackClass ?>">
                        <?= $feedback ?>
                    </div>
                <?php endif; ?>

                <?php if ($db) { $db->close(); } ?>
            </div>
        </div>
    </div>
</div>

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