<?php
ob_start();
require("dbconnect.php");
require("config.php");
require("function.php");

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

if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_OFF); }

if (!isset($_SESSION["username_".$dbname])) {
    echo json_encode(['success'=>false,'message'=>'Session expired. Please re-login.']);
    exit;
}

$zdb = $_SESSION["zdbyear_".$dbname];
mysqli_select_db($conn, $zdb);

// ── Defensive auto-migrate (keep in sync with saleorder.php / dispatchalert.php) ──
$chk = mysqli_query($conn, "SHOW COLUMNS FROM `saleorder` LIKE 'parentso'");
if ($chk && mysqli_num_rows($chk) == 0)
    mysqli_query($conn, "ALTER TABLE `saleorder` ADD COLUMN `parentso` INT(11) NOT NULL DEFAULT 0");

try {

$vouchno = isset($_GET['vouchno']) ? (int)$_GET['vouchno'] : 0;
if ($vouchno <= 0) {
    echo json_encode(['success'=>false,'message'=>'Invalid sale order.']);
    exit;
}

$soRes = mysqli_query($conn, "SELECT s.*, a.name AS custname, g.name AS godownname
                               FROM `saleorder` s
                               LEFT JOIN `accmast` a ON a.accode = s.customer
                               LEFT JOIN `godown` g ON g.code = s.godown
                               WHERE s.vouchno='$vouchno'");
$so = $soRes ? mysqli_fetch_assoc($soRes) : null;
if (!$so) {
    echo json_encode(['success'=>false,'message'=>'Sale order not found.']);
    exit;
}
$ownGodown = (int)($so['godown'] ?? 0);

// ── Line items — Qty here IS the cap: how much of this product is still
//    sitting on this order's own godown, available to redistribute. ────────
$dtlRes = mysqli_query($conn, "SELECT d.product, d.brand, d.cost, SUM(d.qty) AS qty, p.name AS prodname
                                FROM `saleorderdtl` d
                                LEFT JOIN `product` p ON p.id = d.product
                                WHERE d.vouchno='$vouchno'
                                GROUP BY d.product, d.brand, d.cost, p.name
                                ORDER BY p.name") or die(mysqli_error($conn));
$dtl = [];
while ($r = mysqli_fetch_assoc($dtlRes)) {
    if ((float)$r['qty'] > 0) $dtl[] = $r; // nothing left to split for a zero-qty line
}

if (!$dtl) {
    if (ob_get_level() > 0) { ob_clean(); }
    echo json_encode(['success'=>true, 'so'=>['vouchno'=>$vouchno,'godownname'=>$so['godownname'],'custname'=>$so['custname']], 'lines'=>[], 'godowns'=>[]]);
    exit;
}

$productIds = array_values(array_unique(array_map(function($d){ return (int)$d['product']; }, $dtl)));
$prodInList = implode(',', array_map('intval', $productIds));

// ── Every other godown (all of them — not filtered by stock, so you can
//    still allocate into a godown that's currently showing 0) ──────────────
$godowns = [];
$gRes = mysqli_query($conn, "SELECT `code`,`name` FROM `godown` WHERE `code` != '$ownGodown' ORDER BY `name`");
if ($gRes) while ($r = mysqli_fetch_assoc($gRes)) $godowns[] = $r;

// ── Current stock per product, per other godown — one query per godown,
//    shown as a hint under each allocation input ───────────────────────────
$stockByGodown = []; // [godowncode][product] = qty
if ($prodInList !== '') {
    foreach ($godowns as $g) {
        $gc = (int)$g['code'];
        $stockByGodown[$gc] = [];
        $sRes = mysqli_query($conn, "SELECT `product`, COALESCE(SUM(`qty`),0) AS q FROM `transacn` WHERE `godown`='$gc' AND `product` IN ($prodInList) GROUP BY `product`");
        if ($sRes) while ($r = mysqli_fetch_assoc($sRes)) $stockByGodown[$gc][(int)$r['product']] = (float)$r['q'];
    }
}

$lines = [];
foreach ($dtl as $d) {
    $prod = (int)$d['product'];
    $godownStockMap = [];
    foreach ($godowns as $g) {
        $gc = (int)$g['code'];
        $godownStockMap[$gc] = $stockByGodown[$gc][$prod] ?? 0;
    }
    $lines[] = [
        'product'     => $prod,
        'brand'       => (int)$d['brand'],
        'cost'        => (float)$d['cost'],
        'prodname'    => $d['prodname'] ?: ('Product #'.$prod),
        'qty'         => (float)$d['qty'],
        'godownstock' => $godownStockMap,
    ];
}

if (ob_get_level() > 0) { ob_clean(); }
echo json_encode([
    'success' => true,
    'so'      => ['vouchno'=>(int)$so['vouchno'], 'godownname'=>$so['godownname'] ?: '—', 'custname'=>$so['custname'] ?: ''],
    'lines'   => $lines,
    'godowns' => $godowns,
]);

} catch (\Throwable $e) {
    if (ob_get_level() > 0) { ob_clean(); }
    echo json_encode(['success'=>false, 'message'=>$e->getMessage()]);
}
