<?php
// Đặt lệnh header duy nhất ở đây
header('Content-Type: text/html; charset=utf-8');

require_once __DIR__ . '/../../core/init.php';

// ===================================================================
// HÀM ĐỔI SỐ THÀNH CHỮ
// ===================================================================
if (!function_exists('convert_number_to_words_vietnamese')) {
    function convert_number_to_words_vietnamese($number) {
        $hyphen      = ' '; $conjunction = ' '; $separator   = ' ';
        $negative    = 'âm '; $decimal     = ' phẩy ';
        $dictionary  = array(
            0 => 'không', 1 => 'một', 2 => 'hai', 3 => 'ba', 4 => 'bốn', 5 => 'năm', 6 => 'sáu', 7 => 'bảy', 8 => 'tám', 9 => 'chín',
            10 => 'mười', 11 => 'mười một', 12 => 'mười hai', 13 => 'mười ba', 14 => 'mười bốn', 15 => 'mười lăm', 16 => 'mười sáu', 17 => 'mười bảy', 18 => 'mười tám', 19 => 'mười chín',
            20 => 'hai mươi', 30 => 'ba mươi', 40 => 'bốn mươi', 50 => 'năm mươi', 60 => 'sáu mươi', 70 => 'bảy mươi', 80 => 'tám mươi', 90 => 'chín mươi',
            100 => 'trăm', 1000 => 'nghìn', 1000000 => 'triệu', 1000000000 => 'tỷ', 1000000000000 => 'nghìn tỷ',
        );

        if (!is_numeric($number)) { return false; }
        if ($number < 0) { return $negative . convert_number_to_words_vietnamese(abs($number)); }
        $string = $fraction = null;
        if (strpos($number, '.') !== false) { list($number, $fraction) = explode('.', $number); }
        switch (true) {
            case $number < 21: $string = $dictionary[$number]; break;
            case $number < 100:
                $tens   = ((int) ($number / 10)) * 10; $units  = $number % 10;
                $string = $dictionary[$tens];
                if ($units) {
                    if ($units == 1) { $string .= $hyphen . 'mốt'; } else if ($units == 5) { $string .= $hyphen . 'lăm'; } else { $string .= $hyphen . $dictionary[$units]; }
                }
                break;
            case $number < 1000:
                $hundreds  = $number / 100; $remainder = $number % 100;
                $string = $dictionary[(int)$hundreds] . ' ' . $dictionary[100];
                if ($remainder) {
                    if ($remainder < 10) { $string .= $conjunction . 'linh ' . $dictionary[$remainder]; } else { $string .= $conjunction . convert_number_to_words_vietnamese($remainder); }
                }
                break;
            default:
                $baseUnit = pow(1000, floor(log($number, 1000))); $numBaseUnits = (int) ($number / $baseUnit);
                $remainder = $number % $baseUnit;
                $string = convert_number_to_words_vietnamese($numBaseUnits) . ' ' . $dictionary[$baseUnit];
                if ($remainder) {
                    if ($remainder < 100) { $string .= $conjunction . 'không trăm ' . convert_number_to_words_vietnamese($remainder); } else { $string .= $separator . convert_number_to_words_vietnamese($remainder); }
                }
                break;
        }
        if (null !== $fraction && is_numeric($fraction)) {
            $string .= $decimal; $words = array();
            foreach (str_split((string) $fraction) as $number) { $words[] = $dictionary[$number]; }
            $string .= implode(' ', $words);
        }
        return ucfirst($string) . ' đồng chẵn.';
    }
}

// ===================================================================
// PHẦN LOGIC LẤY DỮ LIỆU (giữ nguyên như cũ)
// ===================================================================

if (empty($_GET['code'])) { die('Không tìm thấy mã phiếu tổng hợp.'); }
$consolidated_code = $_GET['code'];
$orders_in_slip = [];
$stmt_orders = $conn->prepare("
    SELECT o.id, o.output_code, o.total_quantity, o.total_money, o.sell_date, o.detail_order,
           c.customer_name, c.customer_addr, c.notes AS customer_tax_code
    FROM cms_orders AS o
    LEFT JOIN cms_customers AS c ON o.customer_id = c.id
    WHERE o.consolidated_code = ? 
    ORDER BY o.id ASC
");
$stmt_orders->bind_param('s', $consolidated_code);
$stmt_orders->execute();
$result_orders = $stmt_orders->get_result();
while($row = $result_orders->fetch_assoc()) { $orders_in_slip[] = $row; }
if (empty($orders_in_slip)) { die('Mã phiếu không hợp lệ hoặc không có đơn hàng nào.'); }
$delivery_date_display = date('d/m/Y', strtotime($orders_in_slip[0]['sell_date']));
$all_product_ids = [];
foreach ($orders_in_slip as $order) {
    $details = json_decode($order['detail_order'], true);
    if (is_array($details)) { foreach ($details as $item) { if (!in_array($item['id'], $all_product_ids)) { $all_product_ids[] = $item['id']; } } }
}
$products_info = [];
if (!empty($all_product_ids)) {
    $ids_placeholder = implode(',', array_fill(0, count(array_unique($all_product_ids)), '?'));
    $ids_types = str_repeat('i', count(array_unique($all_product_ids)));
    $stmt_products = $conn->prepare("
        SELECT id, prd_code, prd_name, prd_quycach 
        FROM cms_products WHERE id IN ($ids_placeholder)
    ");
    $stmt_products->bind_param($ids_types, ...array_unique($all_product_ids));
    $stmt_products->execute();
    $result_products = $stmt_products->get_result();
    while ($product = $result_products->fetch_assoc()) { $products_info[$product['id']] = $product; }
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Phiếu Giao Hàng - <?php echo htmlspecialchars($consolidated_code); ?></title>
    <style>
        body { font-family: 'Times New Roman', Times, serif; font-size: 11pt; margin: 0; background-color: #eee; }
        .print-container { width: 840px; margin: 20px auto; }
        .page { background: white; padding: 40px; margin-bottom: 20px; page-break-after: always; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .page:last-child { page-break-after: auto; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 10pt; }
        th, td { border: 1px solid #333; padding: 6px 5px; text-align: center; vertical-align: middle; }
        .main-title { font-size: 18pt; font-weight: bold; text-align: center; margin-bottom: 20px; }
        .info-block { display: flex; justify-content: space-between; margin-top: 10px; line-height: 1.6; }
        .text-left { text-align: left !important; }
        .text-right { text-align: right !important; }
        .text-bold { font-weight: bold; }
        .no-print { position: fixed; top: 10px; right: 10px; z-index: 100; }
        .footer-summary { margin-top: 15px; padding-top: 10px; width: 60%; margin-left: 40%;}
        .footer-summary p { margin: 4px 0; display: flex; justify-content: space-between; }
        .footer-summary span { font-weight: bold; }
        .footer-signatures { display: flex; justify-content: space-around; text-align: center; margin-top: 40px; }
        .footer-signatures div { font-weight: bold; }
        .footer-signatures span { font-style: italic; font-weight: normal; font-size: 9pt; }
        @media print {
            body { background-color: white; }
            .no-print, .print-container { margin: 0; }
            .page { box-shadow: none; margin: 0; padding: 20px 10px; }
        }
    </style>
</head>
<body>
    <div class="no-print">
        <button onclick="window.print()" style="padding: 10px 15px; font-size: 16px; cursor: pointer;">In Phiếu</button>
    </div>
    <div class="print-container">
        <div class="page">
            <?php require __DIR__ . '/../../templates/print_header_template.php'; ?>
            
            <div class="main-title">PHIẾU GIAO HÀNG TỔNG HỢP</div>
            <div class="info-block" style="justify-content:center; text-align:center;">
                <div>
                    <p>Ngày giao hàng: <strong><?php echo $delivery_date_display; ?></strong></p>
                    <p>Mã phiếu: <strong><?php echo htmlspecialchars($consolidated_code); ?></strong></p>
                </div>
            </div>
            <h3>I. DANH SÁCH ĐƠN HÀNG CẦN GIAO</h3>
            <table>
                <thead>
                    <tr>
                        <th style="width: 5%;">STT</th>
                        <th style="width: 15%;">Mã đơn hàng</th>
                        <th>Khách hàng / Mã số thuế</th>
                        <th style="width: 25%;">Địa chỉ</th>
                        <th style="width: 10%;">Tổng SL</th>
                        <th style="width: 15%;">Tổng tiền</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $stt = 1; $total_qty_all = 0; $total_money_all = 0;
                    foreach($orders_in_slip as $order):
                        $total_qty_all += $order['total_quantity'];
                        $total_money_all += $order['total_money'];
                    ?>
                    <tr>
                        <td><?php echo $stt++; ?></td>
                        <td><?php echo htmlspecialchars($order['output_code']); ?></td>
                        <td class="text-left"><?php echo htmlspecialchars($order['customer_name']); ?><?php if(!empty($order['customer_tax_code'])) echo '<br><small>MST: '.htmlspecialchars($order['customer_tax_code']).'</small>'; ?></td>
                        <td class="text-left"><?php echo htmlspecialchars($order['customer_addr']); ?></td>
                        <td><?php echo number_format($order['total_quantity']); ?></td>
                        <td class="text-right text-bold"><?php echo number_format($order['total_money']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="4" class="text-right">Tổng cộng</th>
                        <th class="text-bold"><?php echo number_format($total_qty_all); ?></th>
                        <th class="text-right text-bold"><?php echo number_format($total_money_all); ?></th>
                    </tr>
                </tfoot>
            </table>
        </div>

        <?php foreach($orders_in_slip as $order): ?>
        <div class="page">
            <?php require __DIR__ . '/../../templates/print_header_template.php'; ?>

            <div class="main-title">PHIẾU GIAO HÀNG</div>
            <div class="info-block">
                <div style="width: 65%;">
                    <p><span class="text-bold">Khách hàng:</span> <?php echo htmlspecialchars($order['customer_name']); ?></p>
                    <p><span class="text-bold">Địa chỉ giao hàng:</span> <?php echo htmlspecialchars($order['customer_addr']); ?></p>
                </div>
                <div style="width: 33%;">
                    <p><span class="text-bold">Hóa đơn số:</span> <?php echo htmlspecialchars($order['output_code']); ?></p>
                    <p><span class="text-bold">Ngày HĐ:</span> <?php echo date('d/m/Y H:i:s', strtotime($order['sell_date'])); ?></p>
                </div>
            </div>
            
            <table>
                <thead>
                    <tr>
                        <th style="width:5%">STT</th>
                        <th style="width:15%">Mã hàng</th>
                        <th class="text-left">Miêu tả</th>
                        <th style="width:10%">Số lượng</th>
                        <th style="width:15%">Đơn giá</th>
                        <th style="width:15%">Thành tiền</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $stt_prd = 1;
                    $order_details = json_decode($order['detail_order'], true);
                    if(is_array($order_details)):
                        foreach($order_details as $item):
                            $product_info = $products_info[$item['id']] ?? ['prd_code' => 'N/A', 'prd_name' => 'Không rõ'];
                    ?>
                    <tr>
                        <td><?php echo $stt_prd++; ?></td>
                        <td><?php echo htmlspecialchars($product_info['prd_code']); ?></td>
                        <td class="text-left"><?php echo htmlspecialchars($product_info['prd_name']); ?></td>
                        <td class="text-bold"><?php echo number_format($item['quantity']); ?></td>
                        <td class="text-right"><?php echo number_format($item['price']); ?></td>
                        <td class="text-right text-bold"><?php echo number_format($item['price'] * $item['quantity']); ?></td>
                    </tr>
                    <?php endforeach; endif; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="3" class="text-right">Tổng cộng</th>
                        <th class="text-bold"><?php echo number_format($order['total_quantity']); ?></th>
                        <th></th>
                        <th class="text-right text-bold"><?php echo number_format($order['total_money']); ?></th>
                    </tr>
                </tfoot>
            </table>
            <div class="footer-summary">
                 <?php 
                 $old_debt = 0; 
                 $total_payment = $order['total_money'] + $old_debt;
                 ?>
                 <p>Thành tiền (A): <span><?php echo number_format($order['total_money']); ?></span></p>
                 <p>Nợ cũ (B): <span><?php echo number_format($old_debt); ?></span></p>
                 <p>Tổng thanh toán (A+B): <span><?php echo number_format($total_payment); ?></span></p>
                 <p>Đã thanh toán: <span>- <?php echo number_format($total_payment); ?></span></p>
                 <hr style="border: 0; border-top: 1px dashed #555; margin: 5px 0;">
                 <p class="text-bold">Còn lại (Tổng nợ mới): <span>0</span></p>
            </div>
            
            <div style="margin-top: 5px;">
                <span class="text-bold">Bằng chữ (Thành tiền đơn này):</span>
                <i><?php echo convert_number_to_words_vietnamese($order['total_money']); ?></i>
            </div>
            
            <div class="footer-signatures">
                <div>Kế toán bán hàng<br><span>(Ký, ghi rõ họ tên)</span></div>
                <div>Nhân viên bán hàng<br><span>(Ký, ghi rõ họ tên)</span></div>
                <div>Nhân viên giao hàng<br><span>(Ký, ghi rõ họ tên)</span></div>
                <div>Khách hàng<br><span>(Ký, ghi rõ họ tên)</span></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</body>
</html>