<?php
// modules/pos/print_invoice.php - FIX LỖI TÍNH TOÁN & HIỂN THỊ
require_once __DIR__ . '/../../core/init.php';

// 1. CẤU HÌNH NGÂN HÀNG
$bank_list = [
    '970418' => ['short_name' => 'BIDV', 'full_name' => 'BIDV - NH TMCP DAU TU VA PHAT TRIEN VN', 'logo' => 'https://api.vietqr.io/img/BIDV.png'],
    '970436' => ['short_name' => 'Vietcombank', 'full_name' => 'VIETCOMBANK - NH TMCP NGOAI THUONG VN', 'logo' => 'https://api.vietqr.io/img/VCB.png'],
    '970422' => ['short_name' => 'MBBank', 'full_name' => 'MB BANK - NH QUAN DOI', 'logo' => 'https://api.vietqr.io/img/MB.png'],
    '970407' => ['short_name' => 'Techcombank', 'full_name' => 'TECHCOMBANK - NH KY THUONG VN', 'logo' => 'https://api.vietqr.io/img/TCB.png'],
    '970415' => ['short_name' => 'Vietinbank', 'full_name' => 'VIETINBANK - NH CONG THUONG VN', 'logo' => 'https://api.vietqr.io/img/ICB.png'],
    '970416' => ['short_name' => 'ACB', 'full_name' => 'ACB - NH A CHAU', 'logo' => 'https://api.vietqr.io/img/ACB.png'],
    '970405' => ['short_name' => 'Agribank', 'full_name' => 'AGRIBANK - NH NN VA PT NT VN', 'logo' => 'https://api.vietqr.io/img/VBA.png'],
    '970432' => ['short_name' => 'VPBank', 'full_name' => 'VPBANK - NH VN THINH VUONG', 'logo' => 'https://api.vietqr.io/img/VPB.png'],
    '970423' => ['short_name' => 'TPBank', 'full_name' => 'TPBANK - NH TIEN PHONG', 'logo' => 'https://api.vietqr.io/img/TPB.png'],
    '970437' => ['short_name' => 'HDBank', 'full_name' => 'HDBANK', 'logo' => 'https://api.vietqr.io/img/HDB.png'],
    '970403' => ['short_name' => 'Sacombank', 'full_name' => 'SACOMBANK', 'logo' => 'https://api.vietqr.io/img/STB.png'],
    '970441' => ['short_name' => 'VIB', 'full_name' => 'VIB', 'logo' => 'https://api.vietqr.io/img/VIB.png']
];

// 2. XỬ LÝ LƯU CẤU HÌNH
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_bank_config') {
    header('Content-Type: application/json');
    $new_bin = $_POST['bin'] ?? '';
    $new_acc_no = $_POST['acc_no'] ?? '';
    $new_acc_name = $_POST['acc_name'] ?? '';
    $new_bank_name_full = $_POST['bank_name_text'] ?? '';

    $sql_get = "SELECT content FROM cms_templates WHERE id = 1";
    $result_get = $conn->query($sql_get);
    
    if ($result_get && $result_get->num_rows > 0) {
        $row = $result_get->fetch_assoc();
        $settings = json_decode($row['content'], true);
        if (!is_array($settings)) $settings = [];

        $settings['company_bank_bin'] = $new_bin;
        $settings['company_bank_info'] = $new_bank_name_full;
        $settings['company_bank_accounts'] = $new_acc_no . " (" . $new_acc_name . ")";
        $settings['company_bank_acc_no_raw'] = $new_acc_no;
        $settings['company_bank_acc_name_raw'] = $new_acc_name;

        $new_content = json_encode($settings, JSON_UNESCAPED_UNICODE);
        $stmt_update = $conn->prepare("UPDATE cms_templates SET content = ? WHERE id = 1");
        $stmt_update->bind_param("s", $new_content);
        
        if ($stmt_update->execute()) echo json_encode(['status' => 'success']);
        else echo json_encode(['status' => 'error']);
    }
    exit; 
}

// 3. LẤY DỮ LIỆU ĐƠN HÀNG
$order_id = intval($_GET['order_id'] ?? 0);
if ($order_id <= 0) die("ID đơn hàng không hợp lệ.");

$sql = "SELECT o.*, c.customer_name, u.display_name as staff_name, t.table_name 
        FROM cms_orders o 
        LEFT JOIN cms_customers c ON o.customer_id = c.ID 
        LEFT JOIN cms_users u ON o.user_init = u.id 
        LEFT JOIN cms_tables t ON o.table_id = t.id 
        WHERE o.ID = ?";

$stmt_order = $conn->prepare($sql);
$stmt_order->bind_param("i", $order_id);
$stmt_order->execute();
$order = $stmt_order->get_result()->fetch_assoc();
$stmt_order->close();

if (!$order) { die("Không tìm thấy đơn hàng."); }

// Lấy cấu hình in
$print_settings = [];
$result_template = $conn->query("SELECT content FROM cms_templates WHERE id = 1");
if ($result_template && $result_template->num_rows > 0) {
    $settings_json = $result_template->fetch_assoc()['content'];
    $print_settings = json_decode($settings_json, true);
}

// =================================================================================
// 4. TÍNH TOÁN SỐ LIỆU CHÍNH XÁC
// =================================================================================

// A. Tổng tiền hàng (Subtotal)
$items = json_decode($order['detail_order'], true);
$sub_total = 0;
if(is_array($items)) {
    foreach($items as $item) {
        $qty = floatval($item['quantity'] ?? $item['qty'] ?? 0);
        $price = floatval($item['price'] ?? 0);
        $sub_total += $qty * $price;
    }
}

// B. Xử lý Giảm giá & Chuỗi hiển thị
$raw_discount = floatval($order['coupon']); // Giá trị lưu trong DB (có thể là 5 hoặc 5000)
$discount_amount = 0;
$discount_display_str = "";

if ($raw_discount > 0) {
    // Nếu số nhỏ <= 100, coi là Phần trăm (%)
    if ($raw_discount <= 100) {
        $discount_amount = $sub_total * ($raw_discount / 100);
        // Format: 5% (5,120)
        $discount_display_str = $raw_discount . "% (" . number_format($discount_amount) . ")";
    } else {
        // Nếu số lớn, coi là VNĐ
        $discount_amount = $raw_discount;
        $discount_display_str = number_format($discount_amount);
    }
}

// C. Tính Thành Tiền (Final Total) - SỬA LỖI Ở ĐÂY
// Thanh toán = Tổng tiền hàng - Tiền giảm giá
$final_total = $sub_total - $discount_amount;

// D. Tiền thừa / Nợ
$customer_pay = floatval($order['customer_pay']);
// Tiền thừa = Khách đưa - Phải thanh toán
$change = $customer_pay - $final_total;

// QR Code
$current_bin = $print_settings['company_bank_bin'] ?? "970418";
$current_acc_no = $print_settings['company_bank_acc_no_raw'] ?? "7370276838";
$current_acc_name = $print_settings['company_bank_acc_name_raw'] ?? "KHA TUAN ANH";
$current_short_name = $bank_list[$current_bin]['short_name'] ?? 'BIDV';
$qrInfo = "TT " . $order['output_code'];
$qrUrl = "https://img.vietqr.io/image/{$current_bin}-{$current_acc_no}-compact2.png?amount={$final_total}&addInfo={$qrInfo}&accountName=" . rawurlencode($current_acc_name);

function remove_vietnamese_diacritics($str) {
    $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
    $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
    $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
    $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
    $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
    $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
    $str = preg_replace("/(đ)/", 'd', $str);
    $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
    $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
    $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
    $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
    $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
    $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
    $str = preg_replace("/(Đ)/", 'D', $str);
    $str = preg_replace("/[^A-Za-z0-9 ]/", '', $str);
    return $str;
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bill K58</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        @media print {
            @page { margin: 0; size: 58mm auto; }
            body { margin: 0; padding: 0; }
            .no-print { display: none !important; }
        }
        body { font-family: 'Arial', sans-serif; font-size: 11px; line-height: 1.3; color: #000; background: #eee; }
        .bill-container { width: 58mm; background: #fff; padding: 5px 10px 20px 10px; margin: 20px auto; }
        
        .header { text-align: center; border-bottom: 1px dashed #000; padding-bottom: 5px; margin-bottom: 5px; }
        .store-name { font-size: 15px; font-weight: 800; text-transform: uppercase; margin-bottom: 2px; line-height: 1.1; }
        .store-info { font-size: 10px; }
        
        .bill-info { font-size: 10px; border-bottom: 1px dashed #000; padding-bottom: 3px; margin-bottom: 3px; }
        .row-info { display: flex; justify-content: space-between; }
        
        .items-list { margin-bottom: 5px; border-bottom: 1px dashed #000; padding-bottom: 5px; }
        .item-row { margin-bottom: 3px; }
        .item-name { font-weight: 700; font-size: 11px; display: block; }
        .item-detail { display: flex; justify-content: space-between; font-size: 10px; padding-left: 8px; }
        
        .total-section { text-align: right; border-bottom: 1px dashed #000; padding-bottom: 5px; }
        .total-row { display: flex; justify-content: space-between; font-size: 11px; }
        .grand-total-row { display: flex; justify-content: space-between; margin-top: 3px; font-size: 14px; font-weight: 800; }
        
        .qr-section { text-align: center; margin-top: 5px; padding-top: 5px; }
        .qr-img { width: 60%; display: block; margin: 0 auto; }
        .footer { text-align: center; margin-top: 8px; font-style: italic; font-size: 10px; }
        
        .controls { position: fixed; top: 10px; right: 10px; display: flex; gap: 5px; }
        .btn { padding: 6px 12px; border: none; border-radius: 4px; color: #fff; cursor: pointer; font-weight: bold; }
        .btn-print { background: #28a745; } .btn-back { background: #6c757d; } .btn-setting { background: #17a2b8; }
        
        .modal-backdrop { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 999; }
        .modal-content { background: #fff; padding: 15px; width: 300px; border-radius: 8px; }
        .form-control { width: 100%; padding: 5px; margin-bottom: 10px; box-sizing: border-box; }
    </style>
</head>
<body>
    <div class="controls no-print">
        <button onclick="document.getElementById('bankModal').style.display='flex'" class="btn btn-setting"><i class="fas fa-cog"></i></button>
        <button onclick="window.print()" class="btn btn-print">In</button>
        <a href="javascript:window.history.back()" class="btn btn-back">Đóng</a>
    </div>

    <div class="bill-container">
        <div class="header">
            <div class="store-name"><?php echo htmlspecialchars($print_settings['company_name'] ?? 'TÊN QUÁN'); ?></div>
            <div class="store-info"><?php echo htmlspecialchars($print_settings['company_address'] ?? ''); ?></div>
            <div class="store-info">SĐT: <?php echo htmlspecialchars($print_settings['company_phone'] ?? ''); ?></div>
        </div>

        <div class="bill-info">
            <div class="row-info"><span>Số: <?php echo substr($order['output_code'], -6); ?></span><span><?php echo date('d/m H:i', strtotime($order['sell_date'])); ?></span></div>
            <div class="row-info"><span>Bàn: <strong><?php echo $order['table_name']; ?></strong></span><span>NV: <?php echo $order['staff_name']; ?></span></div>
        </div>

        <div class="items-list">
            <?php foreach($items as $item): 
                $qty = floatval($item['quantity'] ?? $item['qty'] ?? 0);
                $price = floatval($item['price'] ?? 0);
                if($qty <= 0) continue;
            ?>
            <div class="item-row">
                <div class="item-name"><?php echo htmlspecialchars($item['name']); ?></div>
                <div class="item-detail">
                    <span><?php echo $qty; ?> x <?php echo number_format($price); ?></span>
                    <span><?php echo number_format($qty * $price); ?></span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="total-section">
            <div class="total-row">
                <span>Tổng tiền hàng:</span>
                <span><?php echo number_format($sub_total); ?></span>
            </div>
            
            <?php if($discount_amount > 0): ?>
            <div class="total-row">
                <span>Giảm giá:</span>
                <span><?php echo $discount_display_str; ?></span>
            </div>
            <?php endif; ?>
            
            <div class="grand-total-row">
                <span>THANH TOÁN:</span>
                <span><?php echo number_format($final_total); ?></span>
            </div>
            
            <div class="total-row" style="margin-top: 3px; font-style: italic;">
                <span>Khách đưa:</span>
                <span><?php echo number_format($customer_pay); ?></span>
            </div>
            
            <?php if($change < 0): // Chỉ hiện khi thiếu tiền (Nợ) ?>
            <div class="total-row" style="font-style: italic; font-weight:bold;">
                <span>Còn nợ:</span>
                <span><?php echo number_format(abs($change)); ?></span>
            </div>
            <?php elseif($change > 0): // Hiện tiền thừa nếu dư ?>
            <div class="total-row" style="font-style: italic;">
                <span>Tiền thừa:</span>
                <span><?php echo number_format($change); ?></span>
            </div>
            <?php endif; ?>
        </div>

        <div class="qr-section">
            <img src="<?php echo $qrUrl; ?>" class="qr-img">
            <div style="font-size:9px; font-weight:600; margin-top:2px">
                <?php echo $current_short_name; ?> - <?php echo $current_acc_no; ?><br>
                <?php echo $current_acc_name; ?>
            </div>
        </div>

        <div class="footer">
            Wifi: <?php echo htmlspecialchars($print_settings['wifi_pass'] ?? ''); ?><br>
            Cám ơn quý khách!
        </div>
    </div>

    <div id="bankModal" class="modal-backdrop no-print">
        <div class="modal-content">
            <h4 style="margin:0 0 10px 0;">Cài đặt Ngân hàng</h4>
            <select id="bankBinInput" class="form-control">
                <?php foreach ($bank_list as $bin => $info): ?>
                    <option value="<?php echo $bin; ?>" <?php echo ($bin == $current_bin) ? 'selected' : ''; ?>>
                        <?php echo $info['short_name']; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <input type="text" id="accNoInput" class="form-control" value="<?php echo $current_acc_no; ?>" placeholder="Số tài khoản">
            <input type="text" id="accNameInput" class="form-control" value="<?php echo $current_acc_name; ?>" placeholder="Tên chủ thẻ">
            <div style="text-align:right;">
                <button onclick="document.getElementById('bankModal').style.display='none'" class="btn btn-back">Đóng</button>
                <button onclick="saveBankConfig()" class="btn btn-print">Lưu</button>
            </div>
        </div>
    </div>

    <script>
        function saveBankConfig() {
            var bin = document.getElementById('bankBinInput').value;
            var accNo = document.getElementById('accNoInput').value;
            var accName = document.getElementById('accNameInput').value;
            var bankSelect = document.getElementById('bankBinInput');
            var bankNameText = bankSelect.options[bankSelect.selectedIndex].text;

            var data = new FormData();
            data.append('action', 'save_bank_config');
            data.append('bin', bin);
            data.append('acc_no', accNo);
            data.append('acc_name', accName);
            data.append('bank_name_text', bankNameText);

            fetch(window.location.href, { method: 'POST', body: data })
            .then(res => res.json())
            .then(res => {
                if(res.status == 'success') { alert('Lưu thành công!'); location.reload(); } 
                else { alert('Lỗi: ' + res.message); }
            });
        }
    </script>
</body>
</html>