<?php
session_start();
require_once dirname(__DIR__) . '/includes/whatsapp_helper.php';
require_once dirname(__DIR__) . '/api/_auth_common.php';

$dbPath = dirname(__DIR__) . "/api/db.db";

try {
    $db = new PDO("sqlite:" . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    header("Location: users.php");
    exit;
}

function colunaExiste(PDO $db, $tabela, $coluna) {
    $res = $db->query("PRAGMA table_info($tabela)");
    while ($c = $res->fetch(PDO::FETCH_ASSOC)) {
        if ($c["name"] === $coluna) return true;
    }
    return false;
}

if (!colunaExiste($db, "usuarios", "nome_cliente")) {
    $db->exec("ALTER TABLE usuarios ADD COLUMN nome_cliente TEXT");
}

if (!colunaExiste($db, "usuarios", "whatsapp")) {
    $db->exec("ALTER TABLE usuarios ADD COLUMN whatsapp TEXT");
}

wa_ensure_schema($db);
auth_ensure_schema($db);

$activationCode = '';

if(isset($_POST["submit"])){

    $mac = strtoupper(trim($_POST["mac"]));
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);
    $dns = trim($_POST["dns"]);
    $status = trim($_POST["status"]);
    $vencimentoData = trim($_POST["vencimento"]);
    $nomeCliente = trim($_POST["nome_cliente"]);
    $whatsapp = trim($_POST["whatsapp"]);
    $tipoRegistro = trim((string)($_POST["tipo_registro"] ?? "cliente"));
    $isTeste = ($tipoRegistro === "teste");
    $loginMode = trim((string)($_POST['login_mode'] ?? 'normal'));

    if (!in_array($loginMode, ['normal', 'activation_code'], true)) {
        $loginMode = 'normal';
    }

    $activationCode = $loginMode === 'activation_code' ? auth_generate_activation_code($db) : '';

    if($mac && $username && $password && $dns){

        $check = $db->prepare("SELECT mac FROM usuarios WHERE mac = ?");
        $check->execute([$mac]);

        if($check->fetch()){
            echo "<script>alert('MAC já cadastrado');</script>";
        } else {

            $vencimento = 0;
            if($vencimentoData){
                $vencimento = strtotime($vencimentoData . " 23:59:59");
            }

            $agoraWhatsapp = time();

            $st = $db->prepare("
                INSERT INTO usuarios 
                (mac, dns, username, password, status, vencimento, nome_cliente, whatsapp, teste, teste_criado_at, whatsapp_trial_started_at, whatsapp_activated_at, whatsapp_account_created_at, login_mode, activation_code)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $st->execute([
                $mac,
                $dns,
                $username,
                $password,
                $status ?: "ativo",
                $vencimento,
                $nomeCliente,
                $whatsapp,
                $isTeste ? 1 : null,
                $isTeste ? $agoraWhatsapp : 0,
                $isTeste ? $agoraWhatsapp : 0,
                $isTeste ? 0 : $agoraWhatsapp,
                $agoraWhatsapp,
                $loginMode,
                $activationCode
            ]);

            $createdUser = [
                'mac' => $mac,
                'dns' => $dns,
                'username' => $username,
                'password' => $password,
                'status' => $status ?: 'ativo',
                'vencimento' => $vencimento,
                'nome_cliente' => $nomeCliente,
                'whatsapp' => $whatsapp,
                'teste' => $isTeste ? 1 : null,
                'usuario_id' => 0,
                'login_mode' => $loginMode,
                'activation_code' => $activationCode,
            ];

            if ($isTeste) {
                wa_send_template_to_user($db, $createdUser, 'teste_criado');
            }

            header("Location: users.php?r=adicionado");
            exit;
        }
    }
}

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;
}
.save-btn{
    border-radius:14px;
    min-height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.back-btn{
    border-radius:14px;
    min-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;
}
.alert{
    border-radius:14px;
}
.form-actions{
    display:flex;
    align-items:center;
    justify-content:flex-end;
    gap:10px;
    flex-wrap:wrap;
    margin-top:4px;
}
@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,
    .back-btn{
        width:100%;
    }
    .form-actions{
        display:block;
    }
    .form-actions .btn{
        margin-top:8px;
    }
}
</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-person-plus-fill"></i></div>
                <div>
                    <h5>Novo Usuário</h5>
                    <span>Cadastre MAC, DNS, usuário, senha, WhatsApp e vencimento do cliente</span>
                </div>
            </div>

            <div class="dns-actions">
                <span class="badge-soft"><i class="bi bi-shield-check"></i> Cadastro</span>
            </div>
        </div>

        <div class="card-body">
            <?php if (!empty($activationCode)): ?>
                <div class="alert alert-info d-flex align-items-center gap-2">
                    <i class="bi bi-key-fill"></i>
                    <div>Código de ativação gerado: <strong><?= htmlspecialchars($activationCode, ENT_QUOTES, 'UTF-8') ?></strong></div>
                </div>
            <?php endif; ?>

            <form method="post" class="row g-3">
                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">MAC</label>
                    <input class="form-control input-radius" name="mac" placeholder="00:11:22:33:44:55" maxlength="17" required>
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">Usuário</label>
                    <input class="form-control input-radius" name="username" required>
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">Senha</label>
                    <input class="form-control input-radius" name="password" required>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">DNS</label>
                    <input class="form-control input-radius" name="dns" placeholder="http://servidor:porta" required>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">Nome do Cliente</label>
                    <input class="form-control input-radius" name="nome_cliente">
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">WhatsApp</label>
                    <input class="form-control input-radius" name="whatsapp" placeholder="5511999999999">
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">Login do App</label>
                    <select name="login_mode" class="form-select input-radius" id="login_mode_select">
                        <option value="normal">Login normal</option>
                        <option value="activation_code">Código de ativação</option>
                    </select>
                </div>

                <div class="col-lg-4 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">Status</label>
                    <select name="status" class="form-select input-radius">
                        <option value="ativo">Ativo</option>
                        <option value="inativo">Inativo</option>
                    </select>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">Tipo</label>
                    <select name="tipo_registro" class="form-select input-radius">
                        <option value="cliente">Cliente</option>
                        <option value="teste">Teste</option>
                    </select>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label" style="font-weight:900;">Vencimento</label>
                    <input type="date" name="vencimento" class="form-control input-radius">
                </div>

                <div class="col-12">
                    <div class="info-box">
                        <strong>Login por código:</strong>
                        ao escolher código de ativação, o painel gera automaticamente um código numérico de 4 dígitos.
                    </div>
                </div>

                <div class="col-12">
                    <div class="form-actions">
                        <a href="users.php" class="btn btn-secondary back-btn">
                            <i class="bi bi-arrow-left"></i> Voltar
                        </a>

                        <button class="btn btn-success save-btn" name="submit">
                            <i class="bi bi-save2"></i> Salvar usuário
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.querySelector("[name='mac']").addEventListener("keyup",function(){
    let v=this.value.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();
    let o="";
    for(let i=0;i<v.length;i++){
        if(i>0&&i%2==0)o+=":";
        o+=v[i];
    }
    this.value=o;
});
</script>

<?php include "./includes/footer.php"; ?>