<?php 
session_start();
if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

include 'auth.php';

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

$db = new SQLite3("./api/.anspanel.db");
$db->busyTimeout(5000);

$error_message = '';

if (isset($_POST["submit"])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php");
        exit();
    }

    $name = $_POST['name'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    $mac_amount = $_POST['mac_amount'];

    $checkStmt = $db->prepare("SELECT COUNT(*) as count FROM USERS WHERE NAME = :name");
    $checkStmt->bindValue(':name', $name, SQLITE3_TEXT);
    $checkResult = $checkStmt->execute();
    $row = $checkResult->fetchArray();

    if ($row['count'] > 0) {
        $error_message = "O Nome do revendedor já existe!";
    } else {
        $stmt = $db->prepare("INSERT INTO USERS (NAME, USERNAME, PASSWORD, mac_amount, store_type) VALUES (:name, :username, :password, :mac_amount, 1)");
        $stmt->bindValue(':name', $name, SQLITE3_TEXT);
        $stmt->bindValue(':username', $username, SQLITE3_TEXT);
        $stmt->bindValue(':password', $password, SQLITE3_TEXT);
        $stmt->bindValue(':mac_amount', $mac_amount, SQLITE3_INTEGER);

        if ($stmt->execute()) {
            header("Location: stores.php?status=created");
            exit();
        } else {
            $error_message = "Erro ao criar: " . $db->lastErrorMsg();
        }
    }
}

include "includes/header.php";
?>

<style>
    /* RESET E SEGURANÇA DE LARGURA */
    * { box-sizing: border-box; }

    /* FUNDO TOTAL DARK */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
        overflow-x: hidden;
    }

    /* OCULTAR ELEMENTOS DO HEADER ORIGINAL */
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }

    .container-fluid { padding: 15px !important; }

    /* BOTÃO VOLTAR */
    .btn-back-nav {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        text-decoration: none !important;
        font-size: 0.85rem;
        font-weight: 600;
        margin-bottom: 20px;
        max-width: 600px;
        margin-left: auto;
        margin-right: auto;
    }

    /* CARD PREMIUM CENTRALIZADO */
    .premium-card {
        background: #070e1b !important;
        border: 1px solid #1e293b !important;
        border-radius: 20px;
        padding: 25px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        max-width: 600px; /* Centraliza e limita a largura no desktop */
        margin: 0 auto 40px auto;
        width: 100%;
    }

    .card-header-premium { 
        margin-bottom: 25px; 
        border-bottom: 1px solid rgba(255,255,255,0.05); 
        padding-bottom: 15px; 
    }
    .card-header-premium h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    .card-header-premium p { color: #10b981; font-size: 0.8rem; margin-top: 4px; font-weight: 600; }

    /* ESTILO FORMULÁRIO */
    label { 
        display: block; color: #10b981; font-size: 0.7rem; font-weight: 800; 
        margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;
    }

    .form-input { 
        width: 100%; 
        background: #0f172a !important; 
        border: 1px solid #1e293b !important; 
        color: #fff !important; 
        padding: 15px; 
        border-radius: 12px; 
        font-size: 0.95rem; 
        margin-bottom: 20px; 
        transition: 0.3s;
        display: block;
    }
    .form-input:focus { border-color: #10b981 !important; outline: none; box-shadow: 0 0 10px rgba(16, 185, 129, 0.1); }

    /* CONTAINER SENHA */
    .password-wrapper { position: relative; width: 100%; }
    .toggle-pass {
        position: absolute; right: 15px; top: 18px; color: #475569;
        cursor: pointer; z-index: 10; font-size: 1.1rem;
    }

    /* BOTÕES AJUSTADOS E CENTRALIZADOS */
    .row-buttons { 
        display: grid; 
        grid-template-columns: 1fr; 
        gap: 12px; 
        margin-top: 10px;
        width: 100%;
    }
    
    .btn-premium-save {
        background: #10b981 !important; color: #fff !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px;
        box-shadow: 0 4px 15px rgba(16, 185, 129, 0.2); transition: 0.3s;
        width: 100%;
    }
    
    .btn-premium-cancel {
        background: #1e293b !important; color: #94a3b8 !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        text-align: center; text-decoration: none !important;
        width: 100%;
    }

    @media (min-width: 768px) {
        .row-buttons { grid-template-columns: 2fr 1fr; }
        .btn-back-nav { display: flex; }
    }
</style>

<div class="container-fluid">
    <div style="max-width: 600px; margin: 0 auto;">
        <a href="stores.php" class="btn-back-nav">
            <i class="fas fa-chevron-left"></i> Voltar para Lista
        </a>
    </div>

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Nova Revenda</h1>
            <p><i class="fas fa-plus-circle mr-1"></i> Cadastrar novo parceiro no painel</p>
        </div>

        <form method="post">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>">
            
            <label>Nome do Revendedor / Loja</label>
            <input type="text" class="form-input" name="name" placeholder="Ex: Master Revenda Gold" required>

            <label>Limite de Usuários (MACs)</label>
            <input type="number" class="form-input" name="mac_amount" min="1" value="1000" required>

            <label>Usuário (Login)</label>
            <input type="text" class="form-input" name="username" placeholder="Defina o login de acesso" required>

            <label>Senha de Acesso</label>
            <div class="password-wrapper">
                <input type="password" class="form-input" name="password" id="password" placeholder="Defina uma senha forte" required>
                <i class="fas fa-eye toggle-pass" id="eyeIcon"></i>
            </div>

            <div class="row-buttons">
                <button type="submit" name="submit" class="btn-premium-save">
                    <i class="fas fa-check-circle"></i> Criar Revendedor
                </button>
                <a href="stores.php" class="btn-premium-cancel">Cancelar</a>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    document.getElementById('eyeIcon').addEventListener('click', function () {
        const passwordInput = document.getElementById('password');
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        this.classList.toggle('fa-eye');
        this.classList.toggle('fa-eye-slash');
        this.style.color = (type === 'text') ? '#10b981' : '#475569';
    });

    <?php if ($error_message): ?>
    Swal.fire({
        icon: 'error',
        title: 'Erro no Cadastro',
        text: '<?= $error_message ?>',
        background: '#070e1b',
        color: '#fff',
        confirmButtonColor: '#ef4444'
    });
    <?php endif; ?>
</script>

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