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

/* ==========================
   JSON NO MESMO DIRETÓRIO
========================== */
$jsonFile = __DIR__ . '/maintenance.json';

if (!file_exists($jsonFile)) {
    die('Arquivo maintenance.json não encontrado.');
}

$data = json_decode(file_get_contents($jsonFile), true);

$btnCanais = (bool)($data['btnCanais'] ?? false);
$btnFilmes = (bool)($data['btnFilmes'] ?? false);
$btnSeries = (bool)($data['btnSeries'] ?? false);
$message   = $data['message'] ?? '';

/* ==========================
   SALVAR VIA AJAX
========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $data['btnCanais'] = ($_POST['btnCanais'] ?? 0) == 1;
    $data['btnFilmes'] = ($_POST['btnFilmes'] ?? 0) == 1;
    $data['btnSeries'] = ($_POST['btnSeries'] ?? 0) == 1;
    $data['message']   = trim($_POST['message'] ?? '');

    if ($data['message'] === '') {
        echo json_encode(['status' => 'error', 'message' => 'A mensagem de manutenção é obrigatória.']);
        exit;
    }

    file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    echo json_encode(['status' => 'success', 'message' => 'Configurações de manutenção salvas com sucesso!']);
    exit;
}

$page_title = "Manutenção Servidor";

$page_content = '
<style>
/* ═══════════════════════════
   PAGE HEADER
═══════════════════════════ */
.mac-page-header {
    background: linear-gradient(135deg, #0d1117 0%, #1a2744 50%, #0d1117 100%);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 16px;
    padding: 28px 32px;
    margin-bottom: 24px;
    margin-top: 24px;
    position: relative;
    overflow: hidden;
}
.mac-page-header::before {
    content: "";
    position: absolute;
    top: -60px; right: -60px;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(248,113,113,0.08) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header::after {
    content: "";
    position: absolute;
    bottom: -40px; left: 30%;
    width: 150px; height: 150px;
    background: radial-gradient(circle, rgba(99,179,237,0.07) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header h1 {
    color: #e2e8f0;
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 6px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.mac-page-header h1 .icon-wrap {
    width: 40px; height: 40px;
    background: rgba(248,113,113,0.10);
    border: 1px solid rgba(248,113,113,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #f87171;
    flex-shrink: 0;
}
.mac-page-header p {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    margin: 0;
}

/* ═══════════════════════════
   PANEL
═══════════════════════════ */
.logo-panel {
    background: #161b22;
    border: 1px solid rgba(99,179,237,0.08);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0,0,0,0.3);
}
.logo-panel-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
    padding: 18px 24px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.ph-icon {
    width: 36px; height: 36px;
    border-radius: 9px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px;
    flex-shrink: 0;
}
.ph-icon-warn  { background: rgba(248,113,113,0.12); border: 1px solid rgba(248,113,113,0.2); color: #f87171; }
.ph-icon-msg   { background: rgba(251,191,36,0.12);  border: 1px solid rgba(251,191,36,0.2);  color: #fbbf24; }
.logo-panel-header-text h5 {
    color: #e2e8f0;
    font-size: 14px;
    font-weight: 700;
    margin: 0 0 2px;
}
.logo-panel-header-text p {
    color: rgba(148,163,184,0.5);
    font-size: 12px;
    margin: 0;
}
.logo-panel-body { padding: 24px; }

/* ═══════════════════════════
   WARNING BANNER
═══════════════════════════ */
.warn-banner {
    background: rgba(248,113,113,0.07);
    border: 1px solid rgba(248,113,113,0.18);
    border-radius: 10px;
    padding: 12px 16px;
    font-size: 13px;
    color: rgba(248,113,113,0.9);
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 24px;
}
.warn-banner i { font-size: 15px; flex-shrink: 0; }

/* ═══════════════════════════
   TOGGLE CARDS
═══════════════════════════ */
.toggle-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 24px;
}
@media(max-width: 640px) { .toggle-grid { grid-template-columns: 1fr; } }

.toggle-card {
    background: rgba(255,255,255,0.02);
    border: 1px solid rgba(255,255,255,0.07);
    border-radius: 12px;
    padding: 18px 16px;
    display: flex;
    align-items: center;
    gap: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    user-select: none;
}
.toggle-card:hover {
    background: rgba(255,255,255,0.04);
    border-color: rgba(255,255,255,0.12);
}
.toggle-card.is-on {
    background: rgba(248,113,113,0.07);
    border-color: rgba(248,113,113,0.22);
}
.tc-icon {
    width: 38px; height: 38px;
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
    background: rgba(255,255,255,0.04);
    border: 1px solid rgba(255,255,255,0.07);
    transition: all 0.2s ease;
}
.toggle-card.is-on .tc-icon {
    background: rgba(248,113,113,0.12);
    border-color: rgba(248,113,113,0.22);
}
.tc-label {
    flex: 1;
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    font-weight: 600;
    transition: color 0.2s ease;
}
.toggle-card.is-on .tc-label { color: #f87171; }

/* Custom toggle switch */
.tc-switch {
    position: relative;
    width: 40px; height: 22px;
    flex-shrink: 0;
}
.tc-switch input { display: none; }
.tc-track {
    position: absolute;
    inset: 0;
    background: rgba(255,255,255,0.08);
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 50px;
    transition: all 0.2s ease;
    cursor: pointer;
}
.tc-track::after {
    content: "";
    position: absolute;
    top: 2px; left: 2px;
    width: 16px; height: 16px;
    background: rgba(148,163,184,0.5);
    border-radius: 50%;
    transition: all 0.2s ease;
}
.tc-switch input:checked + .tc-track {
    background: rgba(248,113,113,0.25);
    border-color: rgba(248,113,113,0.4);
}
.tc-switch input:checked + .tc-track::after {
    left: 20px;
    background: #f87171;
    box-shadow: 0 0 6px rgba(248,113,113,0.5);
}

/* ═══════════════════════════
   MESSAGE TEXTAREA
═══════════════════════════ */
.msg-label {
    color: rgba(148,163,184,0.8);
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    display: block;
    margin-bottom: 8px;
}
textarea#message {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    border-radius: 10px !important;
    color: #e2e8f0 !important;
    font-size: 13px !important;
    padding: 12px 14px !important;
    width: 100%;
    resize: vertical;
    min-height: 110px;
    transition: all 0.2s ease !important;
}
textarea#message::placeholder { color: rgba(148,163,184,0.3) !important; }
textarea#message:focus {
    border-color: rgba(248,113,113,0.4) !important;
    box-shadow: 0 0 0 3px rgba(248,113,113,0.08) !important;
    background: rgba(248,113,113,0.03) !important;
    outline: none !important;
}

/* ═══════════════════════════
   SAVE BUTTON
═══════════════════════════ */
.btn-save-maint {
    background: linear-gradient(135deg, #b91c1c, #f87171) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 11px 28px !important;
    display: flex; align-items: center; gap: 8px;
    transition: all 0.2s ease !important;
    box-shadow: 0 4px 12px rgba(248,113,113,0.25) !important;
    cursor: pointer;
}
.btn-save-maint:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(248,113,113,0.35) !important;
}
</style>

<!-- PAGE HEADER -->
<div class="mac-page-header d-flex align-items-center justify-content-between flex-wrap gap-3">
    <div>
        <h1>
            <span class="icon-wrap"><i class="fa-solid fa-screwdriver-wrench"></i></span>
            Manutenção Servidor
        </h1>
        <p>Bloqueie recursos e defina a mensagem exibida durante a manutenção.</p>
    </div>
</div>

<!-- TOGGLES -->
<div class="logo-panel mb-4">
    <div class="logo-panel-header">
        <div class="ph-icon ph-icon-warn"><i class="fa-solid fa-triangle-exclamation"></i></div>
        <div class="logo-panel-header-text">
            <h5>Recursos Bloqueados</h5>
            <p>Ative os itens que devem ficar indisponíveis durante a manutenção</p>
        </div>
    </div>
    <div class="logo-panel-body">

        <div class="warn-banner">
            <i class="fa-solid fa-circle-exclamation"></i>
            Marque os recursos que devem ficar <strong>&nbsp;bloqueados&nbsp;</strong> enquanto o servidor estiver em manutenção.
        </div>

        <div class="toggle-grid">

            <!-- Canais -->
            <div class="toggle-card ' . ($btnCanais ? 'is-on' : '') . '" id="card_canais" onclick="toggleCard(\'canais\')">
                <div class="tc-icon"><i class="fa-solid fa-tv" style="color:#38bdf8;"></i></div>
                <span class="tc-label">Canais</span>
                <label class="tc-switch" onclick="event.stopPropagation()">
                    <input type="checkbox" id="btnCanais" ' . ($btnCanais ? 'checked' : '') . ' onchange="syncCard(\'canais\', this.checked)">
                    <span class="tc-track"></span>
                </label>
            </div>

            <!-- Filmes -->
            <div class="toggle-card ' . ($btnFilmes ? 'is-on' : '') . '" id="card_filmes" onclick="toggleCard(\'filmes\')">
                <div class="tc-icon"><i class="fa-solid fa-film" style="color:#a78bfa;"></i></div>
                <span class="tc-label">Filmes</span>
                <label class="tc-switch" onclick="event.stopPropagation()">
                    <input type="checkbox" id="btnFilmes" ' . ($btnFilmes ? 'checked' : '') . ' onchange="syncCard(\'filmes\', this.checked)">
                    <span class="tc-track"></span>
                </label>
            </div>

            <!-- Séries -->
            <div class="toggle-card ' . ($btnSeries ? 'is-on' : '') . '" id="card_series" onclick="toggleCard(\'series\')">
                <div class="tc-icon"><i class="fa-solid fa-circle-play" style="color:#fb923c;"></i></div>
                <span class="tc-label">Séries</span>
                <label class="tc-switch" onclick="event.stopPropagation()">
                    <input type="checkbox" id="btnSeries" ' . ($btnSeries ? 'checked' : '') . ' onchange="syncCard(\'series\', this.checked)">
                    <span class="tc-track"></span>
                </label>
            </div>

        </div>
    </div>
</div>

<!-- MENSAGEM -->
<div class="logo-panel">
    <div class="logo-panel-header">
        <div class="ph-icon ph-icon-msg"><i class="fa-solid fa-message"></i></div>
        <div class="logo-panel-header-text">
            <h5>Mensagem de Manutenção</h5>
            <p>Texto exibido aos utilizadores durante o bloqueio</p>
        </div>
    </div>
    <div class="logo-panel-body">
        <label class="msg-label">Mensagem</label>
        <textarea id="message" placeholder="Ex: Estamos em manutenção. Voltamos em breve!">' . htmlspecialchars($message, ENT_QUOTES) . '</textarea>

        <div class="d-flex justify-content-end mt-4">
            <button class="btn-save-maint" id="btnSalvar">
                <i class="fa-solid fa-floppy-disk"></i> Salvar Configurações
            </button>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
// Toggle card ao clicar no card inteiro
function toggleCard(name) {
    const cb   = document.getElementById('btn' + name.charAt(0).toUpperCase() + name.slice(1));
    cb.checked = !cb.checked;
    syncCard(name, cb.checked);
}

function syncCard(name, checked) {
    const card = document.getElementById('card_' + name);
    if (checked) card.classList.add('is-on');
    else         card.classList.remove('is-on');
}

// Salvar
document.getElementById('btnSalvar').addEventListener('click', function () {
    const msg = document.getElementById('message').value.trim();

    if (!msg) {
        Swal.fire('Atenção', 'A mensagem de manutenção é obrigatória.', 'warning');
        return;
    }

    Swal.fire({
        title: 'Confirmar',
        text: 'Deseja salvar as configurações de manutenção?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Sim, salvar',
        cancelButtonText: 'Cancelar'
    }).then(result => {
        if (!result.isConfirmed) return;

        const body = new URLSearchParams({
            btnCanais: document.getElementById('btnCanais').checked ? 1 : 0,
            btnFilmes: document.getElementById('btnFilmes').checked ? 1 : 0,
            btnSeries: document.getElementById('btnSeries').checked ? 1 : 0,
            message: msg
        });

        fetch(window.location.href, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body
        })
        .then(r => r.json())
        .then(data => {
            if (data.status === 'success') {
                Swal.fire('Sucesso!', data.message, 'success');
            } else {
                Swal.fire('Erro', data.message, 'error');
            }
        })
        .catch(() => Swal.fire('Erro', 'Erro ao salvar o arquivo.', 'error'));
    });
});
</script>