<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "Banner Type Page";

function getLastSelection()
{
    $file = "./api/ultima_opcao.txt";
    return file_exists($file) ? file_get_contents($file) : "";
}

function saveLastSelection($selection)
{
    $phpFileMap = [
        'banner_1' => 'autoads.php',
        'banner_2' => 'main_movies.php',
        'banner_3' => 'autocima.php',
        'banner_4' => 'autop.php',
        'banner_5' => 'autosinopsebaixo.php',
        'banner_6' => 'autosinopsecima.php',
        'banner_7' => 'autosinopselado.php',
        'banner_8' => 'note.php',
        'banner_9' => 'menads.php',
        'banner_10' => 'pagina.php'
    ];

    $phpFile = isset($phpFileMap[$selection]) ? $phpFileMap[$selection] : 'unknown.php';

    file_put_contents("./api/opcao.txt", $phpFile);
    file_put_contents("./api/ultima_opcao.txt", $selection);
}


$currentBanner = getLastSelection();

$banners = [
    'banner_1' => 'Automatic',
    'banner_2' => 'Automatic 2',
    'banner_3' => 'Automatic 3',
    'banner_4' => 'Automatic 4 for small banners',
    'banner_5' => 'Automatic 5',
    'banner_6' => 'Automatic 6',
    'banner_7' => 'Automatic 7 for bottom icons',
    'banner_8' => 'Banner with message',
    'banner_9' => 'Manual',
    'banner_10' => 'Web page'
];

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['banner_select'])) {
    $selectedBanner = $_POST['banner_select'];
    saveLastSelection($selectedBanner);

    $response = ['success' => true, 'message' => 'Banner type updated successfully!'];

    if ($selectedBanner === 'banner_8') {
        $response['redirect'] = 'messages.php';
    } elseif ($selectedBanner === 'banner_10') {
        $response['redirect'] = 'web_url.php';
    } elseif ($selectedBanner === 'banner_9') {
        $response['redirect'] = 'banner.php';
    }

    echo json_encode($response);
    exit;
}

$page_content = '
<div class="card mb-5">
    <div class="card-body">
        <div class="row">';

foreach ($banners as $banner_id => $banner_label) {
    $banner_image = $static_url . "media/banner-type/$banner_id.jpeg";
    $isChecked = ($currentBanner === $banner_id) ? 'checked' : '';
    $activeClass = ($currentBanner === $banner_id) ? 'active-banner' : '';

    $page_content .= '
            <div class="col-md-4 mb-4 text-center">
                <div class="position-relative">
                    <img src="' . $banner_image . '" alt="' . $banner_label . '" class="img-thumbnail mb-2 ' . $activeClass . '" style="max-width: 100%; height: auto;">
                    <div class="checkbox-container">
                        <input type="radio" name="banner_select" value="' . $banner_id . '" class="banner-checkbox" 
                            onchange="updateBanner(\'' . $banner_id . '\')" ' . $isChecked . '>
                        <label for="' . $banner_id . '">' . $banner_label . '</label>
                    </div>
                </div>
            </div>';
}

$page_content .= '
        </div>
    </div>
</div>';

$page_content .= '
<style>
img.active-banner {
    border: 3px solid #28a745;
    border-radius: 8px;
    padding: 2px;
}

.banner-checkbox {
    width: 20px;
    height: 20px;
    cursor: pointer;
}

.checkbox-container {
    margin-top: 10px;
    text-align: center;
}
</style>

<script>
function updateBanner(bannerId) {
    fetch("", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({ banner_select: bannerId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: "success",
                title: "Success",
                text: data.message
            }).then(() => {
                if (data.redirect) {
                    window.location.href = data.redirect;
                } else {
                    location.reload();
                }
            });
        } else {
            Swal.fire({
                icon: "error",
                title: "Error",
                text: data.message
            });
        }
    })
    .catch(error => {
        console.error("Error:", error);
        Swal.fire({
            icon: "error",
            title: "Error",
            text: "An unexpected error occurred."
        });
    });
}
</script>';

include 'includes/layout.php';
?>
