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

$mensagem = '';
$erro = '';
$licencaGerada = '';
$emailCliente = '';
$senhaTemporaria = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nome = trim($_POST['nome'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $whatsapp = trim($_POST['whatsapp'] ?? '');
    $tipo = $_POST['tipo'] ?? 'mensal';
    $limite_maquinas = (int)($_POST['limite_maquinas'] ?? 1);
    $valor = str_replace(',', '.', trim($_POST['valor'] ?? '0'));

    if (empty($nome) || empty($email)) {
        $erro = 'Informe nome e e-mail do cliente.';
    } else {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("SELECT * FROM clientes WHERE email = ? LIMIT 1");
            $stmt->execute([$email]);
            $cliente = $stmt->fetch();

            if ($cliente) {
                $cliente_id = $cliente['id'];
            } else {
                $senhaTemporaria = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 8);
                $senhaHash = password_hash($senhaTemporaria, PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO clientes (nome, email, whatsapp, senha, status)
                    VALUES (?, ?, ?, ?, 'ativo')
                ");
                $stmt->execute([$nome, $email, $whatsapp, $senhaHash]);
                $cliente_id = $pdo->lastInsertId();
            }

            $data_inicio = date('Y-m-d');
            $data_expiracao = null;

            if ($tipo === 'teste') {
                $data_expiracao = date('Y-m-d', strtotime('+7 days'));
            } elseif ($tipo === 'mensal') {
                $data_expiracao = date('Y-m-d', strtotime('+30 days'));
            } elseif ($tipo === 'anual') {
                $data_expiracao = date('Y-m-d', strtotime('+365 days'));
            }

            do {
                $chave = gerarChaveLicenca();
                $check = $pdo->prepare("SELECT id FROM licencas WHERE chave = ?");
                $check->execute([$chave]);
            } while ($check->fetch());

            $stmt = $pdo->prepare("
                INSERT INTO licencas 
                (cliente_id, chave, tipo, status, data_inicio, data_expiracao, limite_maquinas, valor, ultimo_pagamento, proxima_cobranca)
                VALUES (?, ?, ?, 'ativa', ?, ?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $cliente_id,
                $chave,
                $tipo,
                $data_inicio,
                $data_expiracao,
                $limite_maquinas,
                $valor,
                $data_inicio,
                $data_expiracao
            ]);

            $pdo->commit();

            $mensagem = 'Licença gerada com sucesso.';
            $licencaGerada = $chave;
            $emailCliente = $email;

        } catch (Exception $e) {
            $pdo->rollBack();
            $erro = 'Erro ao gerar licença: ' . $e->getMessage();
        }
    }
}

$clientes = $pdo->query("
    SELECT 
        c.id,
        c.nome,
        c.email,
        c.whatsapp,
        c.status,
        COUNT(l.id) AS total_licencas
    FROM clientes c
    LEFT JOIN licencas l ON l.cliente_id = c.id
    GROUP BY c.id
    ORDER BY c.id DESC
    LIMIT 10
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Gerar Licença - 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,.18),transparent 32%),
        radial-gradient(circle at bottom right,rgba(255,122,0,.15),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:28px;
}
.header h1{
    margin:0;
    font-size:30px;
}
.header p{
    margin:8px 0 0;
    color:#8fa3c7;
}
.grid{
    display:grid;
    grid-template-columns:1.1fr .9fr;
    gap:24px;
}
.card{
    background:rgba(13,24,43,.92);
    border:1px solid rgba(255,255,255,.08);
    border-radius:24px;
    padding:28px;
    box-shadow:0 24px 70px rgba(0,0,0,.35);
}
.card h2{
    margin:0 0 20px;
    font-size:22px;
}
label{
    display:block;
    margin:15px 0 8px;
    color:#c4d2ee;
    font-size:14px;
}
input,select{
    width:100%;
    padding:15px;
    border-radius:14px;
    border:1px solid rgba(255,255,255,.12);
    background:#08111f;
    color:#fff;
    outline:none;
}
input:focus,select:focus{
    border-color:#00aaff;
}
.row{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:14px;
}
button{
    width:100%;
    margin-top:24px;
    padding:16px;
    border:0;
    border-radius:16px;
    background:linear-gradient(135deg,#ff7a00,#00aaff);
    color:#fff;
    font-size:15px;
    font-weight:bold;
    cursor:pointer;
}
button:hover{opacity:.92}
.alert{
    padding:16px;
    border-radius:16px;
    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;
}
.license-box{
    background:#050b15;
    border:1px dashed rgba(0,170,255,.45);
    border-radius:18px;
    padding:18px;
    margin-top:14px;
}
.license-box strong{
    display:block;
    font-size:22px;
    color:#00d4ff;
    margin-top:6px;
    word-break:break-all;
}
.info{
    margin-top:14px;
    color:#b8c7e6;
    line-height:1.6;
    font-size:14px;
}
.table{
    width:100%;
    border-collapse:collapse;
    overflow:hidden;
}
.table th,.table td{
    padding:13px;
    border-bottom:1px solid rgba(255,255,255,.07);
    text-align:left;
    font-size:14px;
}
.table th{
    color:#7f95bd;
    font-weight:normal;
}
.badge{
    display:inline-block;
    padding:6px 10px;
    border-radius:999px;
    font-size:12px;
    background:rgba(0,255,160,.12);
    color:#9fffc8;
}
.small{
    color:#7f95bd;
    font-size:13px;
}
@media(max-width:950px){
    .sidebar{position:relative;width:100%;height:auto}
    .main{margin-left:0;padding:20px}
    .grid{grid-template-columns:1fr}
    .row{grid-template-columns:1fr}
}
</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 class="active" href="gerar_licenca.php">Gerar Licença</a>
    <a href="computadores.php">Computadores</a>
    <a href="logout.php">Sair</a>
</div>

<div class="main">
    <div class="header">
        <div>
            <h1>Gerar nova licença</h1>
            <p>Cadastre o cliente, defina o plano e gere a chave de ativação.</p>
        </div>
    </div>

    <div class="grid">
        <div class="card">
            <h2>Dados da licença</h2>

            <?php if ($erro): ?>
                <div class="alert error"><?= htmlspecialchars($erro); ?></div>
            <?php endif; ?>

            <?php if ($mensagem): ?>
                <div class="alert success"><?= htmlspecialchars($mensagem); ?></div>

                <div class="license-box">
                    Licença criada:
                    <strong><?= htmlspecialchars($licencaGerada); ?></strong>
                </div>

                <div class="info">
                    <b>Acesso do cliente:</b><br>
                    E-mail: <?= htmlspecialchars($emailCliente); ?><br>
                    <?php if (!empty($senhaTemporaria)): ?>
                        Senha inicial: <b><?= htmlspecialchars($senhaTemporaria); ?></b><br>
                    <?php else: ?>
                        Cliente já existente. A senha dele foi mantida.<br>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <form method="POST">
                <label>Nome do cliente</label>
                <input type="text" name="nome" placeholder="Ex: João Silva" required>

                <label>E-mail do cliente</label>
                <input type="email" name="email" placeholder="cliente@email.com" required>

                <label>WhatsApp</label>
                <input type="text" name="whatsapp" placeholder="(81) 99999-9999">

                <div class="row">
                    <div>
                        <label>Tipo da licença</label>
                        <select name="tipo">
                            <option value="teste">Teste - 7 dias</option>
                            <option value="mensal" selected>Mensal - 30 dias</option>
                            <option value="anual">Anual - 365 dias</option>
                            <option value="vitalicia">Vitalícia</option>
                        </select>
                    </div>

                    <div>
                        <label>Valor</label>
                        <input type="text" name="valor" placeholder="Ex: 49.90">
                    </div>
                </div>

                <label>Quantidade de computadores permitidos</label>
                <select name="limite_maquinas">
                    <option value="1">1 computador</option>
                    <option value="2">2 computadores</option>
                    <option value="3">3 computadores</option>
                    <option value="5">5 computadores</option>
                    <option value="10">10 computadores</option>
                    <option value="0">Ilimitado</option>
                </select>

                <button type="submit">Gerar licença agora</button>
            </form>
        </div>

        <div class="card">
            <h2>Últimos clientes</h2>

            <table class="table">
                <thead>
                    <tr>
                        <th>Cliente</th>
                        <th>Licenças</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($clientes)): ?>
                    <tr>
                        <td colspan="3" class="small">Nenhum cliente cadastrado.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($clientes as $c): ?>
                        <tr>
                            <td>
                                <?= htmlspecialchars($c['nome']); ?><br>
                                <span class="small"><?= htmlspecialchars($c['email']); ?></span>
                            </td>
                            <td><?= (int)$c['total_licencas']; ?></td>
                            <td><span class="badge"><?= htmlspecialchars($c['status']); ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>

            <div class="info">
                Aqui você já acompanha os clientes cadastrados e quantas licenças cada um possui.
            </div>
        </div>
    </div>
</div>

</body>
</html>