<?php
require_once 'protege.php';
require_once '../config.php';

function renovarLicenca($pdo, $licenca_id)
{
    $stmt = $pdo->prepare("SELECT * FROM licencas WHERE id = ? LIMIT 1");
    $stmt->execute([$licenca_id]);
    $licenca = $stmt->fetch();

    if (!$licenca) {
        return false;
    }

    $hoje = date('Y-m-d');
    $base = $licenca['data_expiracao'];

    if (empty($base) || $base < $hoje) {
        $base = $hoje;
    }

    if ($licenca['tipo'] === 'mensal') {
        $novaData = date('Y-m-d', strtotime($base . ' +30 days'));
    } elseif ($licenca['tipo'] === 'anual') {
        $novaData = date('Y-m-d', strtotime($base . ' +365 days'));
    } elseif ($licenca['tipo'] === 'teste') {
        $novaData = date('Y-m-d', strtotime($base . ' +7 days'));
    } else {
        $novaData = null;
    }

    $stmt = $pdo->prepare("
        UPDATE licencas
        SET status = 'ativa',
            ultimo_pagamento = ?,
            proxima_cobranca = ?,
            data_expiracao = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $hoje,
        $novaData,
        $novaData,
        $licenca_id
    ]);

    return true;
}

if (isset($_GET['marcar_pago'])) {
    $pagamento_id = (int)$_GET['marcar_pago'];

    $stmt = $pdo->prepare("SELECT * FROM pagamentos WHERE id = ? LIMIT 1");
    $stmt->execute([$pagamento_id]);
    $pagamento = $stmt->fetch();

    if ($pagamento) {
        $pdo->beginTransaction();

        try {
            $stmt = $pdo->prepare("
                UPDATE pagamentos
                SET status = 'pago', pago_em = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$pagamento_id]);

            renovarLicenca($pdo, $pagamento['licenca_id']);

            $pdo->commit();

            header('Location: pagamentos.php?ok=1');
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            header('Location: pagamentos.php?erro=1');
            exit;
        }
    }
}

if (isset($_GET['cancelar'])) {
    $pagamento_id = (int)$_GET['cancelar'];

    $stmt = $pdo->prepare("
        UPDATE pagamentos
        SET status = 'cancelado'
        WHERE id = ?
    ");
    $stmt->execute([$pagamento_id]);

    header('Location: pagamentos.php');
    exit;
}

$status = $_GET['status'] ?? '';

if ($status) {
    $stmt = $pdo->prepare("
        SELECT 
            p.*,
            c.nome AS cliente_nome,
            c.email AS cliente_email,
            l.chave,
            l.tipo,
            l.data_expiracao
        FROM pagamentos p
        INNER JOIN clientes c ON c.id = p.cliente_id
        INNER JOIN licencas l ON l.id = p.licenca_id
        WHERE p.status = ?
        ORDER BY p.id DESC
    ");
    $stmt->execute([$status]);
} else {
    $stmt = $pdo->query("
        SELECT 
            p.*,
            c.nome AS cliente_nome,
            c.email AS cliente_email,
            l.chave,
            l.tipo,
            l.data_expiracao
        FROM pagamentos p
        INNER JOIN clientes c ON c.id = p.cliente_id
        INNER JOIN licencas l ON l.id = p.licenca_id
        ORDER BY p.id DESC
    ");
}

$pagamentos = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Pagamentos - PromoCreative LED Mapper</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
*{box-sizing:border-box}
body{
    margin:0;
    background:
        radial-gradient(circle at top left,rgba(0,170,255,.16),transparent 32%),
        radial-gradient(circle at bottom right,rgba(255,122,0,.13),transparent 28%),
        #060b16;
    color:#fff;
    font-family:Arial,Helvetica,sans-serif;
}
.sidebar{
    width:280px;height:100vh;position:fixed;left:0;top:0;
    background:rgba(8,15,29,.96);
    border-right:1px solid rgba(255,255,255,.08);
    padding:26px;
}
.logo{margin-bottom:34px}
.logo strong{display:block;font-size:21px;line-height:1.2}
.logo span{display:block;margin-top:8px;color:#7f95bd;font-size:13px}
.sidebar a{
    display:block;color:#b7c7e8;text-decoration:none;
    padding:14px 15px;border-radius:13px;margin-bottom:8px;
}
.sidebar a:hover,.sidebar a.active{
    background:linear-gradient(135deg,rgba(255,122,0,.18),rgba(0,170,255,.18));
    color:#fff;
}
.main{margin-left:280px;padding:36px}
.header{
    display:flex;justify-content:space-between;align-items:center;
    margin-bottom:26px;gap:16px;
}
.header h1{margin:0;font-size:30px}
.header p{margin:8px 0 0;color:#8fa3c7}
.filters{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:22px;
}
.filters a{
    color:#fff;
    text-decoration:none;
    background:#13223a;
    padding:10px 14px;
    border-radius:12px;
    font-size:14px;
}
.filters a.active{
    background:linear-gradient(135deg,#ff7a00,#00aaff);
}
.card{
    background:rgba(13,24,43,.92);
    border:1px solid rgba(255,255,255,.08);
    border-radius:24px;
    padding:24px;
    box-shadow:0 24px 70px rgba(0,0,0,.35);
    overflow-x:auto;
}
.table{width:100%;border-collapse:collapse;min-width:1100px}
.table th,.table td{
    padding:15px 13px;
    border-bottom:1px solid rgba(255,255,255,.07);
    text-align:left;
    font-size:14px;
    vertical-align:top;
}
.table th{color:#7f95bd;font-weight:normal}
.small{color:#7f95bd;font-size:13px}
.key{
    font-family:Consolas,monospace;
    color:#00d4ff;
    font-weight:bold;
}
.badge{
    display:inline-block;
    padding:6px 11px;
    border-radius:999px;
    font-size:12px;
}
.pendente{background:rgba(255,200,0,.12);color:#ffe58a}
.pago{background:rgba(0,255,160,.12);color:#9fffc8}
.cancelado{background:rgba(255,60,60,.12);color:#ffc1c1}
.actions a{
    display:inline-block;
    margin:3px 4px 3px 0;
    padding:8px 10px;
    border-radius:10px;
    text-decoration:none;
    font-size:12px;
    background:#13223a;
    color:#fff;
}
.actions .ok{background:rgba(0,255,160,.18);color:#9fffc8}
.actions .cancel{background:rgba(255,60,60,.14);color:#ffc1c1}
.alert{
    padding:15px;
    border-radius:14px;
    margin-bottom:18px;
}
.success{
    background:rgba(0,255,160,.12);
    border:1px solid rgba(0,255,160,.3);
    color:#b7ffd8;
}
.error{
    background:rgba(255,60,60,.12);
    border:1px solid rgba(255,60,60,.3);
    color:#ffc1c1;
}
.empty{
    text-align:center;
    padding:35px;
    color:#8fa3c7;
}
@media(max-width:950px){
    .sidebar{position:relative;width:100%;height:auto}
    .main{margin-left:0;padding:20px}
    .header{flex-direction:column;align-items:flex-start}
}
</style>
</head>

<body>

<div class="sidebar">
    <div class="logo">
        <strong>PromoCreative<br>LED Mapper</strong>
        <span>Painel de licenças</span>
    </div>

    <a href="dashboard.php">Dashboard</a>
    <a href="clientes.php">Clientes</a>
    <a href="licencas.php">Licenças</a>
    <a href="gerar_licenca.php">Gerar Licença</a>
    <a href="computadores.php">Computadores</a>
    <a class="active" href="pagamentos.php">Pagamentos</a>
    <a href="logout.php">Sair</a>
</div>

<div class="main">
    <div class="header">
        <div>
            <h1>Pagamentos</h1>
            <p>Controle pagamentos, renovações e liberação manual de licenças.</p>
        </div>
    </div>

    <?php if (isset($_GET['ok'])): ?>
        <div class="alert success">Pagamento marcado como pago e licença renovada com sucesso.</div>
    <?php endif; ?>

    <?php if (isset($_GET['erro'])): ?>
        <div class="alert error">Erro ao processar pagamento.</div>
    <?php endif; ?>

    <div class="filters">
        <a class="<?= $status === '' ? 'active' : ''; ?>" href="pagamentos.php">Todos</a>
        <a class="<?= $status === 'pendente' ? 'active' : ''; ?>" href="pagamentos.php?status=pendente">Pendentes</a>
        <a class="<?= $status === 'pago' ? 'active' : ''; ?>" href="pagamentos.php?status=pago">Pagos</a>
        <a class="<?= $status === 'cancelado' ? 'active' : ''; ?>" href="pagamentos.php?status=cancelado">Cancelados</a>
    </div>

    <div class="card">
        <?php if (empty($pagamentos)): ?>
            <div class="empty">Nenhum pagamento encontrado.</div>
        <?php else: ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Cliente</th>
                        <th>Licença</th>
                        <th>Plano</th>
                        <th>Valor</th>
                        <th>Status</th>
                        <th>Referência</th>
                        <th>Criado em</th>
                        <th>Pago em</th>
                        <th>Vencimento atual</th>
                        <th>Ações</th>
                    </tr>
                </thead>

                <tbody>
                <?php foreach ($pagamentos as $p): ?>
                    <tr>
                        <td>
                            <?= htmlspecialchars($p['cliente_nome']); ?><br>
                            <span class="small"><?= htmlspecialchars($p['cliente_email']); ?></span>
                        </td>

                        <td>
                            <span class="key"><?= htmlspecialchars($p['chave']); ?></span>
                        </td>

                        <td><?= htmlspecialchars(ucfirst($p['tipo'])); ?></td>

                        <td>R$ <?= number_format((float)$p['valor'], 2, ',', '.'); ?></td>

                        <td>
                            <span class="badge <?= htmlspecialchars($p['status']); ?>">
                                <?= htmlspecialchars($p['status']); ?>
                            </span>
                        </td>

                        <td><?= htmlspecialchars($p['referencia'] ?: '-'); ?></td>

                        <td><?= date('d/m/Y H:i', strtotime($p['criado_em'])); ?></td>

                        <td>
                            <?= $p['pago_em'] ? date('d/m/Y H:i', strtotime($p['pago_em'])) : '-'; ?>
                        </td>

                        <td>
                            <?= $p['data_expiracao'] ? date('d/m/Y', strtotime($p['data_expiracao'])) : 'Vitalícia'; ?>
                        </td>

                        <td class="actions">
                            <?php if ($p['status'] === 'pendente'): ?>
                                <a class="ok"
                                   href="pagamentos.php?marcar_pago=<?= (int)$p['id']; ?>"
                                   onclick="return confirm('Confirmar pagamento e renovar licença?');">
                                    Marcar pago
                                </a>

                                <a class="cancel"
                                   href="pagamentos.php?cancelar=<?= (int)$p['id']; ?>"
                                   onclick="return confirm('Cancelar este pagamento?');">
                                    Cancelar
                                </a>
                            <?php else: ?>
                                <span class="small">Sem ação</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

</body>
</html>