<?php
session_start();

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

include 'db.php';

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.";
                } 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.";
                } elseif ($_POST['action'] === 'renew') {
                    $meses = intval($_POST['meses']);
                    $creditos = 0;

                    // Obtener créditos y estado de pausa
                    $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'];

                        // Verificar si el revendedor está pausado
                        if ($reseller['pause'] == 1) {
                            $message = "Aviso: No puedes renovar usuarios porque tu cuenta está en pausa.";
                        } else {
                            if ($creditos >= $meses) {
                                // Obtener la fecha de vencimiento actual del usuario
                                $stmt = $conn->prepare("SELECT vencimiento FROM users WHERE id = :id");
                                $stmt->bindParam(':id', $user_id);
                                $stmt->execute();
                                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                                // Establecer zona horaria de Argentina
                                $zona = new DateTimeZone("America/Argentina/Buenos_Aires");
                                $fecha_actual = new DateTime("now", $zona);

                                // Obtener la fecha de vencimiento actual del usuario con zona horaria
                                $fecha_vencimiento = new DateTime($user['vencimiento'], $zona);

                                // Determinar la base para la renovación
                                if ($fecha_vencimiento < $fecha_actual) {
                                // Ya vencido, usar la hora actual
                                $nueva_fecha = clone $fecha_actual;
                                } else {
                                // Aún vigente, conservar hora exacta de vencimiento
                                $nueva_fecha = clone $fecha_vencimiento;
                                                                        }

                                // Sumar los meses
                                $nueva_fecha->modify("+$meses months");

                                // Nuevo vencimiento con hora incluida
                                $nuevo_vencimiento = $nueva_fecha->format('Y-m-d H:i:s');

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

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

                                $message = "Usuario renovado con éxito. Nueva fecha de vencimiento: $nuevo_vencimiento.";
                            } 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') {
                    // Eliminar todos los device IDs del usuario
                    $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.";
                }
            } 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 2rem 1.5rem 2rem;
            margin-top: 2rem;
            margin-bottom: 2rem;
        }
        .credit-card {
            background: linear-gradient(90deg, #16a085 60%, #3498db 100%);
            color: #fff;
            border-radius: 10px;
            padding: 1.2rem 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 2px 8px rgba(44,62,80,0.08);
            font-size: 1.2rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        .credit-card i {
            font-size: 1.5rem;
        }
        .table-custom th {
            background: linear-gradient(90deg, #2c3e50 60%, #16a085 100%);
            color: #fff;
            border: none;
        }
        .table-custom td {
            vertical-align: middle;
        }
        .btn-custom-light {
            background: #16a085;
            color: #fff;
            border: none;
        }
        .btn-custom-light:hover {
            background: #138d75;
            color: #fff;
        }
        .btn-custom-dark {
            background: #2c3e50;
            color: #fff;
            border: none;
        }
        .btn-custom-dark:hover {
            background: #1a242f;
            color: #fff;
        }
        .table-striped>tbody>tr:nth-of-type(odd)>* {
            background-color: #f8f9fa;
        }
        .table-striped>tbody>tr:nth-of-type(even)>* {
            background-color: #eaf6f6;
        }
        .table-hover tbody tr:hover>* {
            background-color: #d1f2eb !important;
        }
        .modal-header {
            background: linear-gradient(90deg, #2c3e50 60%, #16a085 100%);
            color: #fff;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
        }
        .modal-footer {
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #16a085;
            box-shadow: 0 0 0 0.2rem rgba(22,160,133,.15);
        }
        .btn-outline-secondary {
            border-radius: 6px;
        }
    </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 '<p>Créditos disponibles: ' . htmlspecialchars($reseller['creditos']) . '</p>';
        }
        ?>

        <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>

    <!-- Modal para editar usuario -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">Editar Usuario</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></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 for="newEmail" class="form-label">Email</label>
                            <input type="email" class="form-control" id="newEmail" name="new_email" required>
                        </div>
                        <div class="mb-3">
                            <label for="newPhone" class="form-label">Teléfono</label>
                            <input type="text" class="form-control" id="newPhone" name="new_phone" required>
                        </div>
                        <div class="mb-3">
                            <label for="newPassword" 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>

    <!-- Modal para eliminar usuario -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">Eliminar Usuario</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    ¿Estás seguro de que quieres eliminar este usuario?
                    <p id="deleteUserEmail"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <form method="post" id="deleteForm">
                        <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>

    <!-- Modal para renovar usuario -->
    <div class="modal fade" id="renewModal" tabindex="-1" aria-labelledby="renewModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="renewModalLabel">Renovar Usuario</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" id="renewForm">
                    <div class="modal-body">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <input type="hidden" name="user_id" id="renewUserId">
                        <div class="mb-3">
                            <label for="meses" class="form-label">Meses a renovar</label>
                            <select class="form-select" id="meses" name="meses" required>
                                <option value="">Selecciona</option>
                                <?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>
                    <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>

    <!-- Modal para eliminar dispositivos -->
    <div class="modal fade" id="deleteDevicesModal" tabindex="-1" aria-labelledby="deleteDevicesModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteDevicesModalLabel">Eliminar Dispositivos</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    ¿Estás seguro de que quieres eliminar todos los Device IDs de este usuario?
                    <p id="deleteDevicesUserEmail"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <form method="post" id="deleteDevicesForm">
                        <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 modal
            $('.edit-user').on('click', function() {
                const userId = $(this).data('user-id');
                $('#editUserId').val(userId);
                
                // Obtener los datos del usuario
                const row = $(this).closest('tr');
                const email = row.find('td:nth-child(1)').text();
                const phone = row.find('td:nth-child(2)').text();
                const password = row.find('td:nth-child(3)').text();
    
                // Rellenar el formulario con los datos del usuario
                $('#newEmail').val(email);
                $('#newPhone').val(phone);
                $('#newPassword').val(password);
            });
    
            // Delete user modal
            $('.delete-user').on('click', function() {
                const userId = $(this).data('user-id');
                const userEmail = $(this).data('user-email');
                $('#deleteUserId').val(userId);
                $('#deleteUserEmail').text(userEmail);
            });
    
            // Renew user modal
            $('.renew-user').on('click', function() {
                const userId = $(this).data('user-id');
                $('#renewUserId').val(userId);
            });

            // Delete devices modal
            $('.delete-devices').on('click', function() {
                const userId = $(this).data('user-id');
                const userEmail = $(this).data('user-email');
                $('#deleteDevicesUserId').val(userId);
                $('#deleteDevicesUserEmail').text(userEmail);
            });
        });
    </script>

</body>
</html>
