<?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 = "Personalização de Temas";

$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, 6);
$page_content = '
<div class="container-fluid py-5">
    <div class="row mb-5 justify-content-center">
        <div class="col-lg-8 text-center">
            <h1 class="display-5 fw-extra-bold text-gradient mb-3">Customização de Interface</h1>
            <p class="fs-5 text-muted">Transforme a experiência visual do seu painel com apenas um clique.</p>
            <div class="h-1px w-100px bg-primary mx-auto"></div>
        </div>
    </div>

    <div class="row g-4 px-lg-5">';

foreach ($themes as $theme) {
    $theme_id = "theme_$theme";
    $theme_image = $static_url . "media/themes/$theme_id.png";
    $isActive = ($currentTheme === $theme_id);
    $isChecked = $isActive ? 'checked' : '';
    
    $page_content .= '
        <div class="col-xl-4 col-md-6">
            <div class="premium-card ' . ($isActive ? 'active' : '') . '" onclick="selectTheme(this, \'' . $theme_id . '\')">
                ' . ($isActive ? '<div class="active-ribbon"><span>EM USO</span></div>' : '') . '
                
                <div class="premium-preview">
                    <img src="' . $theme_image . '" alt="Layout ' . $theme . '">
                    <div class="hover-overlay">
                        <button class="btn btn-light btn-sm fw-bold shadow-sm">Aplicar este Tema</button>
                    </div>
                </div>

                <div class="premium-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <div class="info">
                            <h5 class="mb-1 fw-bold">Layout Edition #' . $theme . '</h5>
                            <div class="d-flex align-items-center gap-2">
                                <span class="dot ' . ($isActive ? 'bg-success' : 'bg-secondary') . '"></span>
                                <small class="text-uppercase ls-1 fw-semibold text-muted">' . ($isActive ? 'Ativo agora' : 'Disponível') . '</small>
                            </div>
                        </div>
                        <div class="selector-wrapper">
                            <div class="custom-check">
                                <input type="radio" name="theme_select" value="' . $theme_id . '" ' . $isChecked . '>
                                <span class="checkmark"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>';
}

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

$page_content .= '
<style>
/* Fontes e Variáveis */
.fw-extra-bold { font-weight: 800; }
.ls-1 { letter-spacing: 1px; }
.text-gradient { 
    background: linear-gradient(45deg, #2b32b2, #1488cc);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

/* Estrutura do Card Premium */
.premium-card {
    background: #ffffff;
    border-radius: 24px;
    border: 1px solid rgba(0,0,0,0.08);
    overflow: hidden;
    position: relative;
    transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
    cursor: pointer;
    box-shadow: 0 10px 30px rgba(0,0,0,0.03);
}

.premium-card:hover {
    transform: translateY(-12px);
    box-shadow: 0 25px 50px rgba(0,0,0,0.1);
    border-color: #007bff;
}

/* Preview de Imagem */
.premium-preview {
    position: relative;
    height: 220px;
    overflow: hidden;
}

.premium-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.8s ease;
}

.premium-card:hover .premium-preview img {
    transform: scale(1.15);
}

/* Overlay no Hover */
.hover-overlay {
    position: absolute;
    top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0, 123, 255, 0.4);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: 0.3s;
    backdrop-filter: blur(3px);
}

.premium-card:hover .hover-overlay {
    opacity: 1;
}

/* Ribbon de Ativo */
.active-ribbon {
    position: absolute;
    top: 20px;
    left: -35px;
    background: #28a745;
    color: white;
    padding: 5px 40px;
    transform: rotate(-45deg);
    font-size: 10px;
    font-weight: 800;
    z-index: 10;
    box-shadow: 0 5px 10px rgba(0,0,0,0.1);
}

/* Corpo do Card */
.premium-body {
    padding: 24px;
    background: #fff;
}

.dot {
    height: 8px;
    width: 8px;
    border-radius: 50%;
    display: inline-block;
}

/* Card Ativo Style */
.premium-card.active {
    border: 2px solid #28a745;
    box-shadow: 0 0 20px rgba(40, 167, 69, 0.15);
}

/* Custom Checkbox */
.custom-check {
    position: relative;
    width: 28px;
    height: 28px;
}

.custom-check input { opacity: 0; width: 0; height: 0; }

.checkmark {
    position: absolute;
    top: 0; left: 0;
    height: 28px; width: 28px;
    background-color: #f0f0f0;
    border-radius: 50%;
    transition: 0.4s;
    border: 2px solid #ddd;
}

.custom-check input:checked ~ .checkmark {
    background-color: #28a745;
    border-color: #28a745;
}

.checkmark:after {
    content: "";
    position: absolute;
    display: none;
    left: 9px; top: 5px;
    width: 7px; height: 12px;
    border: solid white;
    border-width: 0 3px 3px 0;
    transform: rotate(45deg);
}

.custom-check input:checked ~ .checkmark:after {
    display: block;
}

/* Utilitários */
.h-1px { height: 3px; border-radius: 5px; }
.w-100px { width: 60px; }

@media (max-width: 768px) {
    .premium-preview { height: 180px; }
}
</style>

<script>
function selectTheme(card, themeId) {
    const radio = card.querySelector(\'input[type="radio"]\');
    if(!radio.checked) {
        radio.checked = true;
        updateTheme(themeId);
    }
}

function updateTheme(themeId) {
    Swal.fire({
        title: "Alterando Identidade",
        html: "Sincronizando novas configurações de design...",
        allowOutsideClick: false,
        didOpen: () => { Swal.showLoading(); }
    });

    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: "Layout Aplicado!",
                showConfirmButton: false,
                timer: 2000,
                timerProgressBar: true
            }).then(() => {
                location.reload();
            });
        } else {
            Swal.fire({ icon: "error", title: "Ops!", text: data.message });
        }
    })
    .catch(error => {
        Swal.fire({ icon: "error", title: "Erro de Conexão" });
    });
}
</script>';

include 'includes/layout.php';
?>