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

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

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

$result = mysqli_query($conn,
    "SELECT s.*, c.name AS customername
     FROM `sale` s
     LEFT JOIN `accmast` c ON c.accode = s.customer
     WHERE s.vouchno='$vouchno'") or die(mysqli_error($conn));
$get = mysqli_fetch_array($result);
if (!$get) $get = [];

$tres = mysqli_query($conn, "SELECT * FROM `saletr` WHERE `vouchno`='$vouchno' ORDER BY `srl`") or die(mysqli_error($conn));
$lines = [];
while ($r = mysqli_fetch_array($tres)) { $lines[] = $r; }

$eres = mysqli_query($conn, "SELECT e.*, x.`name` AS expname FROM `saleexp` e LEFT JOIN `accmast` x ON x.accode = e.expense WHERE e.`vouchno`='$vouchno' ORDER BY e.`srl`") or die(mysqli_error($conn));
$expLines = [];
while ($r = mysqli_fetch_array($eres)) { $expLines[] = $r; }

$compres = mysqli_query($conn, "SELECT `name` FROM $zdbroot.`company` WHERE `code`='$compcd'");
$comprow = $compres ? mysqli_fetch_assoc($compres) : null;
$compname = $comprow ? $comprow['name'] : '';

$vouchdt_disp = (!empty($get['vouchdt']) && $get['vouchdt'] != '0000-00-00') ? date('d-m-Y', strtotime($get['vouchdt'])) : '';

require_once("includes/upload_path.php");
$uploadurl = upload_path('sale')['url'];

function pf($v) {
    if ($v === null || $v === '') return '';
    $v = (float)$v;
    return $v == 0 ? '' : (($v == (int)$v) ? (string)(int)$v : number_format($v, 2));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sale Invoice - <?php echo $vouchno; ?></title>
<style>
    body { font-family: Arial, sans-serif; font-size:13px; color:#1e293b; margin:20px; }
    h2 { text-align:center; margin:0 0 4px; }
    .sub { text-align:center; color:#64748b; margin-bottom:16px; }
    table { width:100%; border-collapse:collapse; margin-top:10px; }
    th, td { border:1px solid #cbd5e1; padding:6px 8px; font-size:11.5px; }
    th { background:#f1f5f9; text-align:center; }
    td.num { text-align:right; }
    .hdr-table td { border:none; padding:3px 6px; font-size:12.5px; }
    .hdr-label { color:#64748b; font-weight:600; width:120px; }
    tfoot td { font-weight:700; background:#f8fafc; }
    .pic-thumb { width:42px; height:42px; object-fit:cover; border-radius:4px; border:1px solid #cbd5e1; }
    .sec-title { margin-top:18px; font-weight:700; font-size:12.5px; color:#374151; }
    @media print { .no-print { display:none; } }
</style>
</head>
<body>
    <h2><?php echo htmlspecialchars($compname); ?></h2>
    <div class="sub">Sale</div>

    <table class="hdr-table">
        <tr>
            <td class="hdr-label">Voucher No</td><td><?php echo $vouchno; ?></td>
            <td class="hdr-label">Date</td><td><?php echo htmlspecialchars($vouchdt_disp); ?></td>
        </tr>
        <tr>
            <td class="hdr-label">Customer</td><td><?php echo htmlspecialchars($get['customername'] ?? ''); ?></td>
            <td class="hdr-label">Ship Marka</td><td><?php echo htmlspecialchars($get['shipmarka'] ?? ''); ?></td>
        </tr>
        <tr>
            <td class="hdr-label">Remarks</td><td colspan="3"><?php echo htmlspecialchars($get['remarks'] ?? ''); ?></td>
        </tr>
    </table>

    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Pic</th>
                <th>Description</th>
                <th>Model No.</th>
                <th>Marka</th>
                <th>CTN</th>
                <th>QTY</th>
                <th>T.QTY</th>
                <th>Rate</th>
                <th>T.Amount</th>
                <th>CBM</th>
                <th>T.CBM</th>
                <th>Weight</th>
                <th>T.Weight</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($lines as $i => $ln): ?>
            <tr>
                <td style="text-align:center;"><?php echo $i + 1; ?></td>
                <td style="text-align:center;">
                    <?php if (!empty($ln['picfile'])): ?>
                    <img class="pic-thumb" src="<?php echo $uploadurl . htmlspecialchars($ln['picfile']); ?>" alt="">
                    <?php endif; ?>
                </td>
                <td><?php echo htmlspecialchars($ln['description']); ?></td>
                <td><?php echo htmlspecialchars($ln['modelno']); ?></td>
                <td><?php echo htmlspecialchars($ln['marka']); ?></td>
                <td class="num"><?php echo pf($ln['ctn']); ?></td>
                <td class="num"><?php echo pf($ln['qty']); ?></td>
                <td class="num"><?php echo pf($ln['tqty']); ?></td>
                <td class="num"><?php echo pf($ln['rate']); ?></td>
                <td class="num"><?php echo pf($ln['amt']); ?></td>
                <td class="num"><?php echo pf($ln['cbm']); ?></td>
                <td class="num"><?php echo pf($ln['tcbm']); ?></td>
                <td class="num"><?php echo pf($ln['weight']); ?></td>
                <td class="num"><?php echo pf($ln['tweight']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5" style="text-align:right;">Total</td>
                <td class="num"><?php echo pf($get['totctn'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['totqty'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['tottqty'] ?? 0); ?></td>
                <td></td>
                <td class="num"><?php echo pf($get['totamt'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['totcbm'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['tottcbm'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['totweight'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['tottweight'] ?? 0); ?></td>
            </tr>
        </tfoot>
    </table>

    <?php if (count($expLines) > 0): ?>
    <div class="sec-title">Expense Allocation</div>
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Expense Account</th>
                <th>Amount</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($expLines as $i => $el): ?>
            <tr>
                <td style="text-align:center;"><?php echo $i + 1; ?></td>
                <td><?php echo htmlspecialchars($el['expname'] ?? ''); ?></td>
                <td class="num"><?php echo pf($el['expamt']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2" style="text-align:right;">Total Expense</td>
                <td class="num"><?php echo pf($get['totexpamt'] ?? 0); ?></td>
            </tr>
        </tfoot>
    </table>
    <?php endif; ?>

    <div class="no-print" style="margin-top:16px;text-align:center;">
        <button onclick="window.print()" style="padding:8px 18px;border:none;border-radius:6px;background:#2563eb;color:#fff;cursor:pointer;">Print</button>
    </div>
</body>
</html>
