<?php 
include 'includes/config.php';
$ref_no = $_GET['ref_no'] ?? '';
if(!$ref_no) exit('Invalid Ref');

$stmt = $conn->prepare("SELECT supplier_id FROM purchase_lines WHERE ref_no = :ref_no LIMIT 1");
$stmt->bindValue(':ref_no', $ref_no);
$stmt->execute();
$supplier = $stmt->fetch(PDO::FETCH_ASSOC);
$supplier_id = $supplier['supplier_id'] ?? 0;

$stmt = $conn->prepare("SELECT p.id AS line_id, pr.name AS ProductName, pr.sku, pr.barcode, 
                               p.quantity, p.sell_price, p.purchase_price, p.product_id
                        FROM purchase_lines p
                        LEFT JOIN products pr ON p.product_id = pr.id
                        WHERE p.ref_no = :ref_no");
$stmt->bindValue(':ref_no', $ref_no);
$stmt->execute();
$items = $stmt->fetchAll();

echo '<table class="table table-bordered" id="billTable">';
echo '<tr>
        <th>#</th>
        <th>Product</th>
        <th>SKU</th>
        <th>Barcode</th>
        <th>Qty</th>
        <th>Sale Price</th>
        <th>Purchase Price</th>
        <th>Action</th>
      </tr>';
$i=1;
foreach($items as $item){
    echo '<tr>';
    echo '<td>'.$i++.'</td>';
    echo '<td>'.$item['ProductName'].'</td>';
    echo '<td>'.$item['sku'].'</td>';
    echo '<td>'.$item['barcode'].'</td>';
    echo '<td><input type="number" value="'.$item['quantity'].'" class="form-control qty" data-id="'.$item['line_id'].'"></td>';
    echo '<td><input type="number" value="'.$item['sell_price'].'" class="form-control sell_price" data-id="'.$item['line_id'].'"></td>';
    echo '<td><input type="number" value="'.$item['purchase_price'].'" class="form-control purchase_price" data-id="'.$item['line_id'].'"></td>';
    echo '<td><button class="btn btn-sm btn-success saveItemBtn" data-id="'.$item['line_id'].'">Save</button></td>';
    echo '</tr>';
}

echo '<tr id="addRowBtn">
        <td colspan="8" class="text-center">
            <button class="btn btn-sm btn-info" id="newRowBtn"><i class="bi bi-plus"></i> Add New Product</button>
        </td>
      </tr>';

echo '</table>';
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function(){

    $('.saveItemBtn').on('click', function(){
        let id = $(this).data('id');
        let qty = $('.qty[data-id="'+id+'"]').val();
        let sell = $('.sell_price[data-id="'+id+'"]').val();
        let pur = $('.purchase_price[data-id="'+id+'"]').val();
        $.post('ajax_update_item.php', {id:id, qty:qty, sell_price:sell, purchase_price:pur}, function(res){
            alert(res);
        });
    });


$('#newRowBtn').on('click', function(){
    let newRow = `
    <tr class="newItemRow">
        <td>New</td>
        <td>
            <select class="form-control new_product_select" style="width:100%">
                <option value="" selected disabled>Select Product</option>
                <?php 
                $products = $conn->query("SELECT id, name, sku FROM products")->fetchAll();
                foreach($products as $pr){
                    echo '<option value="'.$pr['id'].'">'.$pr['name'].' ('.$pr['sku'].')</option>';
                }
                ?>
            </select>
        </td>
        <td><input type="text" class="form-control new_sku" readonly></td>
        <td></td>
        <td><input type="number" class="form-control new_qty" value="1"></td>
        <td><input type="number" class="form-control new_sell" value="0"></td>
        <td><input type="number" class="form-control new_purchase" value="0"></td>
        <td>
            <button class="btn btn-sm btn-success addItemBtn">Add</button>
            <button class="btn btn-sm btn-danger removeRowBtn">Remove</button>
        </td>
    </tr>`;
    $('#addRowBtn').before(newRow);

    $('.new_product_select').select2({
        placeholder: "Select Product",
        allowClear: true
    });
});


    $(document).on('click', '.removeRowBtn', function(){
        $(this).closest('tr').remove();
    });

    $(document).on('change', '.new_product_select', function(){
        let row = $(this).closest('tr');
        let product_id = $(this).val();
        $.get('ajax_get_product_variation.php', {product_id: product_id}, function(res){
            let data = JSON.parse(res);
            row.find('.new_sku').val(data.sub_sku);
            row.find('.new_sell').val(data.default_sell_price);
            row.find('.new_purchase').val(data.default_purchase_price);
        });
    });

    $(document).on('click', '.addItemBtn', function(){
        let row = $(this).closest('tr');
        let product_id = row.find('.new_product_select').val();
        let qty = row.find('.new_qty').val();
        let sell = row.find('.new_sell').val();
        let pur = row.find('.new_purchase').val();
        let ref_no = '<?php echo $ref_no; ?>';
        let supplier_id = '<?php echo $supplier_id; ?>';

        $.post('ajax_add_new_item.php', 
            {ref_no: ref_no, product_id: product_id, qty: qty, sell_price: sell, purchase_price: pur, supplier_id: supplier_id}, 
            function(res){
                alert(res);
                location.reload();
            }
        );
    });

});
</script>
