<?php
include "core/autoload.php";

include "core/app/model/ProductData.php";
include "core/app/model/PersonData.php";
include "core/app/model/TypeData.php";
include "core/app/model/StateData.php";

// Captura el término de búsqueda
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Obtén todos los clientes
$clients =  ProductData::getAllBy('brand_id', $_GET["id"]);

// Filtra los clientes según el término de búsqueda
// Filtra los clientes según el término de búsqueda
$filteredClients = [];
if ($search !== '') {
    foreach ($clients as $c) {
        if (stripos($c->name, $search) !== false || stripos($c->code, $search) !== false) {
            $filteredClients[] = $c;
        }
    }
} else {
    $filteredClients = $clients;
}


// Genera el HTML de los resultados
if (count($filteredClients) > 0) {
    foreach ($filteredClients as $p): ?>
        <div class="col">
            <div class="card h-100 border">
                <!-- Image container -->
                <div class="card-img-top position-relative" style="height: 200px;">
                    <img src="assets/images/products/<?php echo $p->image; ?>"
                        class="w-100 h-100"
                        style="object-fit: contain; padding: 1rem;"
                        alt="product-img"
                        loading="lazy">
                </div>
                <!-- Content -->
                <div class="card-body">
                    <h6 class="card-title mb-2"><?php echo $p->name; ?></h6>
                    <hr>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="text-muted small">Código:</span>
                        <span class="fw-medium"><?php echo $p->code; ?></span>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-primary btn-sm flex-grow-1"
                            onclick="window.location.href='./?view=product&id=<?php echo $p->id; ?>';">
                            Ver producto
                        </button>
                        <button type="button" class="btn btn-danger btn-sm"
                            data-bs-toggle="modal"
                            data-bs-target="#modaleliminarproducto">
                            <i class="bi bi-trash-fill"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
<?php endforeach;
} else {
    echo '<p>No se encontraron oportunidades con el término "<strong>' . htmlspecialchars($search) . '</strong>".</p>';
}
?>