<?php
session_start();

// Verificar si el usuario ha iniciado sesión
if (!isset($_SESSION['user_email'])) {
    header("Location: index.php");
    exit();
}

// --- FUNCIÓN DE TELEGRAM ---
function notifyTelegram($mensaje) {
    $token = "8332763033:AAHB9zbuJP2K5qbz2s4o5xMbZd56ReNP3y8"; // REEMPLAZAR
    $chat_id = "326717436"; // REEMPLAZAR
    $url = "https://api.telegram.org/bot$token/sendMessage?chat_id=$chat_id&parse_mode=html&text=" . urlencode($mensaje);
    @file_get_contents($url);
}

// Función para generar email aleatorio y verificar que no exista en la DB
function generarEmailUnico($conn) {
    $letras = 'abcdefghijklmnopqrstuvwxyz';
    $intentos = 0;
    $maxIntentos = 100; 
    
    do {
        $usuario = '';
        for ($i = 0; $i < 8; $i++) {
            $usuario .= $letras[rand(0, strlen($letras) - 1)];
        }
        $email = $usuario . '@yae.tv';
        $stmt = $conn->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
        $stmt->bindParam(':email', $email);
        $stmt->execute();
        $count = $stmt->fetchColumn();
        $intentos++;
        if ($count == 0 || $intentos >= $maxIntentos) {
            break;
        }
    } while (true);
    
    return $email;
}

function generarPassword($longitud = 6) {
    $numeros = '0123456789';
    $password = '';
    for ($i = 0; $i < $longitud; $i++) {
        $password .= $numeros[rand(0, strlen($numeros) - 1)];
    }
    return $password;
}

try {
    include 'db.php';
    $conn = $pdo;
    $emailGenerado = generarEmailUnico($conn);
    $passwordGenerada = generarPassword();
} catch(PDOException $e) {
    $emailGenerado = "error@yae.tv";
    $passwordGenerada = "123456";
    $errorConexion = $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agregar Usuario</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.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles/add_reseller.css">
    <script>
        function copiarDatosVisibles() {
            const datosUsuario = document.getElementById('datosUsuario');
            const elementoTemporal = document.createElement("textarea");
            elementoTemporal.value = datosUsuario.innerText;
            elementoTemporal.setAttribute('readonly', '');
            elementoTemporal.style.position = 'absolute';
            elementoTemporal.style.left = '-9999px';
            document.body.appendChild(elementoTemporal);
            elementoTemporal.select();
            elementoTemporal.setSelectionRange(0, 99999);
            try {
                document.execCommand('copy');
                alert('Datos copiados al portapapeles');
            } catch (err) {
                alert('No se pudo copiar manualmente.');
            }
            document.body.removeChild(elementoTemporal);
        }
    </script>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-6 col-md-8 col-sm-10">
                <div class="form-container">
                    <h2 class="form-title">Agregar Nuevo Usuario</h2>
                    <?php 
                    if (isset($errorConexion)) {
                        echo '<div class="alert alert-danger" role="alert">Error de conexión: ' . $errorConexion . '</div>';
                    }
                    
                    $pause = 0;
                    try {
                        $stmt = $conn->prepare("SELECT pause, creditos FROM resellers WHERE email = :email");
                        $stmt->bindParam(':email', $_SESSION['user_email']);
                        $stmt->execute();
                        $result = $stmt->fetch(PDO::FETCH_ASSOC);
                        if ($result) { $pause = $result['pause']; }
                    } catch(PDOException $e) {
                        echo '<div class="alert alert-danger" role="alert">Error: ' . $e->getMessage() . '</div>';
                    }

                    if ($pause == 1) {
                        echo '<div class="alert alert-warning" role="alert">CUENTA PAUSADA</div>';
                    } else {
                        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                            $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
                            $phone = htmlspecialchars($_POST['phone'], ENT_QUOTES, 'UTF-8'); 
                            $password = $_POST['password']; 
                            $meses = intval($_POST['meses']);
                            
                            if (empty($email)) { $email = generarEmailUnico($conn); }
                            if (empty($password)) { $password = generarPassword(); }

                            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                                echo '<div class="alert alert-danger" role="alert">Error: Email no válido.</div>';
                            } elseif ($meses < 1 || $meses > 12) {
                                echo '<div class="alert alert-danger" role="alert">Error: Número de meses no válido.</div>';
                            } else {
                                if ($result['creditos'] >= $meses) {
                                    $stmt = $conn->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
                                    $stmt->bindParam(':email', $email);
                                    $stmt->execute();
                                    if ($stmt->fetchColumn() > 0) {
                                        echo '<div class="alert alert-danger" role="alert">Error: El email ya existe.</div>';
                                    } else {
                                        $now = new DateTime("now", new DateTimeZone("America/Argentina/Buenos_Aires"));
                                        $vencimiento = $now->modify("+$meses months")->format('Y-m-d H:i:s');

                                        // INSERTAR USUARIO
                                        $stmt = $conn->prepare("INSERT INTO users (email, phone, password, vencimiento, idv, demo) VALUES (:email, :phone, :password, :vencimiento, :idv, 'false')");
                                        $stmt->execute([':email' => $email, ':phone' => $phone, ':password' => $password, ':vencimiento' => $vencimiento, ':idv' => $_SESSION['user_email']]);

                                        // ACTUALIZAR CRÉDITOS
                                        $stmt = $conn->prepare("UPDATE resellers SET creditos = creditos - :meses WHERE email = :email");
                                        $stmt->execute([':meses' => $meses, ':email' => $_SESSION['user_email']]);

                                        // --- NOTIFICACIÓN TELEGRAM ---
                                        $vendedor = $_SESSION['user_email'];
                                        $saldo_final = $result['creditos'] - $meses;
                                        
                                        $tg_msg = "🆕 <b>NUEVA CUENTA CREADA</b>\n";
                                        $tg_msg .= "👤 Vendedor: <code>$vendedor</code>\n";
                                        $tg_msg .= "📧 Cliente: <code>$email</code>\n";
                                        $tg_msg .= "📉 Cantidad: <b>$meses mes(es)</b>\n";
                                        $tg_msg .= "🏦 Créditos restante: <b>$saldo_final</b>";
                                        
                                        notifyTelegram($tg_msg);
                                        // --- FIN NOTIFICACIÓN ---

                                        echo '<div class="alert alert-success" role="alert"><strong>Usuario creado con éxito</strong></div>
                                        <div class="user-data-container p-3 border rounded bg-light mb-3">
                                            <div id="datosUsuario">
                                                <p><strong>Email:</strong> ' . $email . '</p>
                                                <p><strong>Contraseña:</strong> ' . $password . '</p>
                                                <p><strong>Vencimiento:</strong> ' . $vencimiento . '</p>
                                                <p><strong>CÓDIGO DOWNLOADER:</strong> 1014739</p>
                                            </div>
                                            <button class="btn btn-primary mt-2" onclick="copiarDatosVisibles()"><i class="fas fa-copy"></i> Copiar datos</button>
                                        </div>';
                                    }
                                } else {
                                    echo '<div class="alert alert-danger" role="alert">Error: Créditos insuficientes.</div>';
                                }
                            }
                        } else {
                            ?>
                            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                                <div class="mb-3">
                                    <label class="form-label">Email:</label>
                                    <div class="input-group">
                                        <input type="email" class="form-control" id="email" name="email" placeholder="Vacío para aleatorio">
                                        <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('email').value='<?php echo $emailGenerado; ?>'">Generar</button>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Contraseña:</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="password" name="password">
                                        <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('password').value='<?php echo $passwordGenerada; ?>'">Generar</button>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Teléfono:</label>
                                        <input type="text" class="form-control" id="phone" name="phone" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Meses:</label>
                                        <select name="meses" class="form-select">
                                            <?php for ($i = 1; $i <= 12; $i++) : ?>
                                                <option value="<?php echo $i; ?>"><?php echo $i; ?> mes(es)</option>
                                            <?php endfor; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="mb-3 text-center">
                                    <button type="submit" class="btn btn-success btn-lg">Agregar Usuario</button>
                                </div>
                            </form>
                            <?php
                        }
                    }
                    ?>
                    <div class="mt-3 text-center">
                        <a href="opciones.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Volver</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>