<?php
session_start();

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

// Conexión centralizada
include 'db.php';

// --- 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);
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Obtener los datos del formulario
        $id = intval($_POST['id']);
        $nombre = htmlspecialchars($_POST['nombre'], ENT_QUOTES, 'UTF-8');
        $telefono = htmlspecialchars($_POST['telefono'], ENT_QUOTES, 'UTF-8');
        $creditos_a_agregar = intval($_POST['creditos']);
        $new_email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
        $new_password = htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8');
        $user_email = $_SESSION['user_email'];

        // Iniciar transacción
        $pdo->beginTransaction();

        // Verificar créditos del usuario logueado (Emisor)
        $stmt = $pdo->prepare("SELECT creditos FROM resellers WHERE email = :user_email");
        $stmt->execute(['user_email' => $user_email]);
        $result = $stmt->fetch();

        if ($result && $result['creditos'] >= $creditos_a_agregar) {
            // Restar créditos del usuario logueado
            $stmt = $pdo->prepare("UPDATE resellers SET creditos = creditos - :creditos WHERE email = :user_email");
            $stmt->execute([
                'creditos' => $creditos_a_agregar,
                'user_email' => $user_email,
            ]);

            // Actualizar el reseller (Receptor)
            $stmt = $pdo->prepare("UPDATE resellers SET nombre = :nombre, telefono = :telefono, email = :email, password = :password, creditos = creditos + :creditos WHERE id = :id");
            $stmt->execute([
                'nombre' => $nombre,
                'telefono' => $telefono,
                'email' => $new_email,
                'password' => $new_password,
                'creditos' => $creditos_a_agregar,
                'id' => $id,
            ]);

            // --- NOTIFICACIÓN TELEGRAM ---
            // Solo notificamos si realmente se agregaron créditos (evitar spam si solo editan nombre)
            if ($creditos_a_agregar > 0) {
                $saldo_restante_master = $result['creditos'] - $creditos_a_agregar;
                
                $tg_msg = "🔌 <b>CARGA DE CRÉDITOS (RESELLER)</b>\n";
                $tg_msg .= "📤 De (Master): <code>$user_email</code>\n";
                $tg_msg .= "📥 Para (Reseller): <code>$new_email</code>\n";
                $tg_msg .= "💎 Cantidad: <b>$creditos_a_agregar créditos</b>\n";
                $tg_msg .= "💰 Saldo Master: <b>$saldo_restante_master</b>";
                
                notifyTelegram($tg_msg);
            }
            // --- FIN NOTIFICACIÓN ---

            // Confirmar transacción
            $pdo->commit();

            $_SESSION['message'] = "Revendedor actualizado con éxito.";
            header("Location: editar_reseller.php?id=$id");
            exit();
        } else {
            $pdo->rollBack();
            echo "<div class='alert alert-danger'>Error: No tienes suficientes créditos.</div>";
        }
    } else {
        $reseller = null;
        if (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $stmt = $pdo->prepare("SELECT * FROM resellers WHERE id = :id");
            $stmt->execute(['id' => $id]);
            $reseller = $stmt->fetch();
        }
    }
} catch (\PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo "Error de base de datos: " . $e->getMessage();
} catch (\Exception $e) {
    echo "Error general: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editar Reseller</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles/add_reseller.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card p-4 shadow">
                    <h2 class="text-center mb-4">Editar / Cargar Reseller</h2>
                    <?php
                    if (isset($_SESSION['message'])) {
                        echo "<div class='alert alert-success'>" . $_SESSION['message'] . "</div>";
                        unset($_SESSION['message']);
                    }
                    ?>
                    <?php if ($reseller): ?>
                        <form method="post" action="editar_reseller.php">
                            <input type="hidden" name="id" value="<?php echo $reseller['id']; ?>">
                            <div class="mb-3">
                                <label class="form-label">Nombre:</label>
                                <input type="text" class="form-control" name="nombre" value="<?php echo htmlspecialchars($reseller['nombre']); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Teléfono:</label>
                                <input type="text" class="form-control" name="telefono" value="<?php echo htmlspecialchars($reseller['telefono']); ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email:</label>
                                <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($reseller['email']); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Contraseña:</label>
                                <input type="text" class="form-control" name="password" value="<?php echo htmlspecialchars($reseller['password']); ?>" required>
                            </div>
                            <div class="alert alert-warning">
                                <label class="form-label"><strong>Agregar Créditos:</strong></label>
                                <input type="number" class="form-control" name="creditos" value="0" min="0" required>
                                <small>Los créditos se restarán de tu balance actual.</small>
                            </div>
                            <div class="text-center">
                                <input type="submit" class="btn btn-success btn-lg" value="Actualizar y Cargar">
                            </div>
                        </form>
                    <?php endif; ?>
                    <div class="mt-3 text-center">
                        <a href="listar_resellers.php" class="btn btn-outline-secondary">Volver</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
