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

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

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

$containerno = isset($_POST['containerno']) ? trim($_POST['containerno']) : '';
if ($containerno === '') {
    header('Content-Type: application/json');
    echo json_encode(['ok' => false, 'error' => 'No container specified']);
    exit;
}
$cnEsc = mysqli_real_escape_string($conn, $containerno);

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

// Get LP for this container
$lpRes = mysqli_query($conn, "SELECT `vouchno` FROM `loadingplan` WHERE `containerno`='$cnEsc' LIMIT 1");
if (!$lpRes || mysqli_num_rows($lpRes) == 0) {
    echo json_encode(['ok' => false, 'error' => 'Container not found']);
    exit;
}
$lpRow   = mysqli_fetch_assoc($lpRes);
$lpVouch = (int)$lpRow['vouchno'];

// Get distinct BC voucher numbers from LP lines
$bcNos = [];
$bcRes = mysqli_query($conn, "SELECT DISTINCT lt.bcvouchno, lt.shipmark
        FROM loadingplantr lt
        WHERE lt.vouchno='$lpVouch' AND lt.bcvouchno > 0 ORDER BY lt.srl");
while ($r = mysqli_fetch_assoc($bcRes)) {
    $bcNos[$r['bcvouchno']] = $r['shipmark'];
}

// Purchase upload path for images
$purUp   = upload_path('purchase');
$purDir  = $purUp['dir'];
$purBase = dirname(rtrim($purDir, '/')) . '/';

$rows = [];

foreach ($bcNos as $bcVouch => $shipmark) {
    // Get purchase voucher linked to this BC reference
    $purRes = mysqli_query($conn, "SELECT `vouchno` FROM `purchase` WHERE `billconfref`='$bcVouch' LIMIT 1");
    if (!$purRes || mysqli_num_rows($purRes) == 0) {
        // No linked purchase found — nothing to pull (Bill Confirming lookup removed)
        continue;
    }

    $purRow   = mysqli_fetch_assoc($purRes);
    $purVouch = (int)$purRow['vouchno'];

    // Pull from purchasetr — this has actual images + quantities used for stock
    $trRes = mysqli_query($conn, "SELECT * FROM `purchasetr` WHERE `vouchno`='$purVouch' ORDER BY `srl`");
    while ($tr = mysqli_fetch_assoc($trRes)) {
        $picfile = $tr['picfile'] ?? '';
        $imgSrc  = '';

        // Try purchase upload folder first
        if ($picfile != '') {
            $path = $purDir . $picfile;
            if (!file_exists($path) && is_dir($purBase)) {
                foreach (scandir($purBase) as $sub) {
                    if ($sub === '.' || $sub === '..') continue;
                    $c = $purBase . $sub . '/' . $picfile;
                    if (file_exists($c)) { $path = $c; break; }
                }
            }
            if (file_exists($path)) {
                $ext  = strtolower(pathinfo($path, PATHINFO_EXTENSION));
                $mime = in_array($ext, ['jpg','jpeg']) ? 'image/jpeg' : "image/$ext";
                $imgSrc = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($path));
            }
        }

        // Fallback to BC image if no purchase image
        if (!$imgSrc) {
            $imgSrc = getBcImageSrc($conn, $picfile, $bcVouch, $tr['description'] ?? '');
        }

        $rows[] = [
            'bcvouchno'   => $bcVouch,
            'shipmark'    => $shipmark,
            'description' => $tr['description'] ?? '',
            'picfile'     => $picfile,
            'imgSrc'      => $imgSrc,
            'ctn'         => (float)($tr['ctn']    ?? 0),
            'qty'         => (float)($tr['qty']    ?? 0),
            'tqty'        => (float)($tr['tqty']   ?? 0),
            'cbm'         => (float)($tr['cbm']    ?? 0),
            'weight'      => (float)($tr['weight'] ?? 0),
        ];
    }
}

echo json_encode(['ok' => true, 'rows' => $rows, 'lpvouchno' => $lpVouch]);
