<?php
session_start();
require_once '../../../assets/db_connect.php';

$product_id = intval($_GET['product_id']);
$shop_id = $_SESSION['user']['shop_id'];

$sql = "
SELECT 
    p.id,
    p.name,
    p.selling_price,
    p.vat_percent,
    COALESCE(ps.total_qty,0) AS stock
FROM products p
LEFT JOIN product_stock_view ps ON p.id = ps.product_id
WHERE p.id = ? AND p.shop_id = ?
";

$stmt = $pdo->prepare($sql);
$stmt->execute([$product_id, $shop_id]);
$p = $stmt->fetch();

if (!$p || $p['stock'] <= 0) exit;

echo "
<tr data-product='{$p['id']}'>
    <td>{$p['name']}
        <input type='hidden' name='items[{$p['id']}][product_id]' value='{$p['id']}'>
    </td>
    <td>{$p['stock']}</td>
    <td>
        <input type='number' name='items[{$p['id']}][price]'
               class='form-control price' value='{$p['selling_price']}' readonly>
    </td>
    <td>
        <input type='number' name='items[{$p['id']}][qty]'
               class='form-control qty' value='1' min='1' max='{$p['stock']}'>
    </td>
    <td>{$p['vat_percent']}%</td>
    <td class='lineTotal'>0.00</td>
    <td>
        <button type='button' class='btn btn-danger btn-sm'
                onclick='$(this).closest(\"tr\").remove(); calcTotals();'>
            ×
        </button>
    </td>
</tr>";
