<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

$query = trim($_GET['q'] ?? '');
$jsonMode = isset($_GET['json']);
$quick = isset($_GET['quick']);
$qty = (float)($_GET['qty'] ?? 1);

if ($qty <= 0) {
    $qty = 1;
}

if ($query === '') {

    $stmt = $db->prepare("
        SELECT *
        FROM items
        ORDER BY name ASC
        LIMIT 15
    ");

    $stmt->execute();

} else {

    /*
        Existing search logic
    */

    if (is_numeric($query)) {

        $stmt = $db->prepare("
            SELECT *
            FROM items
            WHERE barcode = ?
            LIMIT 1
        ");
        $stmt->execute([$query]);

        $item = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($item) {

            if ($quick) {
                ?>
                <script>
                    addItem(<?= $item['id'] ?>, <?= $qty ?>);
                </script>
                <?php
                exit;
            }

            $items = [$item];

        } else {

            $stmt = $db->prepare("
                SELECT *
                FROM items
                WHERE name LIKE ?
                ORDER BY name ASC
                LIMIT 15
            ");

            $stmt->execute(["%$query%"]);

            $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }

    } else {

        $stmt = $db->prepare("
            SELECT *
            FROM items
            WHERE name LIKE ?
            ORDER BY name ASC
            LIMIT 15
        ");

        $stmt->execute(["%$query%"]);

        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

/*
    Search by barcode first if numeric
*/
if (is_numeric($query)) {

    $stmt = $db->prepare("
        SELECT *
        FROM items
        WHERE barcode = ?
        LIMIT 1
    ");
    $stmt->execute([$query]);

    $item = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($item) {

        if ($quick) {
            ?>
            <script>
                addItem(<?= $item['id'] ?>, <?= $qty ?>);
            </script>
            <?php
            exit;
        }

        ?>
        <button
            class="list-group-item list-group-item-action search-item"
            data-id="<?= $item['id'] ?>"
            data-name="<?= htmlspecialchars($item['name']) ?>"
            data-barcode="<?= htmlspecialchars($item['barcode'] ?? '') ?>"
            data-price="<?= $item['price'] ?>"
            onclick="addItem(<?= $item['id'] ?>)"
        >
            <strong><?= htmlspecialchars($item['name']) ?></strong>
            <span class="float-end">
                ₹ <?= number_format($item['price'], 2) ?>
            </span>
        </button>
        <?php
        exit;
    }
}

/*
    Name search
*/
$stmt = $db->prepare("
    SELECT *
    FROM items
    WHERE name LIKE ?
    ORDER BY name ASC
    LIMIT 15
");
$stmt->execute(["%$query%"]);

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$items) {
    ?>
    <div class="list-group-item text-danger">
        No items found
    </div>
    <?php
    exit;
}

/*
    Quick parser auto add first match
*/
if ($quick && count($items) > 0) {
    ?>
    <script>
        addItem(<?= $items[0]['id'] ?>, <?= $qty ?>);
    </script>
    <?php
    exit;
}
if ($jsonMode) {

    if (!empty($items)) {

        echo json_encode([
            'success' => true,
            'item' => [
                'id' => $items[0]['id'],
                'name' => $items[0]['name']
            ]
        ]);

    } else {

        echo json_encode([
            'success' => false
        ]);
    }

    exit;
}
foreach ($items as $item):
?>
    <button
        class="list-group-item list-group-item-action search-item"
        data-id="<?= $item['id'] ?>"
        data-name="<?= htmlspecialchars($item['name']) ?>"
        data-barcode="<?= htmlspecialchars($item['barcode'] ?? '') ?>"
        data-price="<?= $item['price'] ?>"
        onclick="addItem(<?= $item['id'] ?>)"
    >
        <strong><?= htmlspecialchars($item['name']) ?></strong>

        <?php if (!empty($item['barcode'])): ?>
            <small class="text-muted">
                (<?= htmlspecialchars($item['barcode']) ?>)
            </small>
        <?php endif; ?>

        <span class="float-end">
            ₹ <?= number_format($item['price'], 2) ?>
        </span>
    </button>
<?php endforeach; ?>