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

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

$vouchno = isset($_GET['vouchno']) ? (int)$_GET['vouchno'] : 0;

// Fetch despatch header
$dsp = [];
$dr  = mysqli_query($conn, "SELECT * FROM `despatch` WHERE `vouchno`='$vouchno'");
if ($dr) $dsp = mysqli_fetch_assoc($dr) ?: [];

$containerno = $dsp['containerno'] ?? '';
$cnEsc = mysqli_real_escape_string($conn, $containerno);

// Company name
$compRes  = mysqli_query($conn, "SELECT `name` FROM `$dbname`.`company` WHERE `code`='$compcd'");
$compName = ($compRes && ($cr = mysqli_fetch_assoc($compRes))) ? $cr['name'] : '';

// Shipper/Agent name via loadingplan
$shipperName = '';
$lpRes = mysqli_query($conn, "SELECT a.name AS sname FROM loadingplan lp LEFT JOIN accmast a ON a.accode=lp.shipper WHERE lp.containerno='$cnEsc' LIMIT 1");
if ($lpRes && ($lr = mysqli_fetch_assoc($lpRes))) $shipperName = $lr['sname'] ?? '';

// Get all BC voucher numbers in this container's loading plan
$bcNos = [];
$bcRes = mysqli_query($conn, "SELECT DISTINCT lt.bcvouchno FROM loadingplantr lt INNER JOIN loadingplan lp ON lp.vouchno=lt.vouchno WHERE lp.containerno='$cnEsc' AND lt.bcvouchno>0");
while ($r = mysqli_fetch_assoc($bcRes)) $bcNos[] = (int)$r['bcvouchno'];

// Get all purchase vouchers linked to these BCs
$purNos = [];
if ($bcNos) {
    $bcIn = implode(',', $bcNos);
    $purRes = mysqli_query($conn, "SELECT vouchno FROM purchase WHERE billconfref IN ($bcIn)");
    while ($r = mysqli_fetch_assoc($purRes)) $purNos[] = (int)$r['vouchno'];
}

// Build grouped data: customer → [rows]
// Each row = purchase header + purchasetr line
$grouped = []; // [custname => ['custname'=>,'shipmarka'=>,'rows'=>[]]]
$purUp = upload_path('purchase');
$purDir = $purUp['dir'];
$purBase = dirname(rtrim($purDir,'/')) . '/';

if ($purNos) {
    $purIn = implode(',', $purNos);
    $rows = mysqli_query($conn,
        "SELECT p.vouchno, p.vouchdt, p.supplier, p.customer, p.shipmarka, p.godown,
                c.name AS custname, s.name AS supname,
                pt.srl, pt.picfile, pt.description, pt.modelno, pt.calby,
                pt.ctn, pt.qty, pt.tqty, pt.rate, pt.amt,
                pt.cbm, pt.tcbm, pt.weight, pt.tweight
         FROM purchase p
         LEFT JOIN accmast c ON c.accode = p.customer
         LEFT JOIN accmast s ON s.accode = p.supplier
         INNER JOIN purchasetr pt ON pt.vouchno = p.vouchno
         WHERE p.vouchno IN ($purIn)
         ORDER BY c.name ASC, p.vouchno ASC, pt.srl ASC");
    while ($r = mysqli_fetch_assoc($rows)) {
        $ckey = $r['custname'] ?: 'Unknown';
        if (!isset($grouped[$ckey])) {
            $grouped[$ckey] = ['custname'=>$ckey,'shipmarka'=>$r['shipmarka'],'rows'=>[]];
        }
        // Resolve image
        $imgSrc = '';
        if (!empty($r['picfile'])) {
            // Try purchase upload folder
            $path = $purDir . $r['picfile'];
            if (!file_exists($path) && is_dir($purBase)) {
                foreach (scandir($purBase) as $sub) {
                    if ($sub==='.'||$sub==='..') continue;
                    $c = $purBase.$sub.'/'.$r['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: try BC image
        if (!$imgSrc) {
            // Find BC voucher for this purchase
            $bcv = 0;
            $bvr = mysqli_query($conn,"SELECT billconfref FROM purchase WHERE vouchno='{$r['vouchno']}' LIMIT 1");
            if ($bvr && ($bvrow=mysqli_fetch_assoc($bvr))) $bcv = (int)$bvrow['billconfref'];
            if ($bcv) $imgSrc = getBcImageSrc($conn, $r['picfile']??'', $bcv, $r['description']??'');
        }
        $r['imgSrc'] = $imgSrc;
        $grouped[$ckey]['rows'][] = $r;
    }
}

$dspDt = (!empty($dsp['vouchdt'])&&$dsp['vouchdt']!='0000-00-00') ? date('d-m-Y',strtotime($dsp['vouchdt'])) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Packing List — DSP#<?php echo $vouchno; ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:Arial,sans-serif;font-size:11px;color:#000;background:#fff;padding:12px 16px;}
h2{text-align:center;font-size:15px;margin-bottom:2px;}
h3{text-align:center;font-size:12px;font-weight:600;color:#374151;margin-bottom:10px;}
.meta{display:flex;justify-content:space-between;margin-bottom:10px;flex-wrap:wrap;gap:8px;}
.meta-block{font-size:11px;}
.meta-block b{color:#1e293b;}

/* Customer section */
.cust-section{margin-bottom:16px;}
.cust-header{background:#1e3a5f;color:#fff;font-size:11.5px;font-weight:700;padding:6px 10px;letter-spacing:.04em;text-transform:uppercase;}
.cust-marker{background:#dbeafe;color:#1e40af;font-size:10.5px;font-weight:600;padding:3px 10px;}

table{width:100%;border-collapse:collapse;}
thead th{background:#374151;color:#fff;padding:6px 5px;font-size:9.5px;text-transform:uppercase;letter-spacing:.03em;border:1px solid #555;text-align:center;white-space:nowrap;}
tbody td{border:1px solid #d1d5db;padding:4px 5px;vertical-align:middle;font-size:10.5px;}
tbody tr:nth-child(even){background:#f9fafb;}
tfoot td{font-weight:700;background:#f1f5f9;border:1px solid #9ca3af;padding:5px 5px;font-size:11px;}
.num{text-align:right;}
.ctr{text-align:center;}
img.pic{width:48px;height:48px;object-fit:cover;border-radius:3px;display:block;margin:0 auto;}
.no-img{width:48px;height:48px;background:#f3f4f6;border:1px dashed #d1d5db;border-radius:3px;display:flex;align-items:center;justify-content:center;font-size:8px;color:#9ca3af;margin:0 auto;text-align:center;}
.grand-total{margin-top:12px;background:#1e3a5f;color:#fff;padding:8px 14px;border-radius:6px;display:flex;gap:24px;flex-wrap:wrap;}
.gt-item{font-size:11px;} .gt-item b{font-size:13px;}
@media print{
    body{padding:6px;}
    .no-print{display:none;}
    @page{size:A3 landscape;margin:10mm;}
}
</style>
</head>
<body>

<h2><?php echo htmlspecialchars($compName); ?></h2>
<h3>PACKING LIST</h3>

<div class="meta">
    <div class="meta-block">
        <b>Despatch No:</b> DSP#<?php echo $vouchno; ?><br>
        <b>Despatch Date:</b> <?php echo $dspDt; ?><br>
        <b>Container No:</b> <?php echo htmlspecialchars($containerno); ?>
    </div>
    <div class="meta-block" style="text-align:right;">
        <b>Shipper / Agent:</b> <?php echo htmlspecialchars($shipperName); ?><br>
        <?php if (!empty($dsp['remarks'])): ?><b>Remarks:</b> <?php echo htmlspecialchars($dsp['remarks']); ?><?php endif; ?>
    </div>
</div>

<?php if (!$grouped): ?>
<p style="color:#94a3b8;text-align:center;padding:30px;">No purchase data linked to this container.</p>
<?php else: ?>

<?php
$grandCtn=$grandQty=$grandTqty=$grandAmt=$grandCbm=$grandTcbm=$grandWt=$grandTwt=0;
foreach ($grouped as $ckey => $cg):
    $cCtn=$cQty=$cTqty=$cAmt=$cCbm=$cTcbm=$cWt=$cTwt=0;
    foreach ($cg['rows'] as $r) {
        $cCtn+=(float)$r['ctn']; $cQty+=(float)$r['qty']; $cTqty+=(float)$r['tqty'];
        $cAmt+=(float)$r['amt']; $cCbm+=(float)$r['cbm']; $cTcbm+=(float)$r['tcbm'];
        $cWt+=(float)$r['weight']; $cTwt+=(float)$r['tweight'];
    }
    $grandCtn+=$cCtn; $grandQty+=$cQty; $grandTqty+=$cTqty;
    $grandAmt+=$cAmt; $grandCbm+=$cCbm; $grandTcbm+=$cTcbm;
    $grandWt+=$cWt;   $grandTwt+=$cTwt;
?>
<div class="cust-section">
    <div class="cust-header"><?php echo htmlspecialchars($ckey); ?></div>
    <?php if (!empty($cg['shipmarka'])): ?>
    <div class="cust-marker">MARKER: <?php echo htmlspecialchars($cg['shipmarka']); ?></div>
    <?php endif; ?>
    <table>
        <thead>
            <tr>
                <th style="width:54px;">IMAGE</th>
                <th style="text-align:left;width:80px;">MARKER</th>
                <th style="text-align:left;width:100px;">PARTICULAR</th>
                <th style="text-align:left;">DESCRIPTION</th>
                <th style="width:38px;">CTN</th>
                <th style="width:42px;">QTY</th>
                <th style="width:46px;">T.QTY</th>
                <th style="width:36px;">UNIT</th>
                <th style="width:58px;">PRICE</th>
                <th style="width:64px;">AMOUNT</th>
                <th style="width:46px;">CBM</th>
                <th style="width:50px;">T.CBM</th>
                <th style="width:50px;">WEIGHT</th>
                <th style="width:54px;">T.WEIGHT</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($cg['rows'] as $ri => $r): ?>
        <tr>
            <td class="ctr">
                <?php if ($r['imgSrc']): ?>
                <img class="pic" src="<?php echo $r['imgSrc']; ?>">
                <?php else: ?>
                <div class="no-img">NO IMG</div>
                <?php endif; ?>
            </td>
            <td><?php echo htmlspecialchars($r['shipmarka']); ?></td>
            <td><?php echo htmlspecialchars($r['modelno']); ?></td>
            <td><?php echo htmlspecialchars($r['description']); ?></td>
            <td class="num"><?php echo $r['ctn']?number_format((float)$r['ctn'],0):''; ?></td>
            <td class="num"><?php echo $r['qty']?number_format((float)$r['qty'],0):''; ?></td>
            <td class="num"><?php echo $r['tqty']?number_format((float)$r['tqty'],0):''; ?></td>
            <td class="ctr">PCS</td>
            <td class="num"><?php echo $r['rate']?'¥'.number_format((float)$r['rate'],2):''; ?></td>
            <td class="num"><?php echo $r['amt']?'¥'.number_format((float)$r['amt'],2):''; ?></td>
            <td class="num"><?php echo $r['cbm']?number_format((float)$r['cbm'],4):''; ?></td>
            <td class="num"><?php echo $r['tcbm']?number_format((float)$r['tcbm'],4):''; ?></td>
            <td class="num"><?php echo $r['weight']?number_format((float)$r['weight'],3):''; ?></td>
            <td class="num"><?php echo $r['tweight']?number_format((float)$r['tweight'],3):''; ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="4" class="num">Sub-Total (<?php echo $ckey; ?>)</td>
                <td class="num"><?php echo number_format($cCtn,0); ?></td>
                <td class="num"><?php echo number_format($cQty,0); ?></td>
                <td class="num"><?php echo number_format($cTqty,0); ?></td>
                <td></td>
                <td></td>
                <td class="num">¥<?php echo number_format($cAmt,2); ?></td>
                <td class="num"><?php echo number_format($cCbm,4); ?></td>
                <td class="num"><?php echo number_format($cTcbm,4); ?></td>
                <td class="num"><?php echo number_format($cWt,3); ?></td>
                <td class="num"><?php echo number_format($cTwt,3); ?></td>
            </tr>
        </tfoot>
    </table>
</div>
<?php endforeach; ?>

<div class="grand-total">
    <div class="gt-item">GRAND TOTAL &nbsp; CTN: <b><?php echo number_format($grandCtn,0); ?></b></div>
    <div class="gt-item">T.QTY: <b><?php echo number_format($grandTqty,0); ?></b></div>
    <div class="gt-item">AMOUNT: <b>¥<?php echo number_format($grandAmt,2); ?></b></div>
    <div class="gt-item">T.CBM: <b><?php echo number_format($grandTcbm,4); ?></b></div>
    <div class="gt-item">T.WEIGHT: <b><?php echo number_format($grandTwt,3); ?></b></div>
</div>

<?php endif; ?>

<div class="no-print" style="margin-top:16px;text-align:center;">
    <button onclick="window.print()" style="padding:8px 22px;border:none;border-radius:6px;background:#1e293b;color:#fff;cursor:pointer;font-size:13px;font-weight:600;">
        🖨 Print
    </button>
</div>
</body>
</html>
