<?php
require_once dirname(__DIR__, 2) . '/includes/db.php';
error_reporting(0);
header('Content-Type: application/json');

$pid = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
$bid = isset($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;

if ($pid === 0 || $bid === 0) {
    echo json_encode(['status' => 'error', 'message' => 'Missing identifiers.']);
    exit;
}

try {
    $meta_sql = "
        SELECT p.generic_name, bd.brand_name, ib.batch_number, ib.expiry_date, ib.quantity_on_hand
        FROM inventory_batches ib
        INNER JOIN product_variants pv ON ib.variant_id = pv.id
        INNER JOIN products p ON pv.product_id = p.id
        LEFT JOIN brand_dictionary bd ON pv.brand_id = bd.id
        WHERE ib.id = $bid AND p.id = $pid LIMIT 1
    ";
    $meta_res = $conn->query($meta_sql);
    if(!$meta_res) throw new Exception("DB Error");
    $meta = $meta_res->fetch_assoc();

    $hist_sql = "
        SELECT sm.movement_date, sm.transaction_type, sm.quantity, sm.reference_id,
               src.store_name as source_name, 
               dst.store_name as dest_name,
               CONCAT(st.first_name, ' ', st.last_name) as staff_name
        FROM stock_movements sm
        LEFT JOIN stores src ON sm.source_store_id = src.id
        LEFT JOIN stores dst ON sm.dest_store_id = dst.id
        LEFT JOIN staff st ON sm.performed_by = st.staff_id
        WHERE sm.batch_id = $bid
        ORDER BY sm.movement_date DESC
    ";
    
    $history = [];
    $hist_res = $conn->query($hist_sql);
    if($hist_res) {
        while ($row = $hist_res->fetch_assoc()) {
            $history[] = $row;
        }
    }

    echo json_encode(['status' => 'success', 'meta' => $meta, 'history' => $history]);
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>