<?php
$db = new PDO('sqlite:' . __DIR__ . '/../api/db.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$db->exec("CREATE TABLE IF NOT EXISTS vencimento_config (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    ativo INTEGER NOT NULL DEFAULT 1,
    dias_antes INTEGER NOT NULL DEFAULT 7,
    titulo TEXT DEFAULT 'Seu acesso está perto de vencer',
    mensagem TEXT DEFAULT '',
    mostrar_qrcode INTEGER NOT NULL DEFAULT 1,
    updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))
)");

$db->exec("INSERT OR IGNORE INTO vencimento_config (id, ativo, dias_antes, titulo, mensagem, mostrar_qrcode) VALUES (1, 1, 7, 'Seu acesso está perto de vencer', 'Renove para continuar assistindo.', 1)");

$ok = '';

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $st = $db->prepare("UPDATE vencimento_config SET ativo=?, dias_antes=?, titulo=?, mensagem=?, mostrar_qrcode=?, updated_at=strftime('%s','now') WHERE id=1");
    $st->execute([
        (int)($_POST['ativo'] ?? 0),
        max(0, min(7, (int)($_POST['dias_antes'] ?? 7))),
        trim((string)($_POST['titulo'] ?? '')) ?: 'Seu acesso está perto de vencer',
        trim((string)($_POST['mensagem'] ?? '')),
        (int)($_POST['mostrar_qrcode'] ?? 0),
    ]);

    $ok = 'Configuração salva com sucesso.';
}

$row = $db->query('SELECT * FROM vencimento_config WHERE id=1')->fetch() ?: [];

include('./includes/header.php');
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.textarea-radius{
    border-radius:14px !important;
}
.save-btn{
    border-radius:14px;
    height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.info-box{
    background:rgba(0,0,0,.03);
    border:1px solid rgba(0,0,0,.08);
    border-radius:14px;
    padding:12px 14px;
    font-weight:700;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .save-btn{
        width:100%;
    }
}

/* SCROLLBAR CINZA - PC E MOBILE */
html{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

body{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

*::-webkit-scrollbar{
  width: 10px;
  height: 10px;
}

*::-webkit-scrollbar-track{
  background: #1f1f1f;
  border-radius: 999px;
}

*::-webkit-scrollbar-thumb{
  background: linear-gradient(180deg, #b8b8b8, #7c7c7c);
  border-radius: 999px;
  border: 2px solid #1f1f1f;
}

*::-webkit-scrollbar-thumb:hover{
  background: linear-gradient(180deg, #d0d0d0, #909090);
}

.table-responsive{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

@media (max-width: 768px){
  *::-webkit-scrollbar{
    width: 7px;
    height: 7px;
  }
}
</style>

<div class="dns-wrap">
    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-calendar-check"></i></div>
                <div>
                    <h5>Vencimentos</h5>
                    <span>Configure o aviso de vencimento exibido no aplicativo</span>
                </div>
            </div>

            <div class="dns-actions">
                <?php if (!empty($row['ativo'])): ?>
                    <span class="badge-soft"><i class="bi bi-check-circle-fill"></i> Ativo</span>
                <?php else: ?>
                    <span class="badge-soft"><i class="bi bi-lock-fill"></i> Inativo</span>
                <?php endif; ?>
            </div>
        </div>

        <div class="card-body">
            <?php if ($ok): ?>
                <div class="alert alert-success">
                    <?= htmlspecialchars($ok, ENT_QUOTES, 'UTF-8') ?>
                </div>
            <?php endif; ?>

            <form method="post" class="row g-3">
                <div class="col-lg-4 col-md-4 col-12">
                    <label class="form-label" style="font-weight:900;">Ativar aviso de vencimento</label>
                    <select name="ativo" class="form-select input-radius">
                        <option value="1" <?= !empty($row['ativo']) ? 'selected' : '' ?>>Sim</option>
                        <option value="0" <?= empty($row['ativo']) ? 'selected' : '' ?>>Não</option>
                    </select>
                </div>

                <div class="col-lg-4 col-md-4 col-12">
                    <label class="form-label" style="font-weight:900;">Dias antes para começar</label>
                    <select name="dias_antes" class="form-select input-radius">
                        <?php for($i = 0; $i <= 7; $i++): ?>
                            <option value="<?= $i ?>" <?= (int)($row['dias_antes'] ?? 7) === $i ? 'selected' : '' ?>>
                                <?= $i === 0 ? 'Só no dia do vencimento' : $i . ' dia(s) antes' ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div class="col-lg-4 col-md-4 col-12">
                    <label class="form-label" style="font-weight:900;">Mostrar QR Code</label>
                    <select name="mostrar_qrcode" class="form-select input-radius">
                        <option value="1" <?= !empty($row['mostrar_qrcode']) ? 'selected' : '' ?>>Sim</option>
                        <option value="0" <?= empty($row['mostrar_qrcode']) ? 'selected' : '' ?>>Não</option>
                    </select>
                </div>

                <div class="col-12">
                    <label class="form-label" style="font-weight:900;">Título do modal</label>
                    <input name="titulo" class="form-control input-radius" value="<?= htmlspecialchars((string)($row['titulo'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                </div>

                <div class="col-12">
                    <label class="form-label" style="font-weight:900;">Mensagem do modal</label>
                    <textarea name="mensagem" class="form-control textarea-radius" rows="5"><?= htmlspecialchars((string)($row['mensagem'] ?? ''), ENT_QUOTES, 'UTF-8') ?></textarea>
                </div>

                <div class="col-12">
                    <div class="info-box">
                        <strong>Atualização:</strong>
                        <?= !empty($row['updated_at']) ? date('d/m/Y H:i:s', (int)$row['updated_at']) : '-' ?>
                    </div>
                </div>

                <div class="col-12">
                    <button class="btn btn-success save-btn">
                        <i class="bi bi-save"></i> Salvar configuração
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include('./includes/footer.php'); ?>