<?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 = "Themes Page";

$currentTheme = null;
try {
    $db = new PDO('sqlite:ibo_panel.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->query("SELECT theme_id FROM themes LIMIT 1");
    $currentThemeNumber = $stmt->fetchColumn();

    $currentTheme = 'theme_' . $currentThemeNumber;
} catch (PDOException $e) {
    $currentTheme = null;
}


$themes = range(1, 26);
$page_content = '
<div class="card mb-5">
    <div class="card-body">
        <div class="row">';

foreach ($themes as $theme) {
    $theme_id = "theme_$theme";
    $theme_image = $static_url . "media/themes/$theme_id.png";
    $isChecked = ($currentTheme === $theme_id) ? 'checked' : '';
    $activeClass = ($currentTheme === $theme_id) ? 'active-theme' : '';

    $page_content .= '
            <div class="col-md-4 mb-4 text-center">
                <div class="position-relative">
                    <img src="' . $theme_image . '" alt="Theme ' . $theme . '" class="img-thumbnail mb-2 ' . $activeClass . '" style="max-width: 100%;">
                    <div class="checkbox-container">
                        <input type="checkbox" name="theme_select" value="' . $theme_id . '" class="theme-checkbox" 
                            onchange="updateTheme(\'' . $theme_id . '\')" ' . $isChecked . '>
                    </div>
                </div>
            </div>';
}

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

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

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

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

<script>
function updateTheme(themeId) {
    fetch("actions/themes_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "edit", theme_id: themeId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: "success",
                title: "Success",
                text: "Theme updated successfully!"
            }).then(() => {
                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';
?>
