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

$usertype  = (int)($_SESSION["usertype_".$dbname] ?? 0);
$agentcode = (int)($_SESSION["agentcode_".$dbname] ?? 0);

try {

$invno = isset($_POST['invno']) ? (int)$_POST['invno'] : 0;
if ($invno <= 0) {
    echo json_encode(['success'=>false,'message'=>'Invalid invoice no.']);
    exit;
}

$saleRes = mysqli_query($conn, "SELECT s.*, a.name AS custname, a.salesman AS custsalesman
                                 FROM `sale` s
                                 LEFT JOIN `accmast` a ON a.accode = s.customer
                                 WHERE s.`vouchno`='$invno'");
$sale = $saleRes ? mysqli_fetch_assoc($saleRes) : null;
if (!$sale) {
    echo json_encode(['success'=>false,'message'=>'Sale Invoice #'.$invno.' was not found.']);
    exit;
}

// Staff logins may only pull invoices for their own linked customers — same
// restriction the save handler already enforces server-side.
if ($usertype === 3 && $agentcode > 0 && (int)($sale['custsalesman'] ?? 0) !== $agentcode) {
    echo json_encode(['success'=>false,'message'=>'This invoice belongs to a customer not linked to your account.']);
    exit;
}

$trRes = mysqli_query($conn, "SELECT t.*, t.brand AS pbrand, p.name AS prodname
                               FROM `saletr` t
                               LEFT JOIN `product` p ON p.id = t.product
                               WHERE t.`vouchno`='$invno' ORDER BY t.`srl`");
$lines = [];
if ($trRes) while ($r = mysqli_fetch_assoc($trRes)) {
    $lines[] = [
        'product'  => (int)$r['product'],
        'prodname' => $r['prodname'] ?: ($r['description'] ?: ''),
        'brand'    => (int)($r['pbrand'] ?? 0),
        'qty'      => (float)$r['tqty'],
        'cost'     => (float)$r['cost'],
    ];
}

if (ob_get_level() > 0) { ob_clean(); }
echo json_encode([
    'success' => true,
    'header'  => [
        'customer'     => (int)$sale['customer'],
        'customername' => $sale['custname'] ?: '',
        'godown'       => (int)($sale['godown'] ?? 0),
        'salesman'     => (int)($sale['salesman'] ?? 0),
        'vouchdt'      => $sale['vouchdt'] ?? '',
    ],
    'lines' => $lines,
]);

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