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

$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);

$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, 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();
}

// --- TÍNH TOÁN CHIẾT KHẤU ---
$total_base_money = 0;
$total_item_discount_amount = 0;
if(is_array($slip_items)){
    foreach($slip_items as $item) {
        $quantity = (float)($item['quantity'] ?? 0);
        $price = (float)($item['price'] ?? 0);
        $discount_percent = (float)($item['discount_percent'] ?? 0);
        $line_base_total = $quantity * $price;
        $total_base_money += $line_base_total;
        $total_item_discount_amount += $line_base_total * ($discount_percent / 100);
    }
}
$subtotal_after_item_discounts = $total_base_money - $total_item_discount_amount;
$order_discount_percent = (float)($slip['discount'] ?? 0);
$order_discount_amount = $subtotal_after_item_discounts * ($order_discount_percent / 100);
// --- KẾT THÚC TÍNH TOÁN ---


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;
}

$total_money_in_words = ucfirst(numberToWords($slip['total_money'])) . ' đồng';
?>
<!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: 21cm; min-height: 29.7cm; padding: 1.5cm; 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: 18pt; font-weight: bold; margin: 20px 0; }
        .info-grid { display: flex; justify-content: space-between; margin-bottom: 20px; line-height: 1.6; }
        .items-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        .items-table th, .items-table td { border: 1px solid #000; padding: 5px; text-align: center; vertical-align: middle; }
        .items-table .text-left { text-align: left; }
        .items-table .text-right { text-align: right; }
        .summary-section { margin-top: 10px; width: 60%; float: right; }
        .summary-table { width: 100%; font-size: 11pt; }
        .summary-table td { padding: 4px; }
        .signatures { margin-top: auto; padding-top: 50px; display: flex; justify-content: space-around; text-align: center; clear: both; }
        .signatures div { font-weight: bold; }
        .signatures span { display: block; margin-top: 70px; font-style: italic; font-weight: normal; }
        .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>

        <div class="info-grid">
            <div>
                <strong>Nhà cung cấp:</strong> <?php echo htmlspecialchars($slip['supplier_name'] ?? 'N/A'); ?><br>
                <strong>Địa chỉ:</strong> <?php echo htmlspecialchars($slip['supplier_addr'] ?? '(chưa có)'); ?>
            </div>
            <div style="text-align: right;">
                <strong>Mã phiếu:</strong> <?php echo htmlspecialchars($slip['input_code']); ?><br>
                <strong>Ngày nhập:</strong> <?php echo date('d/m/Y H:i', strtotime($slip['created'])); ?>
            </div>
        </div>
        
        <div class="main-content">
            <table class="items-table">
                <thead>
                    <tr>
                        <th style="width: 5%;">STT</th>
                        <th class="text-left">Tên sản phẩm</th>
                        <th style="width: 8%;">SL</th>
                        <th style="width: 10%;">ĐVT</th>
                        <th class="text-right" style="width: 15%;">Đơn giá</th>
                        <th style="width: 8%;">%CK</th>
                        <th class="text-right" style="width: 20%;">Thành tiền</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    if (!empty($slip_items)):
                        $stt = 1;
                        $total_quantity = 0;
                        $total_final_amount = 0;
                        foreach($slip_items as $item): 
                            $product = $products_info[$item['id']] ?? null;
                            $quantity = (float)($item['quantity'] ?? 0);
                            $price = (float)($item['price'] ?? 0);
                            $discount_percent = (float)($item['discount_percent'] ?? 0);
                            $line_total_before_discount = $quantity * $price;
                            $discount_amount = $line_total_before_discount * ($discount_percent / 100);
                            $line_total = $line_total_before_discount - $discount_amount;
                            $total_quantity += $quantity;
                            $total_final_amount += $line_total;
                    ?>
                    <tr>
                        <td><?php echo $stt++; ?></td>
                        <td class="text-left"><?php echo htmlspecialchars($product['prd_name'] ?? 'Sản phẩm không xác định'); ?></td>
                        <td><?php echo number_format($quantity); ?></td>
                        <td><?php echo htmlspecialchars($product['prd_unit_name'] ?? 'N/A'); ?></td>
                        <td class="text-right"><?php echo number_format($price); ?></td>
                        <td><?php echo number_format($discount_percent, 2); ?></td>
                        <td class="text-right"><?php echo number_format($line_total); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <tr>
                        <td colspan="2" class="text-right"><strong>Tổng cộng</strong></td>
                        <td><strong><?php echo number_format($total_quantity); ?></strong></td>
                        <td colspan="3"></td>
                        <td class="text-right"><strong><?php echo number_format($subtotal_after_item_discounts); ?></strong></td>
                    </tr>
                    <?php else: ?>
                        <tr><td colspan="7" class="text-center">Không có sản phẩm trong phiếu.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="summary-section">
            <table class="summary-table">
                <tr>
                    <td>Tổng tiền hàng:</td>
                    <td class="text-right"><?php echo number_format($total_base_money); ?></td>
                </tr>
                <tr>
                    <td>Chiết khấu sản phẩm:</td>
                    <td class="text-right"><?php echo number_format($total_item_discount_amount); ?></td>
                </tr>
                <tr>
                    <td>Chiết khấu HĐ (<?php echo number_format($order_discount_percent, 2); ?>%):</td>
                    <td class="text-right"><?php echo number_format($order_discount_amount); ?></td>
                </tr>
                <tr>
                    <td><strong>Tổng thanh toán:</strong></td>
                    <td class="text-right"><strong><?php echo number_format($slip['total_money']); ?></strong></td>
                </tr>
            </table>
        </div>
        
        <p style="clear: both; margin-top: 15px;"><em>(Bằng chữ: <?php echo $total_money_in_words; ?>)</em></p>

        <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>