<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/erp/config/database.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/erp/config/auth.php';
requireLogin();

$pdo = getDBConnection();
$id  = (int)($_GET['id'] ?? 0);
if (!$id) die('Không tìm thấy biên bản');

$delivery = $pdo->prepare("
    SELECT dn.*,
           c.customer_name, c.customer_code, c.address, c.phone
    FROM delivery_notes dn
    LEFT JOIN customers c ON dn.customer_id = c.id
    WHERE dn.id = ?
");
$delivery->execute([$id]);
$delivery = $delivery->fetch(PDO::FETCH_ASSOC);
if (!$delivery) die('Không tìm thấy biên bản');

$items = $pdo->prepare("
    SELECT dni.*,
           pc.product_code,
           pc.unit
    FROM delivery_note_items dni
    JOIN product_codes pc ON dni.product_code_id = pc.id
    WHERE dni.delivery_note_id = ?
    ORDER BY dni.id
");
$items->execute([$id]);
$items = $items->fetchAll(PDO::FETCH_ASSOC);

$totalQty    = array_sum(array_column($items, 'quantity'));
$totalAmount = array_sum(array_column($items, 'total_price'));
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Biên bản giao hàng - <?= htmlspecialchars($delivery['delivery_no']) ?></title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Times New Roman', Times, serif;
            font-size: 13px;
            color: #111;
            background: #fff;
            padding: 18mm 20mm;
        }

        /* ── Header 2 cột ── */
        .doc-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            border-bottom: 2.5px solid #1a237e;
            padding-bottom: 10px;
            margin-bottom: 14px;
        }
        .company-info { flex: 1; padding-right: 20px; }
        .company-name {
            font-size: 14px;
            font-weight: bold;
            text-transform: uppercase;
            color: #1a237e;
            line-height: 1.5;
            margin-bottom: 4px;
        }
        .company-detail {
            font-size: 11.5px;
            color: #333;
            line-height: 1.6;
        }
        .company-detail span { font-weight: bold; color: #111; }

        .doc-meta {
            text-align: right;
            flex-shrink: 0;
            min-width: 190px;
        }
        .doc-meta .doc-title {
            font-size: 20px;
            font-weight: bold;
            text-transform: uppercase;
            color: #1a237e;
            letter-spacing: 1px;
        }
        .doc-meta .doc-no {
            font-size: 12px;
            margin-top: 4px;
            color: #444;
        }
        .doc-meta .doc-no strong { color: #c62828; font-size: 13px; }
        .doc-meta .doc-date {
            font-size: 12px;
            color: #444;
            margin-top: 2px;
        }

        /* ── Khách hàng & vận chuyển ── */
        .section-title {
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
            color: #1a237e;
            border-left: 4px solid #1a237e;
            padding-left: 7px;
            margin: 12px 0 6px;
            letter-spacing: 0.5px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2px 20px;
            font-size: 12.5px;
        }
        .info-row { display: flex; gap: 6px; padding: 2px 0; }
        .info-label {
            font-weight: bold;
            color: #555;
            white-space: nowrap;
            min-width: 110px;
        }
        .info-value { color: #111; }
        .info-full { grid-column: 1 / -1; }

        /* ── Bảng hàng hoá ── */
        .section-items { margin-top: 14px; }

        table.items {
            width: 100%;
            border-collapse: collapse;
            font-size: 12.5px;
        }
        table.items thead tr {
            background: #1a237e;
            color: #fff;
        }
        table.items th {
            padding: 6px 8px;
            text-align: center;
            font-weight: bold;
            border: 1px solid #1a237e;
        }
        table.items td {
            padding: 5px 8px;
            border: 1px solid #ccc;
            vertical-align: middle;
        }
        table.items tbody tr:nth-child(even) { background: #f5f7ff; }
        table.items tbody tr:hover { background: #e8eaf6; }

        .tc { text-align: center; }
        .tr { text-align: right; }

        table.items tfoot tr {
            background: #e8eaf6;
            font-weight: bold;
        }
        table.items tfoot td {
            border: 1px solid #9fa8da;
            padding: 6px 8px;
        }

        /* ── Tổng tiền bằng chữ ── */
        .total-words {
            font-size: 12px;
            font-style: italic;
            color: #333;
            margin-top: 6px;
            padding: 5px 10px;
            background: #f5f7ff;
            border-left: 3px solid #1a237e;
        }

        /* ── Ghi chú ── */
        .note-box {
            margin-top: 10px;
            padding: 6px 10px;
            border: 1px dashed #9fa8da;
            border-radius: 4px;
            font-size: 12px;
            color: #555;
        }
        .note-box strong { color: #1a237e; }

        /* ── Ký tên ── */
        .sign-area {
            display: flex;
            justify-content: space-between;
            margin-top: 36px;
            gap: 10px;
        }
        .sign-box {
            flex: 1;
            text-align: center;
            padding: 0 8px;
        }
        .sign-box .sign-title {
            font-weight: bold;
            font-size: 13px;
            color: #1a237e;
            border-bottom: 1.5px solid #1a237e;
            padding-bottom: 4px;
            margin-bottom: 4px;
        }
        .sign-box .sign-sub {
            font-size: 11px;
            color: #888;
            font-style: italic;
        }
        .sign-box .sign-space { height: 58px; }
        .sign-box .sign-name {
            font-size: 12px;
            font-weight: bold;
            color: #1a237e;
            margin-top: 4px;
        }

        /* ── Footer ── */
        .doc-footer {
            margin-top: 24px;
            padding-top: 8px;
            border-top: 1px solid #ccc;
            font-size: 10.5px;
            color: #999;
            text-align: center;
        }

        @media print {
            body { padding: 10mm 12mm; }
            table.items tbody tr:hover { background: inherit; }
        }
    </style>
</head>
<body onload="window.print()">

    <!-- ══ HEADER ══════════════════════════════════════════════════════ -->
    <div class="doc-header">
        <div class="company-info">
            <div class="company-name">Công ty Cổ phần Sản xuất<br>và Cung ứng NTN Việt Nam</div>
            <div class="company-detail">
                <span>MST:</span> 0111343796<br>
                <span>Địa chỉ:</span> Số 36, Xóm Trại, Quan Âm, Xã Phúc Thịnh, TP. Hà Nội<br>
                <span>Đại diện:</span> Mr. Nam &nbsp;|&nbsp;
                <span>ĐT:</span> 0966.459.663 &nbsp;–&nbsp; 0966.240.297
            </div>
        </div>
        <div class="doc-meta">
            <div class="doc-title">Biên bản<br>giao hàng</div>
            <div class="doc-no">Số: <strong><?= htmlspecialchars($delivery['delivery_no']) ?></strong></div>
            <div class="doc-date">Ngày: <strong><?= date('d/m/Y', strtotime($delivery['delivery_date'])) ?></strong></div>
        </div>
    </div>

    <!-- ══ THÔNG TIN KHÁCH HÀNG ════════════════════════════════════════ -->
    <div class="section-title">Bên nhận hàng (Bên B)</div>
    <div class="info-grid">
        <div class="info-row">
            <span class="info-label">Khách hàng:</span>
            <span class="info-value"><strong><?= htmlspecialchars($delivery['customer_name'] ?? '—') ?></strong></span>
        </div>
        <div class="info-row">
            <span class="info-label">Mã khách hàng:</span>
            <span class="info-value"><?= htmlspecialchars($delivery['customer_code'] ?? '—') ?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Điện thoại:</span>
            <span class="info-value"><?= htmlspecialchars($delivery['phone'] ?? '—') ?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Người nhận:</span>
            <span class="info-value"><?= htmlspecialchars($delivery['sender_name'] ?? '—') ?></span>
        </div>
        <div class="info-row info-full">
            <span class="info-label">Địa chỉ giao:</span>
            <span class="info-value"><?= htmlspecialchars($delivery['address'] ?? '—') ?></span>
        </div>
    </div>

    <!-- ══ THÔNG TIN VẬN CHUYỂN ════════════════════════════════════════ -->
    <?php if (!empty($delivery['vehicle_plate']) || !empty($delivery['driver_name'])): ?>
    <div class="section-title">Thông tin vận chuyển</div>
    <div class="info-grid">
        <div class="info-row">
            <span class="info-label">Biển số xe:</span>
            <span class="info-value"><?= htmlspecialchars($delivery['vehicle_plate'] ?? '—') ?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Tài xế:</span>
            <span class="info-value"><?= htmlspecialchars($delivery['driver_name'] ?? '—') ?></span>
        </div>
    </div>
    <?php endif; ?>

    <!-- ══ BẢNG HÀNG HOÁ ═══════════════════════════════════════════════ -->
    <div class="section-title section-items">Danh sách hàng hoá</div>
    <table class="items">
        <thead>
            <tr>
                <th width="30">STT</th>
                <th width="90">Mã SP</th>
                <th>Tên hàng hoá / Mô tả</th>
                <th width="55">ĐVT</th>
                <th width="80">Số lượng</th>
                <th width="110">Đơn giá (đ)</th>
                <th width="120">Thành tiền (đ)</th>
            </tr>
        </thead>
        <tbody>
        <?php $i = 1; foreach ($items as $it): ?>
        <tr>
            <td class="tc"><?= $i++ ?></td>
            <td class="tc"><strong><?= htmlspecialchars($it['product_code']) ?></strong></td>
            <td><?= htmlspecialchars($it['description']) ?></td>
            <td class="tc"><?= htmlspecialchars($it['unit']) ?></td>
            <td class="tr"><?= number_format($it['quantity']) ?></td>
            <td class="tr"><?= number_format($it['unit_price'] ?? 0) ?></td>
            <td class="tr"><?= number_format($it['total_price'] ?? 0) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="4" class="tr" style="color:#1a237e;">Tổng cộng:</td>
                <td class="tr"><?= number_format($totalQty) ?></td>
                <td></td>
                <td class="tr" style="color:#c62828;"><?= number_format($totalAmount) ?> đ</td>
            </tr>
        </tfoot>
    </table>

    <?php if ($totalAmount > 0): ?>
    <div class="total-words">
        Tổng tiền thanh toán:
        <strong style="color:#c62828;"><?= number_format($totalAmount) ?> đồng</strong>
    </div>
    <?php endif; ?>

    <!-- ══ GHI CHÚ ═════════════════════════════════════════════════════ -->
    <?php if (!empty($delivery['note'])): ?>
    <div class="note-box">
        <strong>Ghi chú:</strong> <?= nl2br(htmlspecialchars($delivery['note'])) ?>
    </div>
    <?php endif; ?>

    <!-- ══ KÝ TÊN ══════════════════════════════════════════════════════ -->
    <div class="sign-area">
        <div class="sign-box">
            <div class="sign-title">Người giao hàng</div>
            <div class="sign-sub">(Ký, ghi rõ họ tên)</div>
            <div class="sign-space"></div>
            <div class="sign-name"><?= htmlspecialchars($delivery['sender_name'] ?? '') ?></div>
        </div>
        <div class="sign-box">
            <div class="sign-title">Người nhận hàng</div>
            <div class="sign-sub">(Ký, ghi rõ họ tên)</div>
            <div class="sign-space"></div>
            <div class="sign-name">&nbsp;</div>
        </div>
        <div class="sign-box">
            <div class="sign-title">Đại diện Công ty</div>
            <div class="sign-sub">(Ký, đóng dấu)</div>
            <div class="sign-space"></div>
            <div class="sign-name">Mr. Nam</div>
        </div>
    </div>

    <!-- ══ FOOTER ══════════════════════════════════════════════════════ -->
    <div class="doc-footer">
        Công ty Cổ phần SX &amp; Cung ứng NTN Việt Nam &nbsp;·&nbsp; MST: 0111343796
        &nbsp;·&nbsp; In ngày: <?= date('d/m/Y H:i') ?>
    </div>

</body>
</html>