<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    exit;
}

include_once "../config/database.php";

$keyword = '';

if (isset($_GET['keyword'])) {
    $keyword = trim(mysqli_real_escape_string($conn, $_GET['keyword']));
}

if ($keyword == '') {
    exit;
}

$sql = "
SELECT
    id,
    product_name,
    sku,
    barcode,
    selling_price,
    stock
FROM products
WHERE status = 1
AND stock > 0
AND (
    product_name LIKE '%$keyword%'
    OR sku LIKE '%$keyword%'
    OR barcode LIKE '%$keyword%'
)
ORDER BY product_name ASC
LIMIT 20
";

$result = mysqli_query($conn, $sql);

if (!$result) {
    exit;
}

if (mysqli_num_rows($result) == 0) {
    ?>

    <div class="list-group-item text-center text-muted py-3">
        No Product Found
    </div>

    <?php
    exit;
}

while ($row = mysqli_fetch_assoc($result)) {
?>

<button
    type="button"
    class="list-group-item list-group-item-action addProduct"
    data-id="<?= $row['id']; ?>">

    <div class="d-flex justify-content-between align-items-center">

        <div>

            <strong>
                <?= htmlspecialchars($row['product_name']); ?>
            </strong>

            <br>

            <small class="text-muted">

                SKU :
                <?= htmlspecialchars($row['sku']); ?>

                <?php if (!empty($row['barcode'])) { ?>

                    |

                    Barcode :
                    <?= htmlspecialchars($row['barcode']); ?>

                <?php } ?>

            </small>

        </div>

        <div class="text-end">

            <strong class="text-success">

                ₹<?= number_format($row['selling_price'], 2); ?>

            </strong>

            <br>

            <small class="text-primary">

                Stock :
                <?= (int)$row['stock']; ?>

            </small>

        </div>

    </div>

</button>

<?php
}
?>