<?php
require_once 'conexao.php';

$msg = "";
$msg_tipo = "";

// --- PROCESSAMENTO DO FORMULÁRIO ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Recebe dados
        $nome = trim($_POST['nome']);
        $usuario = trim($_POST['usuario']);
        $senha = trim($_POST['senha']);
        $email = trim($_POST['email']);
        $celular = trim($_POST['celular']);
        $conexao = (int)$_POST['conexao'];
        $vencimento = $_POST['vencimento'];
        $notas = $_POST['obs'];

        // Verifica se usuário já existe
        $check = $connUser->prepare("SELECT id FROM usuario WHERE usuario = ?");
        $check->execute([$usuario]);
        
        if ($check->rowCount() > 0) {
            $msg = "Erro: Este usuário já existe!";
            $msg_tipo = "warning";
        } else {
            // Insere no Banco
            $sql = "INSERT INTO usuario (
                CadUser, nome, usuario, senha, email, celular, 
                conexao, data_premio, obs, bloqueado, data_cadastro
            ) VALUES (
                :cad, :nome, :user, :pass, :email, :cel, 
                :con, :venc, :obs, 'nao', NOW()
            )";
            
            $stmt = $connUser->prepare($sql);
            $stmt->execute([
                ':cad' => 'Admin', 
                ':nome' => $nome,
                ':user' => $usuario,
                ':pass' => $senha,
                ':email' => $email,
                ':cel' => $celular,
                ':con' => $conexao,
                ':venc' => $vencimento,
                ':obs' => $notas
            ]);

            $msg = "Cliente <b>$nome</b> criado com sucesso!";
            $msg_tipo = "success";
        }

    } catch (PDOException $e) {
        $msg = "Erro no banco: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Novo Cliente | Painel</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        :root { --sidebar-width: 260px; --bg-body: #151521; --bg-card: #1e1e2d; --text-main: #e0e0e0; --primary: #7367f0; }
        body { background: var(--bg-body); color: var(--text-main); font-family: 'Segoe UI', sans-serif; padding-bottom: 60px; }
        
        /* MENU LATERAL */
        .sidebar { width: 260px; height: 100vh; position: fixed; top: 0; left: 0; background: #1e1e2d; padding: 20px; z-index: 1000; transition: 0.3s; border-right: 1px solid #333; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .card-custom { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.2); }
        
        /* CORREÇÃO DOS CAMPOS DE TEXTO (PARA VER O QUE ESCREVE) */
        .form-control, .form-select { 
            background: #2b2b40 !important; 
            border: 1px solid #444 !important; 
            color: #ffffff !important; 
            height: 45px; 
        }
        .form-control:focus, .form-select:focus { 
            background: #32324a !important; 
            border-color: var(--primary) !important; 
            color: #ffffff !important; 
            box-shadow: none; 
        }
        textarea.form-control { height: auto; }
        .form-label { color: #aaa; font-size: 0.9rem; margin-bottom: 5px; }
        
        /* BOTÕES */
        .btn-primary-custom { background: var(--primary); border: none; padding: 12px; font-weight: 600; width: 100%; border-radius: 8px; color: white; }
        .btn-primary-custom:hover { background: #5e50ee; color: white; }
        .nav-link { color: #a6a6b7; padding: 12px; border-radius: 8px; margin-bottom: 5px; display: flex; align-items: center; gap: 10px; text-decoration: none; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }

        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 15px; }
            .mobile-toggle { display: block !important; }
        }
        .mobile-toggle { display: none; font-size: 1.5rem; color: #fff; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold"><i class="fas fa-tv text-primary"></i> Painel v3.0</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="criar_cliente.php" class="nav-link active"><i class="fas fa-user-plus"></i> Novo Cliente</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div><h3 class="fw-bold">Novo Cliente</h3><p class="text-muted">Preencha os dados abaixo.</p></div>
        <a href="clientes.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-2"></i>Voltar</a>
    </div>

    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show">
            <?= $msg ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card card-custom">
                <div class="card-body p-4">
                    <form method="POST">
                        
                        <h6 class="text-primary mb-3"><i class="fas fa-lock me-2"></i>Dados de Acesso</h6>
                        <div class="row g-3 mb-4">
                            <div class="col-md-6">
                                <label class="form-label">Usuário (Login)</label>
                                <input type="text" name="usuario" class="form-control" required placeholder="ex: cliente123">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Senha</label>
                                <div class="input-group">
                                    <input type="text" name="senha" id="input_senha" class="form-control" required value="<?= substr(str_shuffle('1234567890abcdef'),0,6) ?>">
                                    <button type="button" class="btn btn-outline-secondary" onclick="gerarSenha()"><i class="fas fa-random"></i></button>
                                </div>
                            </div>
                        </div>

                        <h6 class="text-primary mb-3"><i class="fas fa-calendar-alt me-2"></i>Plano & Vencimento</h6>
                        <div class="row g-3 mb-4">
                            <div class="col-md-6">
                                <label class="form-label">Data de Vencimento</label>
                                <input type="date" name="vencimento" class="form-control" required value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Conexões (Telas)</label>
                                <select name="conexao" class="form-select">
                                    <option value="1">1 Tela</option>
                                    <option value="2">2 Telas</option>
                                    <option value="3">3 Telas</option>
                                    <option value="4">4 Telas</option>
                                </select>
                            </div>
                        </div>

                        <hr class="border-secondary my-4">

                        <h6 class="text-muted mb-3 small text-uppercase">Informações Opcionais</h6>
                        <div class="row g-3 mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Nome Completo</label>
                                <input type="text" name="nome" class="form-control" placeholder="Nome do cliente">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Whatsapp</label>
                                <input type="tel" name="celular" class="form-control" placeholder="(00) 00000-0000">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" class="form-control">
                            </div>
                            <div class="col-12">
                                <label class="form-label">Observações</label>
                                <textarea name="obs" class="form-control" rows="2" placeholder="Anotações internas..."></textarea>
                            </div>
                        </div>

                        <div class="mt-4">
                            <button type="submit" class="btn btn-primary-custom">
                                <i class="fas fa-check-circle me-2"></i> Criar Cliente
                            </button>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>

</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() {
        document.getElementById('sidebar').classList.toggle('show');
        document.getElementById('overlay').classList.toggle('show');
    }

    function gerarSenha() {
        const chars = '0123456789abcdefghijklmnopqrstuvwxyz';
        let pass = '';
        for (let i = 0; i < 6; i++) {
            pass += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        document.getElementById('input_senha').value = pass;
    }
</script>

</body>
</html>
