<?php
require_once '../db.php';

$pid = (int)($_GET['product_id'] ?? 0);
if ($pid <= 0) { echo json_encode(['error' => 'Invalid product']); exit; }

header('Content-Type: application/json');

$prod = $conn->query("SELECT name, selling_price FROM products WHERE id = $pid LIMIT 1")->fetch_assoc();
if (!$prod) { echo json_encode(['error' => 'Product not found']); exit; }

$batchRes = $conn->query("
    SELECT
        pi.id AS purchase_item_id,
        po.company_id,
        pi.batch_no,
        pi.quantity,
        pi.available_qty,
        pi.purchase_price,
        pi.gst_percent,
        ROUND(pi.purchase_price * (1 + pi.gst_percent / 100), 2) AS purchase_price_incl,
        pi.selling_price AS selling_price_excl,
        ROUND(pi.selling_price * (1 + pi.gst_percent / 100), 2) AS selling_price_incl,
        pi.mrp,
        po.purchase_date,
        cm.company_name,
        COALESCE(NULLIF(cm.invoice_prefix,''), UPPER(SUBSTR(cm.company_name, 1, 3))) AS company_prefix
    FROM purchase_items pi
    JOIN purchase_orders po ON po.id = pi.purchase_order_id
    JOIN company_master cm ON cm.id = po.company_id
    WHERE pi.product_id = $pid AND po.status = 'final' AND pi.available_qty > 0
    ORDER BY po.purchase_date DESC, pi.id DESC
    LIMIT 30
");
$batches = [];
while ($b = $batchRes->fetch_assoc()) $batches[] = $b;

$lastSale = $conn->query("
    SELECT selling_price_incl FROM sales_items WHERE product_id = $pid ORDER BY id DESC LIMIT 1
")->fetch_assoc();
$lastSellingPrice = (float)($lastSale['selling_price_incl'] ?? 0);

echo json_encode([
    'product_name'       => $prod['name'],
    'default_sell_price' => (float)$prod['selling_price'],
    'last_selling_price' => $lastSellingPrice,
    'batches'            => $batches,
]);
