<?php
$page_title = 'Scan Product ID';
require_once('includes/load.php');
page_require_level(2);

// Handle scan or manual input
$product_details = null;
if (isset($_POST['scan_product_id']) && !empty($_POST['product_id'])) {
    $product_id = $db->escape($_POST['product_id']);
    
    // Query product based on part_number or barcode_id
    $sql = "SELECT part_number, name FROM products WHERE part_number = '{$product_id}' OR barcode_id = '{$product_id}' LIMIT 1";
    $result = $db->query($sql);
    
    if ($db->num_rows($result) > 0) {
        $product_details = $db->fetch_assoc($result);
    } else {
        $session->msg('d', "Product not found.");
    }
}

include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-6 offset-md-3">
        <div class="panel panel-default">
            <div class="panel-heading text-center">
                <strong>
                    <span class="glyphicon glyphicon-barcode"></span>
                    <span>Scan Product ID</span>
                </strong>
            </div>
            <div class="panel-body">
                <!-- Form to scan barcode or manual input -->
                <form method="POST">
                    <div class="form-group">
                        <label for="product_id" style="font-size: 18px;">Scan Product ID (Barcode or Part Number):</label>
                        <input type="text" name="product_id" id="product_id" class="form-control" style="font-size: 20px; padding: 15px;" required autofocus placeholder="Enter Part Number or Barcode" />
                    </div>
                    <button type="submit" name="scan_product_id" class="btn btn-primary btn-lg btn-block" style="font-size: 18px; padding: 15px;">Search Product</button>
                </form>
                <br>

                <!-- Display Product Details -->
                <?php if ($product_details): ?>
                    <div class="alert alert-success">
                        <h4>Product Found!</h4>
                        <p><strong>Part Number:</strong> <?php echo htmlspecialchars($product_details['part_number']); ?></p>
                        <p><strong>Product Name:</strong> <?php echo htmlspecialchars($product_details['name']); ?></p>
                    </div>
                <?php elseif (isset($_POST['scan_product_id'])): ?>
                    <div class="alert alert-danger">
                        <h4>Product not found!</h4>
                        <p>Please check the barcode or part number and try again.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>
