<?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__ . '/alerta_status.json';

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

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

$alertaAtivo  = $data['alerta_vencimento_ativo']  ?? false;
$mensagemHoje = $data['mensagem_vencimento_hoje'] ?? '';
$mensagemDias = $data['mensagem_vencimento_dias'] ?? '';

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

    $alertaAtivo  = filter_var($_POST['alerta_ativo'] ?? false, FILTER_VALIDATE_BOOLEAN);
    $mensagemHoje = trim($_POST['mensagem_hoje'] ?? '');
    $mensagemDias = trim($_POST['mensagem_dias'] ?? '');

    if ($mensagemHoje === '' || $mensagemDias === '') {
        echo json_encode(['status' => 'error', 'message' => 'Preencha todas as mensagens!']);
        exit;
    }

    $data['alerta_vencimento_ativo']  = $alertaAtivo;
    $data['mensagem_vencimento_hoje'] = $mensagemHoje;
    $data['mensagem_vencimento_dias'] = $mensagemDias;

    file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

    echo json_encode(['status' => 'success', 'message' => 'Configurações salvas com sucesso!']);
    exit;
}

$page_title = "Alerta Vencimento";

$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(251,191,36,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(251,191,36,0.10);
    border: 1px solid rgba(251,191,36,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #fbbf24;
    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);
    margin-bottom: 20px;
}
.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: 15px;
    flex-shrink: 0;
}
.ph-icon-bell   { background: rgba(251,191,36,0.12);  border: 1px solid rgba(251,191,36,0.2);  color: #fbbf24; }
.ph-icon-today  { background: rgba(248,113,113,0.12); border: 1px solid rgba(248,113,113,0.2); color: #f87171; }
.ph-icon-days   { 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; }

/* ═══════════════════════════
   INFO BANNER
═══════════════════════════ */
.info-banner {
    background: rgba(99,179,237,0.06);
    border: 1px solid rgba(99,179,237,0.15);
    border-radius: 10px;
    padding: 12px 16px;
    font-size: 13px;
    color: rgba(99,179,237,0.85);
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 24px;
}
.info-banner i { font-size: 15px; flex-shrink: 0; }

/* ═══════════════════════════
   TOGGLE PRINCIPAL
═══════════════════════════ */
.main-toggle-card {
    background: rgba(255,255,255,0.02);
    border: 1px solid rgba(255,255,255,0.07);
    border-radius: 12px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    cursor: pointer;
    transition: all 0.2s ease;
    margin-bottom: 0;
}
.main-toggle-card.is-on {
    background: rgba(251,191,36,0.06);
    border-color: rgba(251,191,36,0.2);
}
.main-toggle-card:hover { background: rgba(255,255,255,0.04); }
.main-toggle-card.is-on:hover { background: rgba(251,191,36,0.09); }
.mtc-left { display: flex; align-items: center; gap: 12px; }
.mtc-left i { font-size: 20px; color: rgba(148,163,184,0.3); transition: color 0.2s ease; }
.main-toggle-card.is-on .mtc-left i { color: #fbbf24; }
.mtc-text h6 {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    font-weight: 700;
    margin: 0 0 2px;
    transition: color 0.2s ease;
}
.main-toggle-card.is-on .mtc-text h6 { color: #e2e8f0; }
.mtc-text small { color: rgba(148,163,184,0.35); font-size: 11px; }

/* Custom switch */
.tc-switch {
    position: relative;
    width: 44px; height: 24px;
    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: 3px; left: 3px;
    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(251,191,36,0.2);
    border-color: rgba(251,191,36,0.4);
}
.tc-switch input:checked + .tc-track::after {
    left: 23px;
    background: #fbbf24;
    box-shadow: 0 0 6px rgba(251,191,36,0.5);
}

/* ═══════════════════════════
   MESSAGE INPUTS
═══════════════════════════ */
.field-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;
}
.field-hint {
    color: rgba(148,163,184,0.35);
    font-size: 11px;
    margin-top: 6px;
    display: block;
}
.field-hint code {
    background: rgba(255,255,255,0.06);
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 4px;
    padding: 1px 6px;
    color: #fbbf24;
    font-size: 11px;
}
.dark-input {
    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: 11px 14px !important;
    width: 100%;
    transition: all 0.2s ease !important;
}
.dark-input::placeholder { color: rgba(148,163,184,0.3) !important; }
.dark-input:focus {
    outline: none !important;
    border-color: rgba(251,191,36,0.4) !important;
    box-shadow: 0 0 0 3px rgba(251,191,36,0.08) !important;
    background: rgba(251,191,36,0.03) !important;
}

/* preview badge */
.msg-preview {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 8px;
    padding: 8px 12px;
    font-size: 12px;
    color: rgba(148,163,184,0.5);
    margin-top: 8px;
    font-style: italic;
    display: none;
}
.msg-preview.visible { display: block; }

/* ═══════════════════════════
   SAVE BUTTON
═══════════════════════════ */
.btn-save-alert {
    background: linear-gradient(135deg, #b45309, #fbbf24) !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(251,191,36,0.2) !important;
    cursor: pointer;
}
.btn-save-alert:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(251,191,36,0.32) !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-bell"></i></span>
            Alerta Vencimento
        </h1>
        <p>Configure as mensagens enviadas automaticamente aos utilizadores próximos do vencimento.</p>
    </div>
</div>

<!-- ATIVAR / DESATIVAR -->
<div class="logo-panel">
    <div class="logo-panel-header">
        <div class="ph-icon ph-icon-bell"><i class="fa-solid fa-bell"></i></div>
        <div class="logo-panel-header-text">
            <h5>Estado do Alerta</h5>
            <p>Ative ou desative os alertas automáticos de vencimento</p>
        </div>
    </div>
    <div class="logo-panel-body">

        <div class="info-banner">
            <i class="fa-solid fa-circle-info"></i>
            As mensagens são exibidas automaticamente conforme a data de vencimento da assinatura do utilizador.
        </div>

        <div class="main-toggle-card ' . ($alertaAtivo ? 'is-on' : '') . '" id="mainToggleCard" onclick="toggleMain()">
            <div class="mtc-left">
                <i class="fa-solid fa-bell"></i>
                <div class="mtc-text">
                    <h6>Alertas de Vencimento</h6>
                    <small>Clique para ' . ($alertaAtivo ? 'desativar' : 'ativar') . '</small>
                </div>
            </div>
            <label class="tc-switch" onclick="event.stopPropagation()">
                <input type="checkbox" id="alertaAtivo" ' . ($alertaAtivo ? 'checked' : '') . ' onchange="syncMainToggle(this.checked)">
                <span class="tc-track"></span>
            </label>
        </div>

    </div>
</div>

<!-- MENSAGENS -->
<div class="row g-4">

    <!-- Vencimento Hoje -->
    <div class="col-lg-6">
        <div class="logo-panel" style="margin-bottom:0;">
            <div class="logo-panel-header">
                <div class="ph-icon ph-icon-today"><i class="fa-solid fa-calendar-day"></i></div>
                <div class="logo-panel-header-text">
                    <h5>Vencimento Hoje</h5>
                    <p>Mensagem exibida no dia do vencimento</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <label class="field-label">Mensagem</label>
                <input
                    type="text"
                    class="dark-input"
                    id="mensagemHoje"
                    placeholder="Ex: Sua assinatura vence hoje!"
                    value="' . htmlspecialchars($mensagemHoje, ENT_QUOTES) . '"
                    oninput="updatePreview(\'previewHoje\', this.value)"
                >
                <span class="field-hint">Mensagem exibida quando o vencimento é <strong style="color:#f87171;">hoje</strong>.</span>
                <div class="msg-preview ' . (!empty($mensagemHoje) ? 'visible' : '') . '" id="previewHoje">' . htmlspecialchars($mensagemHoje, ENT_QUOTES) . '</div>
            </div>
        </div>
    </div>

    <!-- Vencimento em Dias -->
    <div class="col-lg-6">
        <div class="logo-panel" style="margin-bottom:0;">
            <div class="logo-panel-header">
                <div class="ph-icon ph-icon-days"><i class="fa-solid fa-hourglass-half"></i></div>
                <div class="logo-panel-header-text">
                    <h5>Vencimento em Dias</h5>
                    <p>Mensagem exibida com antecedência</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <label class="field-label">Mensagem</label>
                <input
                    type="text"
                    class="dark-input"
                    id="mensagemDias"
                    placeholder="Ex: Sua assinatura vence em %d dias."
                    value="' . htmlspecialchars($mensagemDias, ENT_QUOTES) . '"
                    oninput="updatePreview(\'previewDias\', this.value)"
                >
                <span class="field-hint">Use <code>%d</code> para inserir o número de dias restantes.</span>
                <div class="msg-preview ' . (!empty($mensagemDias) ? 'visible' : '') . '" id="previewDias">' . htmlspecialchars($mensagemDias, ENT_QUOTES) . '</div>
            </div>
        </div>
    </div>

</div>

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

include 'includes/layout.php';
?>

<script>
// Toggle principal
function toggleMain() {
    const cb = document.getElementById('alertaAtivo');
    cb.checked = !cb.checked;
    syncMainToggle(cb.checked);
}
function syncMainToggle(checked) {
    const card = document.getElementById('mainToggleCard');
    const hint = card.querySelector('.mtc-text small');
    if (checked) {
        card.classList.add('is-on');
        hint.textContent = 'Clique para desativar';
    } else {
        card.classList.remove('is-on');
        hint.textContent = 'Clique para ativar';
    }
}

// Preview ao digitar
function updatePreview(previewId, val) {
    const el = document.getElementById(previewId);
    if (val.trim()) {
        el.textContent = val;
        el.classList.add('visible');
    } else {
        el.classList.remove('visible');
    }
}

// Salvar
document.getElementById('btnSalvar').addEventListener('click', function () {
    const mensagemHoje = document.getElementById('mensagemHoje').value.trim();
    const mensagemDias = document.getElementById('mensagemDias').value.trim();
    const alertaAtivo  = document.getElementById('alertaAtivo').checked;

    if (!mensagemHoje || !mensagemDias) {
        Swal.fire('Atenção', 'Preencha todas as mensagens.', 'warning');
        return;
    }

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

        const body = new URLSearchParams({
            alerta_ativo:  alertaAtivo,
            mensagem_hoje: mensagemHoje,
            mensagem_dias: mensagemDias
        });

        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>