<?php
define('IS_PRINT_PAGE', true); 
require_once __DIR__ . '/../../core/init.php';

// --- LẤY THÔNG TIN PHIẾU NHẬP ---
$slip_id = intval($_GET['id'] ?? 0);
if ($slip_id <= 0) die("ID phiếu nhập không hợp lệ.");

$sql = "SELECT i.*, s.store_name, sup.supplier_name, sup.supplier_phone, sup.supplier_addr, u.display_name as user_created 
        FROM cms_input AS i 
        LEFT JOIN cms_stores AS s ON i.store_id = s.id 
        LEFT JOIN cms_suppliers AS sup ON i.supplier_id = sup.id 
        LEFT JOIN cms_users AS u ON i.user_init = u.id 
        WHERE i.id = ?";
$stmt = $conn->prepare($sql);
if ($stmt === false) die("Lỗi SQL: " . htmlspecialchars($conn->error));
$stmt->bind_param("i", $slip_id);
$stmt->execute();
$slip = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$slip) die("Không tìm thấy phiếu nhập.");
$slip_items = json_decode($slip['detail_input'], true);

// Lấy thông tin sản phẩm
$products_info = [];
if (!empty($slip_items)) {
  $product_ids = array_map(function($item) { return intval($item['id']); }, $slip_items);;
    $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
    $types = str_repeat('i', count($product_ids));
    
    $sql_products = "SELECT p.id, p.prd_code, p.prd_name, p.prd_quycach, u.prd_unit_name 
                     FROM cms_products p 
                     LEFT JOIN cms_products_unit u ON p.prd_unit_id = u.id 
                     WHERE p.id IN ($placeholders)";
    
    $stmt_products = $conn->prepare($sql_products);
    $stmt_products->bind_param($types, ...$product_ids);
    $stmt_products->execute();
    $result_products = $stmt_products->get_result();
    
    while ($row = $result_products->fetch_assoc()) {
        $products_info[$row['id']] = $row;
    }
    $stmt_products->close();
}

// ## THAY ĐỔI 1: Thêm hàm đọc số thành chữ ##
function numberToWords($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ỷ');
    if (!is_numeric($number)) { return false; }
    if ($number < 0) { return $negative . numberToWords(abs($number)); }
    $string = '';
    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) { $string .= $hyphen . ($units == 1 ? 'mốt' : ($units == 5 ? 'lăm' : $dictionary[$units])); } break;
        case $number < 1000: $hundreds  = $number / 100; $remainder = $number % 100; $string = $dictionary[(int)$hundreds] . ' ' . $dictionary[100]; if ($remainder) { $string .= $conjunction . ($remainder < 10 ? 'linh ' : '') . numberToWords($remainder); } break;
        default: $baseUnit = pow(1000, floor(log($number, 1000))); $numBaseUnits = (int) ($number / $baseUnit); $remainder = $number % $baseUnit; $string = numberToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit]; if ($remainder) { $string .= $remainder < 100 ? $conjunction . 'không trăm ' . ($remainder < 10 ? 'linh ' : '') : $conjunction; $string .= numberToWords($remainder); } break;
    }
    return $string;
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>In Phiếu Nhập Kho - <?php echo htmlspecialchars($slip['input_code']); ?></title>
    <style>
        body { font-family: 'Times New Roman', Times, serif; font-size: 12pt; margin: 0; background-color: #eee; }
        .page { background: white; width: 14.8cm; min-height: 21cm; padding: 1cm; margin: 1cm auto; display: flex; flex-direction: column; box-shadow: 0 0 5px rgba(0,0,0,0.1); }
        .main-content { flex-grow: 1; }
        .title { text-align: center; font-size: 18px; font-weight: bold; margin: 15px 0; }
        .info-table { width: 100%; border-collapse: collapse; margin-bottom: 15px; font-size: 12pt; }
        .info-table td { padding: 3px; vertical-align: top; }
        .items-table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 11pt; }
        .items-table th, .items-table td { border: 1px solid #000; padding: 4px; text-align: center; vertical-align: middle; }
        .items-table .text-left { text-align: left; }
        .items-table .text-right { text-align: right; }
        .summary-section { margin-top: 20px; line-height: 1.6; }
        .signatures { margin-top: auto; padding-top: 40px; display: flex; justify-content: space-around; text-align: center; clear: both; }
        .signatures div { font-weight: bold; font-size: 11pt; }
        .signatures span { display: block; margin-top: 60px; font-style: italic; font-weight: normal; font-size: 10pt; }
        .print-controls { display: none; }

        @media screen {
            .print-controls { display: block; position: fixed; top: 1rem; right: 1rem; z-index: 10; }
            .print-controls button { background-color: #0d6efd; color: white; border: none; padding: 8px 15px; border-radius: 5px; cursor: pointer; margin-left: 10px; }
            .print-controls button.btn-back { background-color: #6c757d; }
        }
        @media print {
            body { background-color: white; }
            .page { margin: 0; padding: 0.5cm; box-shadow: none; border: none; }
            .print-controls { display: none; }
        }
    </style>
</head>
<body>
    <div class="print-controls">
        <button class="btn-back" onclick="window.history.back()">← Trở lại</button>
        <button class="btn-print" onclick="window.print()">🖨️ In Phiếu</button>
    </div>

    <div class="page">
        <?php require_once __DIR__ . '/../../templates/print_header_template.php'; ?>

        <div class="title">PHIẾU NHẬP KHO</div>

        <table class="info-table">
            <tr>
                <td style="width: 70%;"><strong>Nhà cung cấp:</strong> <?php echo htmlspecialchars($slip['supplier_name'] ?? 'N/A'); ?></td>
                <td style="width: 30%;"><strong>Ngày nhập:</strong> <?php echo date('d/m/Y H:i', strtotime($slip['created'])); ?></td>
            </tr>
            <tr>
                <td><strong>Điện thoại:</strong> <?php echo htmlspecialchars($slip['supplier_phone'] ?? '(chưa có)'); ?></td>
                <td><strong>Mã phiếu:</strong> <?php echo htmlspecialchars($slip['input_code']); ?></td>
            </tr>
            <tr>
                <td colspan="2"><strong>Địa chỉ:</strong> <?php echo htmlspecialchars($slip['supplier_addr'] ?? '(chưa có)'); ?></td>
            </tr>
        </table>
        
        <div class="main-content">
            <table class="items-table">
                <thead>
                    <tr>
                        <th>STT</th><th>Mã hàng</th><th class="text-left">Miêu tả</th><th>Quy cách</th><th>Thùng</th><th>Lẻ</th><th>Tổng SL</th><th class="text-right">Giá thùng</th><th class="text-right">Giá lẻ</th><th class="text-right">Thành tiền</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if (!empty($slip_items)):
                        $stt = 1; $total_quantity = 0; $total_packs = 0; $total_loose = 0;
                        foreach($slip_items as $item): 
                            $product = $products_info[$item['id']] ?? null;
                            $spec_size = (int)($product['prd_quycach'] ?? 0);
                            $quantity = (int)$item['quantity'];
                            $price_loose = (float)$item['price'];
                            $packs = ($spec_size > 0) ? floor($quantity / $spec_size) : 0;
                            $loose = ($spec_size > 0) ? $quantity % $spec_size : $quantity;
                            $price_pack = ($spec_size > 0) ? $price_loose * $spec_size : 0;
                            $line_total = $quantity * $price_loose;
                            $total_quantity += $quantity; $total_packs += $packs; $total_loose += $loose;
                    ?>
                    <tr>
                        <td><?php echo $stt++; ?></td>
                        <td><?php echo htmlspecialchars($product['prd_code'] ?? 'N/A'); ?></td>
                        <td class="text-left"><?php echo htmlspecialchars($product['prd_name'] ?? 'Sản phẩm không xác định'); ?></td>
                        <td><?php echo $spec_size > 0 ? $spec_size : ''; ?></td>
                        <td><?php echo $packs > 0 ? number_format($packs) : ''; ?></td>
                        <td><?php echo $loose > 0 ? number_format($loose) : ''; ?></td>
                        <td><strong><?php echo number_format($quantity); ?></strong></td>
                        <td class="text-right"><?php echo $price_pack > 0 ? number_format($price_pack) : ''; ?></td>
                        <td class="text-right"><?php echo number_format($price_loose); ?></td>
                        <td class="text-right"><strong><?php echo number_format($line_total); ?></strong></td>
                    </tr>
                    <?php endforeach; ?>
                    <tr>
                        <td colspan="4" class="text-right"><strong>Tổng cộng</strong></td>
                        <td><strong><?php echo $total_packs > 0 ? number_format($total_packs) : ''; ?></strong></td>
                        <td><strong><?php echo $total_loose > 0 ? number_format($total_loose) : ''; ?></strong></td>
                        <td><strong><?php echo number_format($total_quantity); ?></strong></td>
                        <td colspan="2"></td>
                        <td class="text-right"><strong><?php echo number_format($slip['total_money']); ?></strong></td>
                    </tr>
                    <?php else: ?>
                        <tr><td colspan="10" class="text-center">Không có sản phẩm trong phiếu.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="summary-section">
            <p><strong>Tổng tiền thanh toán: <?php echo number_format($slip['total_money']); ?></strong></p>
            <p><em>(Bằng chữ: <?php echo ucfirst(numberToWords($slip['total_money'])) . ' đồng'; ?>)</em></p>
            <p><strong>Ghi chú:</strong> <?php echo nl2br(htmlspecialchars($slip['notes'])); ?></p>
        </div>

        <footer class="signatures">
            <div>Người lập phiếu<span>(Ký, ghi rõ họ tên)</span></div>
            <div>Nhà cung cấp<span>(Ký, ghi rõ họ tên)</span></div>
            <div>Thủ kho<span>(Ký, ghi rõ họ tên)</span></div>
        </footer>
    </div>
</body>
</html>