<?php
session_start();
if (!isset($_SESSION["user_id"])) {
    header("Location: auth/login.php");
    exit();
}
require_once 'includes/header.php';

// Search term
$search_term = isset($_GET['search']) ? trim($_GET['search']) : '';

// Pagination settings
$products_per_page = 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $products_per_page;

$pdo = db();

// Base query
$sql_count = "SELECT COUNT(*) FROM productos";
$sql = "SELECT 
            p.*, 
            GROUP_CONCAT(c.nombre, ': ', spc.stock_actual SEPARATOR '<br>') as stock_por_ciudad
        FROM 
            productos p
        LEFT JOIN 
            stock_por_ciudad spc ON p.id = spc.producto_id
        LEFT JOIN
            ciudades c ON spc.ciudad_id = c.id";

$params = [];

// Apply search filter
if (!empty($search_term)) {
    $sql_count .= " WHERE nombre LIKE :search";
    $sql .= " WHERE p.nombre LIKE :search";
    $params[':search'] = '%' . $search_term . '%';
}

// Get total number of products (filtered or not)
$total_stmt = $pdo->prepare($sql_count);
$total_stmt->execute($params);
$total_products = $total_stmt->fetchColumn();
$total_pages = ceil($total_products / $products_per_page);

// Add grouping, ordering and pagination to the main query
$sql .= " GROUP BY p.id
        ORDER BY p.id DESC
        LIMIT :limit OFFSET :offset";

$stmt = $pdo->prepare($sql);

// Bind search param if it exists
if (!empty($search_term)) {
    $stmt->bindValue(':search', $params[':search'], PDO::PARAM_STR);
}

$stmt->bindValue(':limit', $products_per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">

    <!-- Page Heading -->
    <div class="d-sm-flex justify-content-between align-items-center mb-4">
        <h3 class="text-dark mb-0">Gestión de Productos</h3>
        <a class="btn btn-primary btn-sm" role="button" href="agregar_producto.php">
            <i class="fas fa-plus fa-sm text-white-50"></i>&nbsp;Agregar Producto
        </a>
    </div>

    <!-- Success/Error Messages -->
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success_message']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error_message']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>

    <!-- Search Form -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <form action="productos.php" method="get" class="form-inline">
                <div class="input-group">
                    <input type="text" name="search" class="form-control" placeholder="Buscar por nombre..." value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
                    <button class="btn btn-primary" type="submit">Buscar</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow">
        <div class="card-header py-3">
            <p class="text-primary m-0 fw-bold">Listado de Productos</p>
        </div>
        <div class="card-body">
            <div class="table-responsive table mt-2" id="dataTable" role="grid" aria-describedby="dataTable_info">
                <table class="table my-0" id="dataTable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nombre</th>
                            <th>Descripción</th>
                            <th>Precio</th>
                            <th>Stock por Ciudad</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($products) > 0): ?>
                            <?php foreach ($products as $product): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($product['id']); ?></td>
                                    <td><?php echo htmlspecialchars($product['nombre']); ?></td>
                                    <td><?php echo htmlspecialchars($product['descripcion']); ?></td>
                                    <td>$<?php echo htmlspecialchars(number_format($product['precio_venta'], 2)); ?></td>
                                    <td><?php echo $product['stock_por_ciudad'] ? $product['stock_por_ciudad'] : 'Sin stock'; ?></td>
                                    <td>
                                        <a href="editar_producto.php?id=<?php echo $product['id']; ?>" class="btn btn-warning btn-sm"><i class="fas fa-edit"></i> Editar</a>
                                        <a href="eliminar_producto.php?id=<?php echo $product['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('¿Estás seguro de que quieres eliminar este producto?');"><i class="fas fa-trash"></i> Eliminar</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="text-center">No hay productos que coincidan con la búsqueda.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <!-- Pagination Controls -->
            <div class="d-flex justify-content-center">
                <nav>
                    <ul class="pagination">
                        <?php if ($page > 1): ?>
                            <li class="page-item"><a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo isset($_GET['search']) ? '&search=' . htmlspecialchars($_GET['search']) : ''; ?>">Anterior</a></li>
                        <?php endif; ?>

                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?><?php echo isset($_GET['search']) ? '&search=' . htmlspecialchars($_GET['search']) : ''; ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>

                        <?php if ($page < $total_pages): ?>
                            <li class="page-item"><a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo isset($_GET['search']) ? '&search=' . htmlspecialchars($_GET['search']) : ''; ?>">Siguiente</a></li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>