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

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

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);

// ── Ensure transacn table exists ───────────────────────────────────────────
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `transacn` (
    `srl` INT(11) NOT NULL AUTO_INCREMENT,
    `vouchdt` DATE NULL,
    `source` VARCHAR(10) NOT NULL DEFAULT '',
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `godown` INT(11) NOT NULL DEFAULT 0,
    `product` INT(11) NOT NULL DEFAULT 0,
    `qty` DOUBLE NOT NULL DEFAULT 0,
    `cost` DOUBLE NOT NULL DEFAULT 0,
    `adduser` VARCHAR(50) NOT NULL DEFAULT '',
    `adddate` DATE NULL,
    `addtime` TIME NULL,
    PRIMARY KEY (`srl`),
    KEY `vouchno` (`vouchno`),
    KEY `product` (`product`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$product = (int)($_POST['product'] ?? 0);
$godown  = (int)($_POST['godown'] ?? 0);

if ($godown <= 0) {
    echo json_encode(['success'=>false, 'message'=>'Please select a Godown first.', 'qty'=>0]);
    exit;
}

$qty = 0;
if ($product > 0) {
    $sql = "SELECT COALESCE(SUM(`qty`),0) AS q FROM `transacn` WHERE `product`='$product' AND `godown`='$godown'";
    $r = mysqli_query($conn, $sql);
    if ($r) {
        $row = mysqli_fetch_assoc($r);
        $qty = (float)$row['q'];
    }
}

echo json_encode(['success'=>true, 'qty'=>$qty]);
