<?php
session_start();

if (!isset($_SESSION['user_email'])) {
    header("Location: index.php");
    exit();
}

include 'db.php';

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

try {
    $conn = $pdo;

    $message = '';

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Verificación del CSRF
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            die("CSRF token validation failed");
        }

        if (isset($_POST['action'])) {
            $user_id = $_POST['user_id'];

            // Verifica si el usuario tiene permiso para editar/eliminar
            $stmt = $conn->prepare("SELECT * FROM users WHERE id = :id AND idv = :idv");
            $stmt->bindParam(':id', $user_id);
            $stmt->bindParam(':idv', $_SESSION['user_email']);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                if ($_POST['action'] === 'edit') {
                    $new_email = filter_var($_POST['new_email'], FILTER_SANITIZE_EMAIL);
                    $new_password = $_POST['new_password'];
                    $new_phone = htmlspecialchars($_POST['new_phone'], ENT_QUOTES, 'UTF-8');

                    $stmt = $conn->prepare("UPDATE users SET email = :email, phone = :phone, password = :password WHERE id = :id AND idv = :idv");
                    $stmt->bindParam(':email', $new_email);
                    $stmt->bindParam(':phone', $new_phone);
                    $stmt->bindParam(':password', $new_password);
                    $stmt->bindParam(':id', $user_id);
                    $stmt->bindParam(':idv', $_SESSION['user_email']);
                    $stmt->execute();

                    $message = "Usuario actualizado con éxito.";
                    notifyTelegram("📝 <b>Usuario Editado</b>\n<b>Reseller:</b> {$_SESSION['user_email']}\n<b>Cliente:</b> $new_email");

                } elseif ($_POST['action'] === 'delete') {
                    $stmt = $conn->prepare("DELETE FROM users WHERE id = :id AND idv = :idv");
                    $stmt->bindParam(':id', $user_id);
                    $stmt->bindParam(':idv', $_SESSION['user_email']);
                    $stmt->execute();

                    $message = "Usuario eliminado con éxito.";
                    notifyTelegram("🗑 <b>Usuario Eliminado</b>\n<b>Reseller:</b> {$_SESSION['user_email']}\n<b>Cliente:</b> {$user['email']}");

                } elseif ($_POST['action'] === 'renew') {
                    $meses = intval($_POST['meses']);
                    $creditos = 0;

                    $stmt = $conn->prepare("SELECT creditos, pause FROM resellers WHERE email = :email");
                    $stmt->bindParam(':email', $_SESSION['user_email']);
                    $stmt->execute();
                    $reseller = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($reseller) {
                        $creditos = $reseller['creditos'];

                        if ($reseller['pause'] == 1) {
                            $message = "Aviso: No puedes renovar usuarios porque tu cuenta está en pausa.";
                        } else {
                            if ($creditos >= $meses) {
                                $stmt = $conn->prepare("SELECT vencimiento FROM users WHERE id = :id");
                                $stmt->bindParam(':id', $user_id);
                                $stmt->execute();
                                $user_data = $stmt->fetch(PDO::FETCH_ASSOC);

                                $zona = new DateTimeZone("America/Argentina/Buenos_Aires");
                                $fecha_actual = new DateTime("now", $zona);
                                $fecha_vencimiento = new DateTime($user_data['vencimiento'], $zona);

                                if ($fecha_vencimiento < $fecha_actual) {
                                    $nueva_fecha = clone $fecha_actual;
                                } else {
                                    $nueva_fecha = clone $fecha_vencimiento;
                                }

                                $nueva_fecha->modify("+$meses months");
                                $nuevo_vencimiento = $nueva_fecha->format('Y-m-d H:i:s');

                                $stmt = $conn->prepare("UPDATE users SET vencimiento = :vencimiento WHERE id = :id");
                                $stmt->bindParam(':vencimiento', $nuevo_vencimiento);
                                $stmt->bindParam(':id', $user_id);
                                $stmt->execute();

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

                                // --- CORRECCIÓN AQUÍ: CALCULO DE CRÉDITO RESTANTE ---
                                $creditos_restantes = $creditos - $meses;

                                $message = "Usuario renovado con éxito. Nueva fecha de vencimiento: $nuevo_vencimiento.";
                                notifyTelegram("💰 <b>Renovación Exitosa</b>\n<b>Reseller:</b> {$_SESSION['user_email']}\n<b>Cliente:</b> {$user['email']}\n<b>Meses:</b> $meses\n<b>Vence:</b> $nuevo_vencimiento\n<b>Créditos Restantes:</b> $creditos_restantes");
                            } else {
                                $message = "Error: No tienes suficientes créditos para renovar este usuario.";
                            }
                        }
                    } else {
                        $message = "Error: No se encontró información de revendedor.";
                    }
                } elseif ($_POST['action'] === 'delete_devices') {
                    $stmt = $conn->prepare("UPDATE users SET device_id = NULL, device_id_2 = NULL, device_id_3 = NULL, device_id_4 = NULL WHERE id = :id AND idv = :idv");
                    $stmt->bindParam(':id', $user_id);
                    $stmt->bindParam(':idv', $_SESSION['user_email']);
                    $stmt->execute();

                    $message = "Todos los Device IDs del usuario han sido eliminados con éxito.";
                    notifyTelegram("📱 <b>IDs Limpiados</b>\n<b>Reseller:</b> {$_SESSION['user_email']}\n<b>Cliente:</b> {$user['email']}");
                }
            } else {
                $message = "Error: No tienes permiso para editar este usuario.";
            }
        }

        header("Location: " . $_SERVER['PHP_SELF'] . "?message=" . urlencode($message));
        exit();
    }

    $search = isset($_GET['search']) ? $_GET['search'] : '';
    $stmt = $conn->prepare("SELECT * FROM users WHERE idv = :idv AND email LIKE :search");
    $stmt->bindParam(':idv', $_SESSION['user_email']);
    $stmt->bindValue(':search', "%$search%");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $conn->prepare("SELECT creditos FROM resellers WHERE email = :email");
    $stmt->bindParam(':email', $_SESSION['user_email']);
    $stmt->execute();
    $reseller = $stmt->fetch(PDO::FETCH_ASSOC);

} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
    exit();
}

$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Usuarios Creados</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/users.css">
    <style>
        body { background: #f5f7fa; }
        .main-card { background: #fff; border-radius: 14px; box-shadow: 0 4px 16px rgba(44,62,80,0.08); padding: 2rem; margin-top: 2rem; }
        .credit-card { background: linear-gradient(90deg, #16a085 60%, #3498db 100%); color: #fff; border-radius: 10px; padding: 1.2rem 2rem; display: flex; align-items: center; gap: 1rem; }
        .table-custom th { background: linear-gradient(90deg, #2c3e50 60%, #16a085 100%); color: #fff; }
        .btn-custom-light { background: #16a085; color: #fff; border: none; }
        .btn-custom-dark { background: #2c3e50; color: #fff; border: none; }
    </style>
</head>
<body>
    <div class="container">
        <h2 class="text-center mb-4">Usuarios Creados</h2>

        <?php
        if (isset($_GET['message'])) {
            echo '<div class="alert alert-info" role="alert">' . htmlspecialchars($_GET['message']) . '</div>';
        }

        if ($reseller) {
            echo '<div class="credit-card mb-4"><i class="fas fa-coins"></i><span>Créditos disponibles: ' . htmlspecialchars($reseller['creditos']) . '</span></div>';
        }
        ?>

        <form method="get" class="mb-4" style="max-width: 400px;">
            <div class="d-flex">
                <input type="text" class="form-control" name="search" placeholder="Buscar por email" value="<?php echo htmlspecialchars($search); ?>" style="margin-right: 10px;">
                <button type="submit" class="btn btn-custom-light p-2">Buscar</button>
            </div>
        </form>

        <div class="table-responsive">
            <table id="usersTable" class="table table-striped table-hover table-custom">
                <thead>
                    <tr>
                        <th>Email</th>
                        <th>Teléfono</th>
                        <th>Contraseña</th>
                        <th>Vencimiento</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                        <td><?php echo htmlspecialchars($user['phone']); ?></td>
                        <td><?php echo htmlspecialchars($user['password']); ?></td>
                        <td><?php echo htmlspecialchars($user['vencimiento']); ?></td>
                        <td>
                            <button class="btn btn-custom-light btn-sm edit-user" data-bs-toggle="modal" data-bs-target="#editModal" data-user-id="<?php echo $user['id']; ?>">Editar</button>
                            <button class="btn btn-custom-dark btn-sm renew-user" data-bs-toggle="modal" data-bs-target="#renewModal" data-user-id="<?php echo $user['id']; ?>">Renovar</button>
                            <button class="btn btn-danger btn-sm delete-user" data-bs-toggle="modal" data-bs-target="#deleteModal" data-user-id="<?php echo $user['id']; ?>" data-user-email="<?php echo htmlspecialchars($user['email']); ?>">Eliminar</button>
                            <button class="btn btn-warning btn-sm delete-devices" data-bs-toggle="modal" data-bs-target="#deleteDevicesModal" data-user-id="<?php echo $user['id']; ?>" data-user-email="<?php echo htmlspecialchars($user['email']); ?>">Eliminar Dispositivos</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div class="mt-3 text-center">
                <a href="opciones.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left"></i> Volver al Panel de Control
                </a>
            </div>
        </div>
    </div>

    <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Editar Usuario</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post" id="editForm">
                    <div class="modal-body">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <input type="hidden" name="user_id" id="editUserId">
                        <div class="mb-3"><label class="form-label">Email</label><input type="email" class="form-control" id="newEmail" name="new_email" required></div>
                        <div class="mb-3"><label class="form-label">Teléfono</label><input type="text" class="form-control" id="newPhone" name="new_phone" required></div>
                        <div class="mb-3"><label class="form-label">Contraseña</label><input type="text" class="form-control" id="newPassword" name="new_password" required></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                        <button type="submit" class="btn btn-custom-light" name="action" value="edit">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">Eliminar Usuario</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">¿Estás seguro de que quieres eliminar este usuario?<p id="deleteUserEmail" class="fw-bold"></p></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <input type="hidden" name="user_id" id="deleteUserId">
                        <button type="submit" class="btn btn-danger" name="action" value="delete">Eliminar</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="renewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">Renovar Usuario</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <input type="hidden" name="user_id" id="renewUserId">
                        <label class="form-label">Meses a renovar</label>
                        <select class="form-select" name="meses" required>
                            <?php for ($i = 1; $i <= 12; $i++): ?>
                                <option value="<?php echo $i; ?>"><?php echo $i; ?> mes<?php echo $i > 1 ? 'es' : ''; ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                        <button type="submit" class="btn btn-custom-dark" name="action" value="renew">Renovar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="deleteDevicesModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">Eliminar Dispositivos</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">¿Estás seguro de eliminar los Device IDs?<p id="deleteDevicesUserEmail" class="fw-bold"></p></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <input type="hidden" name="user_id" id="deleteDevicesUserId">
                        <button type="submit" class="btn btn-warning" name="action" value="delete_devices">Eliminar Dispositivos</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            $('.edit-user').on('click', function() {
                const row = $(this).closest('tr');
                $('#editUserId').val($(this).data('user-id'));
                $('#newEmail').val(row.find('td:nth-child(1)').text());
                $('#newPhone').val(row.find('td:nth-child(2)').text());
                $('#newPassword').val(row.find('td:nth-child(3)').text());
            });
            $('.delete-user').on('click', function() {
                $('#deleteUserId').val($(this).data('user-id'));
                $('#deleteUserEmail').text($(this).data('user-email'));
            });
            $('.renew-user').on('click', function() {
                $('#renewUserId').val($(this).data('user-id'));
            });
            $('.delete-devices').on('click', function() {
                $('#deleteDevicesUserId').val($(this).data('user-id'));
                $('#deleteDevicesUserEmail').text($(this).data('user-email'));
            });
        });
    </script>
</body>
</html>