<?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,
           c.contact_person,
           u.full_name AS creator_name
    FROM delivery_notes dn
    LEFT JOIN customers c ON dn.customer_id = c.id
    LEFT JOIN users u     ON dn.created_by  = u.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.description,
           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'));

// Thông tin bên giao cố định
$sender = [
    'company'     => 'CÔNG TY CỔ PHẦN SẢN XUẤT VÀ CUNG ỨNG NTN VIỆT NAM',
    'tax_code'    => '0111343796',
    'address'     => 'Số 36, Xóm Trại, Quan Âm, Xã Phúc Thịnh, TP Hà Nội',
    'rep_name'    => 'Mr Nam',
    'rep_phone'   => '0966459663 / 0966240297',
];
?>
<!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', serif; font-size: 13px; color: #111; background: #fff; }
        .page { padding: 18mm 20mm; max-width: 210mm; margin: 0 auto; }

        /* Header */
        .header-wrap { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
        .company-info { font-size: 11px; line-height: 1.6; }
        .company-info .company-name { font-size: 13px; font-weight: bold; text-transform: uppercase; }
        .company-info .tax { color: #555; }
        .doc-info { text-align: right; font-size: 11px; }
        .doc-info .doc-no { font-size: 14px; font-weight: bold; color: #1a56a0; }

        /* Title */
        .doc-title { text-align: center; margin: 12px 0 4px; }
        .doc-title h1 { font-size: 20px; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; }
        .doc-title .sub { font-size: 12px; color: #555; margin-top: 2px; }
        .doc-title .date-line { font-size: 12px; margin-top: 4px; }

        /* Divider */
        .divider { border: none; border-top: 2px solid #1a56a0; margin: 10px 0; }
        .divider-thin { border: none; border-top: 1px solid #ccc; margin: 8px 0; }

        /* Party section */
        .parties { display: flex; gap: 20px; margin: 10px 0 14px; }
        .party-box { flex: 1; border: 1px solid #d0d7e2; border-radius: 6px; padding: 8px 12px; background: #f8fafd; }
        .party-box .party-title {
            font-weight: bold; font-size: 12px; text-transform: uppercase;
            color: #1a56a0; border-bottom: 1px solid #d0d7e2; padding-bottom: 4px; margin-bottom: 6px;
        }
        .party-box table { width: 100%; font-size: 12px; }
        .party-box table td { padding: 2px 0; vertical-align: top; }
        .party-box table td.label { color: #555; width: 105px; white-space: nowrap; }
        .party-box table td.val { font-weight: 600; }

        /* Transport info */
        .transport-row { display: flex; gap: 10px; margin-bottom: 12px; font-size: 12px; }
        .transport-item { flex: 1; border: 1px solid #e0e6ef; border-radius: 5px; padding: 5px 10px; }
        .transport-item .t-label { color: #666; font-size: 11px; }
        .transport-item .t-val { font-weight: bold; font-size: 13px; }

        /* Table */
        table.items { width: 100%; border-collapse: collapse; margin-bottom: 12px; font-size: 12px; }
        table.items th {
            background: #1a56a0; color: #fff; padding: 6px 8px;
            text-align: center; font-weight: bold; border: 1px solid #1a56a0;
        }
        table.items td { border: 1px solid #bcc8d8; padding: 5px 8px; vertical-align: middle; }
        table.items tbody tr:nth-child(even) td { background: #f0f5fb; }
        .tr { text-align: right; }
        .tc { text-align: center; }
        table.items tfoot td {
            font-weight: bold; background: #eaf0fb;
            border: 1px solid #bcc8d8; padding: 6px 8px;
        }

        /* Total box */
        .total-box { display: flex; justify-content: flex-end; margin-bottom: 14px; }
        .total-inner { border: 2px solid #1a56a0; border-radius: 6px; padding: 8px 16px; text-align: right; min-width: 240px; }
        .total-inner .total-label { font-size: 12px; color: #555; }
        .total-inner .total-amount { font-size: 18px; font-weight: bold; color: #1a56a0; }

        /* Note */
        .note-box { font-size: 12px; color: #444; margin-bottom: 14px; }
        .note-box span { font-weight: bold; }

        /* Signatures */
        .sign-section { display: flex; justify-content: space-between; margin-top: 20px; }
        .sign-col { text-align: center; width: 30%; }
        .sign-col .sign-title { font-weight: bold; font-size: 12px; margin-bottom: 4px; }
        .sign-col .sign-sub { font-size: 11px; color: #666; margin-bottom: 50px; }
        .sign-col .sign-name { font-size: 11px; color: #555; border-top: 1px dashed #aaa; padding-top: 4px; }

        /* Footer */
        .page-footer { margin-top: 16px; font-size: 10px; color: #aaa; text-align: center; border-top: 1px solid #eee; padding-top: 6px; }

        @media print {
            .page { padding: 10mm 12mm; }
            body { font-size: 12px; }
        }
    </style>
</head>
<body onload="window.print()">
<div class="page">

    <!-- ── Header: Logo/Thông tin công ty + Số biên bản ── -->
    <div class="header-wrap">
        <div class="company-info">
            <div class="company-name"><?= $sender['company'] ?></div>
            <div class="tax">MST: <?= $sender['tax_code'] ?></div>
            <div><?= $sender['address'] ?></div>
            <div>Người đại diện: <strong><?= $sender['rep_name'] ?></strong>
                &nbsp;|&nbsp; ĐT: <?= $sender['rep_phone'] ?></div>
        </div>
        <div class="doc-info">
            <div style="font-size:11px; color:#888;">Mã biên bản</div>
            <div class="doc-no"><?= htmlspecialchars($delivery['delivery_no']) ?></div>
            <div style="font-size:11px; margin-top:4px;">
                Ngày: <strong><?= date('d/m/Y', strtotime($delivery['delivery_date'])) ?></strong>
            </div>
        </div>
    </div>

    <hr class="divider">

    <!-- ── Tiêu đề ── -->
    <div class="doc-title">
        <h1>Biên bản giao hàng</h1>
        <div class="sub">DELIVERY NOTE</div>
        <div class="date-line">
            Ngày <?= date('d', strtotime($delivery['delivery_date'])) ?>
            tháng <?= date('m', strtotime($delivery['delivery_date'])) ?>
            năm <?= date('Y', strtotime($delivery['delivery_date'])) ?>
        </div>
    </div>

    <hr class="divider-thin">

    <!-- ── Thông tin hai bên ── -->
    <div class="parties">
        <div class="party-box">
            <div class="party-title">🏭 Bên giao hàng (Bên A)</div>
            <table>
                <tr>
                    <td class="label">Công ty:</td>
                    <td class="val"><?= $sender['company'] ?></td>
                </tr>
                <tr>
                    <td class="label">MST:</td>
                    <td><?= $sender['tax_code'] ?></td>
                </tr>
                <tr>
                    <td class="label">Địa chỉ:</td>
                    <td><?= $sender['address'] ?></td>
                </tr>
                <tr>
                    <td class="label">Người giao hàng:</td>
                    <td class="val"><?= htmlspecialchars($delivery['sender_name'] ?? $sender['rep_name']) ?></td>
                </tr>
                <tr>
                    <td class="label">Người lập phiếu:</td>
                    <td class="val"><?= htmlspecialchars($delivery['creator_name'] ?? $sender['rep_name']) ?></td>
                </tr>
            </table>
        </div>
        <div class="party-box">
            <div class="party-title">🏢 Bên nhận hàng (Bên B)</div>
            <table>
                <tr>
                    <td class="label">Công ty/KH:</td>
                    <td class="val"><?= htmlspecialchars($delivery['customer_name'] ?? '—') ?></td>
                </tr>
                <tr>
                    <td class="label">Mã KH:</td>
                    <td><?= htmlspecialchars($delivery['customer_code'] ?? '—') ?></td>
                </tr>
                <tr>
                    <td class="label">Địa chỉ:</td>
                    <td><?= htmlspecialchars($delivery['address'] ?? '—') ?></td>
                </tr>
                <tr>
                    <td class="label">Người nhận hàng:</td>
                    <td class="val"><?= htmlspecialchars($delivery['contact_person'] ?? $delivery['receiver_name'] ?? '—') ?></td>
                </tr>
                <tr>
                    <td class="label">Điện thoại:</td>
                    <td><?= htmlspecialchars($delivery['phone'] ?? '—') ?></td>
                </tr>
            </table>
        </div>
    </div>

    <!-- ── Thông tin vận chuyển ── -->
    <?php
    $hasTransport = !empty($delivery['vehicle_plate']) || !empty($delivery['driver_name']) || !empty($delivery['driver_phone']);
    if ($hasTransport):
    ?>
    <div class="transport-row">
        <?php if (!empty($delivery['vehicle_plate'])): ?>
        <div class="transport-item">
            <div class="t-label">🚛 Biển số xe</div>
            <div class="t-val"><?= htmlspecialchars($delivery['vehicle_plate']) ?></div>
        </div>
        <?php endif; ?>
        <?php if (!empty($delivery['driver_name'])): ?>
        <div class="transport-item">
            <div class="t-label">👤 Tài xế</div>
            <div class="t-val"><?= htmlspecialchars($delivery['driver_name']) ?></div>
        </div>
        <?php endif; ?>
        <?php if (!empty($delivery['driver_phone'])): ?>
        <div class="transport-item">
            <div class="t-label">📞 SĐT tài xế</div>
            <div class="t-val"><?= htmlspecialchars($delivery['driver_phone']) ?></div>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- ── Bảng chi tiết hàng hóa ── -->
    <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">Cộng:</td>
                <td class="tr"><?= number_format($totalQty) ?></td>
                <td></td>
                <td class="tr"><?= number_format($totalAmount) ?></td>
            </tr>
        </tfoot>
    </table>

    <!-- ── Tổng tiền ── -->
    <div class="total-box">
        <div class="total-inner">
            <div class="total-label">Tổng giá trị hàng hoá</div>
            <div class="total-amount"><?= number_format($totalAmount) ?> đ</div>
        </div>
    </div>

    <!-- ── Ghi chú ── -->
    <?php if (!empty($delivery['note'])): ?>
    <div class="note-box">
        <span>Ghi chú:</span> <?= htmlspecialchars($delivery['note']) ?>
    </div>
    <?php endif; ?>

    <hr class="divider-thin">

    <!-- ── Ký tên ── -->
    <div class="sign-section">
        <div class="sign-col">
            <div class="sign-title">Người giao hàng</div>
            <div class="sign-sub">(Ký, ghi rõ họ tên)</div>
            <div class="sign-name"><?= htmlspecialchars($delivery['sender_name'] ?? $sender['rep_name']) ?></div>
        </div>
        <div class="sign-col">
            <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-name"><?= htmlspecialchars($delivery['contact_person'] ?? $delivery['receiver_name'] ?? '') ?></div>
        </div>
        <div class="sign-col">
            <div class="sign-title">Đại diện công ty</div>
            <div class="sign-sub">(Ký, đóng dấu)</div>
            <div class="sign-name"><?= $sender['rep_name'] ?></div>
        </div>
    </div>

    <div class="page-footer">
        In ngày: <?= date('d/m/Y H:i') ?> &nbsp;|&nbsp;
        <?= $sender['company'] ?> — MST: <?= $sender['tax_code'] ?>
    </div>

</div>
</body>
</html>