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

$adjustments = json_decode($_POST['adjustments'], true);
if(!$adjustments) exit("No adjustments received.");

$stmt = $conn->prepare("SELECT invoice FROM stock_sale ORDER BY sale_id DESC LIMIT 1");
$stmt->execute();
$lastInvoice = $stmt->fetchColumn();
$nextInvoice = $lastInvoice ? str_pad((int)$lastInvoice + 1, 10, '0', STR_PAD_LEFT) : '0000000001';

$processedVouchers = []; 

foreach($adjustments as $adj) {
    $product_id = $adj['product_id'];
    $variance = $adj['variance'];
    $systemQty = $adj['systemQty'];
    $physicalQty = $adj['physicalQty'];
    
    $stmt = $conn->prepare("SELECT default_sell_price, default_purchase_price FROM variations WHERE product_id=? LIMIT 1");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    if(!$product) continue;

    $sell_price = $product['default_sell_price'];
    $purchase_price = $product['default_purchase_price'];

    $stmt = $conn->prepare("SELECT unit_id, name FROM products WHERE id=? LIMIT 1");
    $stmt->execute([$product_id]);
    $unitData = $stmt->fetch(PDO::FETCH_ASSOC);
    $unit_id = $unitData ? $unitData['unit_id'] : null;
    $product_name = $unitData ? $unitData['name'] : '';

    $stock_after_adjustment = $systemQty - $variance;

    if($variance > 0) {
        $stmt = $conn->prepare("SELECT id FROM contacts WHERE type='customer' AND name='Audit Sale' LIMIT 1");
        $stmt->execute();
        $customer = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!$customer) {
            $conn->prepare("INSERT INTO contacts (type, name) VALUES ('customer', 'Audit Sale')")->execute();
            $customer_id = $conn->lastInsertId();
        } else {
            $customer_id = $customer['id'];
        }

        $stmt = $conn->prepare("INSERT INTO stock_sale (user_id, product_id, invoice, customer_id, product_name, unit, price, sale_qty, total_amount, date_sale) VALUES (?,?,?,?,?,?,?,?,?,NOW())");
        $stmt->execute([
            1,
            $product_id,
            $nextInvoice,
            $customer_id,
            $product_name,
            $unit_id,
            $sell_price,
            $variance,
            $variance * $sell_price
        ]);

        $stmt = $conn->prepare("INSERT INTO audit_adjustments (product_id, product_name, unit_id, variance, adjustment_type, price, qty, voucher_no, stock_after_adjustment) VALUES (?,?,?,?,?,?,?,?,?)");
        $stmt->execute([
            $product_id,
            $product_name,
            $unit_id,
            $variance,
            'sale',
            $sell_price,
            $variance,
            $nextInvoice,
            $stock_after_adjustment
        ]);

        $processedVouchers[] = $nextInvoice;
        $nextInvoice = str_pad((int)$nextInvoice + 1, 10, '0', STR_PAD_LEFT);

    } elseif($variance < 0) {
        $qty = abs($variance);

        $stmt = $conn->prepare("SELECT id FROM contacts WHERE type='supplier' AND name='Audit Purchase' LIMIT 1");
        $stmt->execute();
        $supplier = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!$supplier) {
            $conn->prepare("INSERT INTO contacts (type, name) VALUES ('supplier', 'Audit Purchase')")->execute();
            $supplier_id = $conn->lastInsertId();
        } else {
            $supplier_id = $supplier['id'];
        }

        $stmt = $conn->prepare("INSERT INTO purchase_lines (supplier_id, product_id, quantity, pp_without_discount, purchase_price, sell_price, purchase_date, ref_no, voucher_no) VALUES (?,?,?,?,?,?,NOW(),?,?)");
        $stmt->execute([
            $supplier_id,
            $product_id,
            $qty,
            $purchase_price,
            $purchase_price,
            $sell_price,
            $nextInvoice,
            $nextInvoice
        ]);

        $stmt = $conn->prepare("INSERT INTO audit_adjustments (product_id, product_name, unit_id, variance, adjustment_type, price, qty, voucher_no, stock_after_adjustment) VALUES (?,?,?,?,?,?,?,?,?)");
        $stmt->execute([
            $product_id,
            $product_name,
            $unit_id,
            $variance,
            'purchase',
            $purchase_price,
            $qty,
            $nextInvoice,
            $stock_after_adjustment
        ]);

        $processedVouchers[] = $nextInvoice;
        $nextInvoice = str_pad((int)$nextInvoice + 1, 10, '0', STR_PAD_LEFT);
    }
}

echo implode(", ", $processedVouchers);
