<?php
require_once "db.php";
header('Content-Type: application/json');

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid sale ID']);
    exit;
}

$sale_id = intval($_GET['id']);

// --- Fetch sale info ---
$stmt = $conn->prepare("SELECT sale_id, customer_id, sale_date, payment_due_date, total, paid, due FROM sales WHERE sale_id=?");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$saleResult = $stmt->get_result();

if ($saleResult->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Sale not found']);
    exit;
}

$sale = $saleResult->fetch_assoc();

// --- Fetch sale items ---
$itemQuery = $conn->prepare("SELECT sale_item_id, product, size, rate, qty, subtotal FROM sale_items WHERE sale_id=?");
$itemQuery->bind_param("i", $sale_id);
$itemQuery->execute();
$itemsResult = $itemQuery->get_result();

$items = [];
while ($row = $itemsResult->fetch_assoc()) {
    $size_value = 0;
    $size_qty = 1;

    // Parse stored size like "10×20" or "10x20"
    if (preg_match('/^(\d+(?:\.\d+)?)\s*[×xX]\s*(\d+(?:\.\d+)?)/', $row['size'], $m)) {
        $size_value = floatval($m[1]);
        $size_qty = floatval($m[2]);
    } elseif (is_numeric($row['size'])) {
        $size_value = floatval($row['size']);
        $size_qty = 1;
    }

    $row['size_value'] = $size_value;
    $row['size_qty'] = $size_qty;

    $items[] = $row;
}

echo json_encode([
    'success' => true,
    'sale' => $sale,
    'items' => $items
]);
?>
