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

$accode  = isset($_POST['accode']) ? (int)$_POST['accode'] : 0;
$exclVouch = isset($_POST['exclvouch']) ? (int)$_POST['exclvouch'] : 0;  // current receipt vouchno being edited
$exclSource = isset($_POST['exclsource']) ? trim($_POST['exclsource']) : '';

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

// Confirm this account is a Customer (grpcode 010); if not, no bills to settle
$ares = mysqli_query($conn, "SELECT `grpcode` FROM `accmast` WHERE `accode`='$accode'") or die(mysqli_error($conn));
$arow = mysqli_fetch_assoc($ares);
if (!$arow || $arow['grpcode'] != '010') {
    header('Content-Type: application/json');
    echo json_encode(['ok' => true, 'bills' => []]);
    exit;
}

// Exclude settlements belonging to the receipt currently being edited, so its own
// previously-saved allocations don't double-subtract from the outstanding amount.
$exclcond = '';
if ($exclVouch > 0 && $exclSource != '') {
    $exclSourceEsc = mysqli_real_escape_string($conn, $exclSource);
    $exclcond = " AND NOT (bs.`vouchno`='$exclVouch' AND bs.`source`='$exclSourceEsc')";
}

// Sale Return now settles against a specific invoice the same way a Cash/Bank
// Receipt or Discount Given does — via `billsettle` rows (source='SR'), which
// the `settled` subquery below already aggregates generically (no source
// filter). The second subquery is a LEGACY fallback only, for Sale Return
// vouchers saved before this existed that just have `invno` set with no
// billsettle rows at all — guarded by NOT EXISTS so a return that has since
// been re-saved through the new Bill Settlement grid never gets subtracted
// twice (once via its billsettle rows, once via this legacy invno sum).
$sql = "SELECT s.`vouchno`, s.`vouchdt`, s.`totamt`,
               COALESCE((SELECT SUM(bs.`settleamt`) FROM `billsettle` bs
                         WHERE bs.`saleinvno`=s.`vouchno` $exclcond), 0) AS settled,
               COALESCE((SELECT SUM(sr.`totamt`) FROM `salereturn` sr
                         WHERE sr.`invno`=s.`vouchno`
                           AND NOT EXISTS (SELECT 1 FROM `billsettle` bs2
                                           WHERE bs2.`source`='SR' AND bs2.`vouchno`=sr.`vouchno`)), 0) AS returned
        FROM `sale` s
        WHERE s.`customer`='$accode'
        ORDER BY s.`vouchdt` ASC, s.`vouchno` ASC";
$res = mysqli_query($conn, $sql) or die(mysqli_error($conn));

$bills = [];
while ($row = mysqli_fetch_assoc($res)) {
    $outstanding = (float)$row['totamt'] - (float)$row['settled'] - (float)$row['returned'];
    if ($outstanding <= 0.005) continue;   // fully settled/returned, skip
    $bills[] = [
        'vouchno'     => (int)$row['vouchno'],
        'vouchdt'     => $row['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($row['vouchdt'])) : '',
        'totamt'      => round((float)$row['totamt'], 2),
        'outstanding' => round($outstanding, 2),
    ];
}

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