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

if (!isset($_SESSION["username_" . $dbname])) {
    header('Content-Type: application/json');
    echo json_encode(['ok' => false, 'error' => 'Not authenticated']);
    exit;
}

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

$godown    = isset($_POST['godown']) ? (int)$_POST['godown'] : 0;
$exclVouch = isset($_POST['exclvouch'])  ? (int)$_POST['exclvouch']           : 0;
$exclSource= isset($_POST['exclsource']) ? trim($_POST['exclsource'])          : '';

if ($godown <= 0) {
    header('Content-Type: application/json');
    echo json_encode(['ok' => true, 'stock' => []]);
    exit;
}

$exclcond = '';
if ($exclVouch > 0 && $exclSource != '') {
    $exclSourceEsc = mysqli_real_escape_string($conn, $exclSource);
    $exclcond = " AND NOT (`source`='$exclSourceEsc' AND `vouchno`='$exclVouch')";
}

$sql = "SELECT sl.`customer`, sl.`supplier`, sl.`description`, sl.`modelno`, sl.`marka`,
               c.`name` AS customername, s.`name` AS suppliername,
               SUM(sl.`ctn`)     AS bal,
               SUM(sl.`ctn`)     AS totctn,
               SUM(sl.`tcbm`)    AS tottcbm,
               SUM(sl.`tweight`) AS tottweight
        FROM `stockledger` sl
        LEFT JOIN `accmast` c ON c.accode = sl.customer
        LEFT JOIN `accmast` s ON s.accode = sl.supplier
        WHERE sl.`godown`='$godown' $exclcond
        GROUP BY sl.`customer`, sl.`supplier`, sl.`description`, sl.`modelno`, sl.`marka`
        HAVING bal > 0.005
        ORDER BY sl.`description` ASC";
$res = mysqli_query($conn, $sql) or die(mysqli_error($conn));

$stock = [];
while ($row = mysqli_fetch_assoc($res)) {
    $stock[] = [
        'customer'     => (int)$row['customer'],
        'supplier'     => (int)$row['supplier'],
        'customername' => $row['customername'] ?? '',
        'suppliername' => $row['suppliername'] ?? '',
        'description'  => $row['description'],
        'modelno'      => $row['modelno'],
        'marka'        => $row['marka'],
        'balance'      => round((float)$row['bal'], 2),
        'totctn'       => round((float)$row['totctn'], 2),
        'tottcbm'      => round((float)$row['tottcbm'], 4),
        'tottweight'   => round((float)$row['tottweight'], 2),
    ];
}

header('Content-Type: application/json');
echo json_encode(['ok' => true, 'stock' => $stock]);
