<?php
include 'includes/config.php';

if (isset($_POST['id']) && isset($_POST['row_count'])) {
    $product_id = $_POST['id'];
    $row_count = intval($_POST['row_count']); // Get current row count from the request

    // Query to get product details and units
    $query = $conn->prepare("
        SELECT 
            p.name AS product_name, 
            p.id AS product_id,
            v.default_purchase_price AS purchase_price,
            v.dpp_inc_tax AS unit_cost_before_tax,
            v.profit_percent AS profit_margin,
            v.sell_price_inc_tax AS sell_price,
            p.unit_id AS unit_id
        FROM products p
        INNER JOIN variations v ON p.id = v.product_id
        WHERE business_id = 3 AND p.id = ?
    ");
    $query->execute([$product_id]);
    $product = $query->fetch();

    if ($product) {
        // Query to get units if the unit_id matches
        $unitQuery = $conn->prepare("
            SELECT `id`, `business_id`, `actual_name`, `short_name`
            FROM units
            WHERE `business_id` = 3 AND `id` = ?
        ");
        $unitQuery->execute([$product['unit_id']]);
        $units = $unitQuery->fetchAll();

        // Generate options for the select box
        $unitOptions = '';
        foreach ($units as $unit) {
            $unitOptions .= '<option value="' . htmlspecialchars($unit['actual_name']) . '">'
                            . htmlspecialchars($unit['actual_name']) . ' (' 
                            . htmlspecialchars($unit['short_name']) . ')</option>';
        }

        // Prepare HTML output with auto-incremented row number
        $html = '
        <tr>
            <td>' . ($row_count + 1) . '</td> <!-- Increment row count -->
            <td style="display:none;"><input type="text" name="product_id[]" class="form-control" value="' . htmlspecialchars($product['product_id']) . '"></td>
            <td class="product-name">' . htmlspecialchars($product['product_name']) . '</td>
            <td>
                <input type="text" class="form-control quantity" name="quantity[]" value="1">
                <br>
                <select name="unit[]" class="form-control">' . $unitOptions . '</select>
            </td>
            <td style="display:none;"><input type="text" class="form-control unit-selling-price" name="price[]" value="' . htmlspecialchars($product['sell_price']) . '"></td>
            <td class="subtotal">1.00</td>
            <td>
                <ion-icon name="trash-outline" class="delete-row"></ion-icon>
            </td>
        </tr>';
        
        echo $html;
    } else {
        echo '<tr><td colspan="11">Product not found.</td></tr>';
    }
}
?>
