<?php
include "auth.php";
checkPermission(['admin', 'manager', 'staff']);
require_once "db.php";

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$sale_id = intval($_POST['sale_id']);
$customer_id = intval($_POST['customer_id']);
$sale_date = $_POST['sale_date'];
$payment_due_date = !empty($_POST['payment_due_date']) ? $_POST['payment_due_date'] : NULL;
$total = floatval($_POST['total']);
$paid = floatval($_POST['paid']);
$due = floatval($_POST['due']);
$deleted_item_ids = isset($_POST['deleted_item_ids']) && $_POST['deleted_item_ids'] !== '' ? explode(',', $_POST['deleted_item_ids']) : [];

// Start transaction
$conn->begin_transaction();

try {
    // Update main sale record
    $updateSale = $conn->prepare("UPDATE sales SET customer_id=?, sale_date=?, payment_due_date=?, total=?, paid=?, due=? WHERE sale_id=?");
    $updateSale->bind_param("issdddi", $customer_id, $sale_date, $payment_due_date, $total, $paid, $due, $sale_id);
    $updateSale->execute();

    // Delete removed items
    if (!empty($deleted_item_ids)) {
        $in = implode(',', array_fill(0, count($deleted_item_ids), '?'));
        $types = str_repeat('i', count($deleted_item_ids));
        $stmtDel = $conn->prepare("DELETE FROM sale_items WHERE sale_item_id IN ($in)");
        $stmtDel->bind_param($types, ...$deleted_item_ids);
        $stmtDel->execute();
    }

    // Process item updates/inserts
    $products = $_POST['product'];
    $sizes = $_POST['size'];
    $size_qtys = $_POST['size_qty'];
    $rates = $_POST['rate'];
    $qtys = $_POST['qty'];
    $item_ids = $_POST['item_id'];

    for ($i = 0; $i < count($products); $i++) {
        $item_id = intval($item_ids[$i]);
        $product = trim($products[$i]);
        $size_value = floatval($sizes[$i]);
        $size_qty = floatval($size_qtys[$i]);
        $rate = floatval($rates[$i]);
        $qty = floatval($qtys[$i]);

        // Combine size and qty into one string for saving (e.g., "10×20")
        $size_text = $size_value . "×" . $size_qty;

        // Calculate subtotal
        $subtotal = $size_value * $size_qty * $rate * $qty;

        if ($item_id > 0) {
            // Update existing item
            $stmt = $conn->prepare("UPDATE sale_items SET product=?, size=?, rate=?, qty=?, subtotal=? WHERE sale_item_id=?");
            $stmt->bind_param("ssdddi", $product, $size_text, $rate, $qty, $subtotal, $item_id);
            $stmt->execute();
        } else {
            // Insert new item
            $stmt = $conn->prepare("INSERT INTO sale_items (sale_id, product, size, rate, qty, subtotal) VALUES (?,?,?,?,?,?)");
            $stmt->bind_param("issddd", $sale_id, $product, $size_text, $rate, $qty, $subtotal);
            $stmt->execute();
        }
    }

    $conn->commit();
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
