<?php
session_start();
require_once 'db_connection.php';

$branch_id = $_SESSION['branch_id'] ?? 0;

if (isset($_POST['product']) && !empty($_POST['product'])) {
    $product = $conn->real_escape_string($_POST['product']);
    $list = "";

    $query = "
        SELECT mp.itemcode, mp.proname, mp.prid, IFNULL(ts.qty, 0) AS stock_qty
        FROM mobileproducts mp
        LEFT JOIN tbl_stock ts ON ts.prid = mp.prid AND ts.branch_id = '$branch_id'
        WHERE mp.itemcode LIKE '$product%' OR mp.proname LIKE '%$product%'
        ORDER BY mp.proname ASC
        LIMIT 20
    ";

    $result = $conn->query($query);

    if ($result && $result->num_rows > 0) {
        $list .= "<ul>";
        while ($row = $result->fetch_assoc()) {
            $itemcode = htmlspecialchars($row['itemcode']);
            $proname = htmlspecialchars($row['proname']);
            $prid = intval($row['prid']);
            $sqty = intval($row['stock_qty']);

            // You can style "out of stock" here if needed
            $style = ($sqty < 1) ? " style='background:red; color:#fff;'" : "";
            $label = ($sqty < 1) 
                ? "$itemcode / $proname / OUT OF STOCK" 
                : "$itemcode / $proname / QTY - $sqty";

            $list .= "<li$style tabindex='0' 
                onkeydown=\"if(event.keyCode==13){ addNewProductById($prid); event.preventDefault(); }\" 
                onclick=\"addNewProductById($prid);\">$label</li>";
        }
        $list .= "</ul>";
    }

    echo $list;
}
?>
