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

// =================================================================================
// CẤU HÌNH DANH SÁCH NGÂN HÀNG KÈM LOGO CHUẨN
// =================================================================================
$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'
    ],
    '970449' => [
        'short_name' => 'LPBank', 
        'full_name' => 'LPBANK - NH BUU DIEN LIEN VIET',
        'logo' => 'https://api.vietqr.io/img/LPB.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 - NH PT TP HO CHI MINH',
        'logo' => 'https://api.vietqr.io/img/HDB.png'
    ],
    '970403' => [
        'short_name' => 'Sacombank', 
        'full_name' => 'SACOMBANK - NH SAIGON THUONG TIN',
        'logo' => 'https://api.vietqr.io/img/STB.png'
    ],
    '970441' => [
        'short_name' => 'VIB', 
        'full_name' => 'VIB - NH QUOC TE',
        'logo' => 'https://api.vietqr.io/img/VIB.png'
    ],
    '970443' => [
        'short_name' => 'SHB', 
        'full_name' => 'SHB - NH SAI GON - HA NOI',
        'logo' => 'https://api.vietqr.io/img/SHB.png'
    ],
];

// =================================================================================
// PHẦN 1: XỬ LÝ AJAX 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'] ?? '';

    // Lấy cấu hình hiện tại
    $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 = [];

        // Cập nhật thông tin mới
        $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;

        // Lưu xuống DB
        $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', 'message' => 'Đã lưu thông tin ngân hàng mặc định!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Lỗi DB: ' . $conn->error]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy mẫu in ID=1']);
    }
    exit; 
}

// =================================================================================
// PHẦN 2: LOGIC LẤY DỮ LIỆU HIỂN THỊ
// =================================================================================

$order_id = intval($_GET['order_id'] ?? 0);
if ($order_id <= 0) die("ID đơn hàng không hợp lệ.");

$stmt_order = $conn->prepare("SELECT o.*, c.customer_name, c.customer_phone, c.customer_addr, u.display_name as staff_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 WHERE o.ID = ?");
$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."); }

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

// Dữ liệu mặc định
$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'] ?? "GIANG THI XUAN HONG";
$current_bank_text = $print_settings['company_bank_info'] ?? "BIDV - NH DAU TU VA PHAT TRIEN VN";
$current_short_name = $bank_list[$current_bin]['short_name'] ?? 'BIDV';
// Lấy logo hiện tại
$current_logo_url = $bank_list[$current_bin]['logo'] ?? 'https://api.vietqr.io/img/BIDV.png';


// --- XỬ LÝ CHI TIẾT ĐƠN HÀNG ---
$order_items = json_decode($order['detail_order'], true);
if (!is_array($order_items)) $order_items = [];

$units_map = [];
$units_result = $conn->query("SELECT ID, prd_unit_name FROM cms_products_unit");
if ($units_result) {
    while ($unit_row = $units_result->fetch_assoc()) {
        $units_map[$unit_row['ID']] = $unit_row['prd_unit_name'];
    }
}
$stmt_product_unit = $conn->prepare("SELECT prd_unit_id FROM cms_products WHERE ID = ?");

$total_quantity = 0;
$total_price_before_discount = 0;
$total_discount_on_items = 0;
$total_after_discount = 0; 

foreach ($order_items as $item) {
    $quantity = floatval($item['quantity'] ?? 0);
    $price = floatval($item['price'] ?? 0);
    $item_discount_amount = floatval($item['discount'] ?? 0);
    $total_price_before_discount += $quantity * $price;
    $total_discount_on_items += $item_discount_amount;
    $total_quantity += $quantity;
    $total_after_discount += ($quantity * $price) - $item_discount_amount; 
}
$final_total_money = $order['total_money'];

function numberToWords($number) {
    $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 => 'ngàn', 1000000 => 'triệu', 1000000000 => 'tỷ');
    if (!is_numeric($number)) return false;
    if ($number < 0) return 'âm ' . numberToWords(abs($number));
    $string = '';
    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 .= ' ' . ($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 .= ' ' . ($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 ? ' không trăm ' . ($remainder < 10 ? 'linh ' : '') : ' '; $string .= numberToWords($remainder); } break;
    }
    return $string;
}

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\s]/', '', $str);
    $str = preg_replace('/\s+/', ' ', $str);
    return trim($str);
}

$total_money_in_words = ucfirst(numberToWords($final_total_money)) . ' đồng';

// --- TẠO QR CODE INITIAL ---
$qrAmount = $final_total_money;
$qrAccountName_encoded = rawurlencode($current_acc_name);
$template = "compact2";
$customerName = $order['customer_name'] ?? 'Khach le';
$invoiceCode = $order['output_code'];
$cleanCustomerName = remove_vietnamese_diacritics($customerName);
$transferContent = $cleanCustomerName . ' ' . $invoiceCode;
$qrContent_encoded = rawurlencode($transferContent);
$qrImageUrl = "https://img.vietqr.io/image/{$current_bin}-{$current_acc_no}-{$template}.png?amount={$qrAmount}&addInfo={$qrContent_encoded}&accountName={$qrAccountName_encoded}";
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Hóa đơn <?php echo htmlspecialchars($order['output_code']); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* --- CẤU HÌNH IN --- */
        @media print {
            @page { size: A5 portrait; margin: 0; }
            body { margin: 0; padding: 0; }
            .print-controls, .modal-backdrop, .toast-msg { display: none !important; }
            .page {
                width: 138mm !important; 
                max-width: 138mm !important;
                margin: 0 auto !important;
                min-height: 205mm !important; 
                padding: 3mm !important;
                box-shadow: none !important;
                border: none !important;
                display: flex !important;
                flex-direction: column !important;
            }
        }

        /* --- CSS MÀN HÌNH --- */
        body { font-family: 'Times New Roman', Times, serif; font-size: 9pt; margin: 0; background-color: #f0f2f5; }
        
        .page {
            background: white;
            width: 148mm;
            min-height: 209mm; 
            padding: 3mm; 
            margin: 5mm auto;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column; 
            box-sizing: border-box;
        }
        
        .main-content { flex-grow: 1; }
        
        /* HEADER STYLES */
        .page-header-container { display: flex; justify-content: space-between; align-items: flex-start; padding-bottom: 2px; margin-bottom: 2px; border-bottom: 1px solid #eee; }
        
        /* --- ĐIỀU CHỈNH KÍCH THƯỚC HEADER ĐỂ LOGO VÀ QR TO HƠN --- */
        .header-left-col { flex: 0 0 100px; display: flex; align-items: center; } /* Tăng từ 60px lên 100px */
        .header-center-col { flex: 1; text-align: center; padding: 0 2px; }
        .header-right-col { flex: 0 0 140px; text-align: right; } /* Tăng từ 80px lên 140px */
        
        /* Logo to hơn */
        .logo-container img { max-height: 80px; width: auto; } /* Tăng max-height lên 80px */
        
        .company-name { font-size: 16pt; font-weight: bold; line-height: 1.1; text-transform: uppercase; }
        .company-slogan { font-size: 9pt; font-style: italic; margin-top: 2px; }
        
        /* QR CODE TO HƠN */
        .header-qr-code img { 
            max-width: 100%; 
            height: auto; 
            max-height: 130px; /* Tăng max-height lên 130px */
        }
        
        .header-details-block { display: flex; justify-content: space-between; width: 100%; margin: 2px 0 5px 0; font-size: 9pt; line-height: 1.3; font-weight: bold; color: #333; border-bottom: 1px solid #000; padding-bottom: 3px; }
        .detail-col { width: 49%; }
        
        .title { text-align: center; font-size: 14pt; font-weight: bold; margin: 5px 0; text-transform: uppercase; }
        
        /* TABLE STYLES */
        .customer-info-grid { display: flex; justify-content: space-between; width: 100%; margin-bottom: 5px; font-size: 9pt; line-height: 1.3; }
        .customer-info-grid .info-col { width: 49%; }
        .customer-info-grid p { margin: 1px 0; }
        
        .items-table { width: 100%; border-collapse: collapse; font-size: 9pt; margin-bottom: 5px; }
        .items-table th, .items-table td { border: 1px solid #000; padding: 2px 1px; text-align: center; vertical-align: middle; }
        .items-table .text-left { text-align: left; padding-left: 3px; }
        .items-table .text-right { text-align: right; padding-right: 3px; }
        .col-code { width: 8%; } .col-name { width: auto; } .col-unit { width: 6%; } .col-qty { width: 5%; }
        .col-price { width: 12%; } .col-total { width: 13%; } .col-disc-p { width: 6%; } .col-disc-m { width: 9%; } .col-final { width: 13%; }

        .summary-section { width: 100%; margin-top: 2px; font-size: 9pt; }
        .summary-table { width: 100%; border-collapse: collapse; }
        .summary-table td { padding: 1px 5px; }
        .summary-value { text-align: right; font-weight: bold; }
        .footer-text { margin-top: 5px; font-size: 9pt; }
        
        .signatures { display: table; width: 100%; margin-top: auto; padding-top: 10px; text-align: center; font-weight: bold; font-size: 9pt; page-break-inside: avoid; }
        .signatures .signer { display: table-cell; width: 25%; vertical-align: top; }
        .signatures .signer p { margin-top: 50px; font-style: italic; font-weight: normal; font-size: 8.5pt; margin-bottom: 0; }

        /* --- GIAO DIỆN NÚT ĐIỀU KHIỂN --- */
        .print-controls { position: fixed; top: 1rem; right: 1rem; z-index: 100; display: flex; gap: 8px; }
        .custom-btn {
            font-family: 'Arial', sans-serif; border: none; border-radius: 6px; padding: 10px 18px; 
            cursor: pointer; text-decoration: none; color: white; font-size: 14px; font-weight: 600;
            display: flex; align-items: center; gap: 6px; box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: transform 0.1s, box-shadow 0.1s;
        }
        .custom-btn:active { transform: translateY(1px); box-shadow: none; }
        .btn-back { background: #6c757d; }
        .btn-print { background: #007bff; }
        .btn-setting { background: #17a2b8; }
        
        /* --- GIAO DIỆN MODAL DÀNH CHO NGƯỜI LỚN TUỔI --- */
        .modal-backdrop {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.6); 
            display: none; justify-content: center; align-items: center;
            z-index: 9999;
            backdrop-filter: blur(2px);
        }
        .modal-content {
            background: white; 
            width: 500px; /* Rộng hơn hẳn */
            max-width: 95%; 
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.3);
            overflow: visible; /* Để dropdown không bị che */
            animation: slideDown 0.3s ease-out;
            font-family: 'Arial', sans-serif;
            display: flex; flex-direction: column;
            max-height: 90vh; /* Tránh tràn màn hình */
        }
        @keyframes slideDown { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

        .modal-header {
            background: #f0f2f5; padding: 15px 25px; border-bottom: 2px solid #ddd;
            display: flex; justify-content: space-between; align-items: center;
            border-radius: 12px 12px 0 0;
        }
        .modal-header h3 { margin: 0; font-size: 18px; color: #333; display: flex; align-items: center; gap: 10px; }
        .modal-close { cursor: pointer; font-size: 28px; color: #666; font-weight: bold; line-height: 1; padding: 0 10px;}
        .modal-close:hover { color: #dc3545; }

        .modal-body { padding: 25px; overflow-y: auto; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-size: 15px; font-weight: bold; color: #333; }
        
        /* INPUT FIELDS TO HƠN */
        .form-control {
            width: 100%; padding: 12px 15px; border: 2px solid #ccc; border-radius: 8px;
            font-size: 16px; box-sizing: border-box; transition: border-color 0.2s; height: 50px;
        }
        .form-control:focus { border-color: #007bff; outline: none; }

        /* --- CUSTOM DROPDOWN SELECT --- */
        .custom-select-wrapper { position: relative; user-select: none; width: 100%; }
        .custom-select-trigger {
            position: relative;
            display: flex; align-items: center; justify-content: space-between;
            padding: 0 15px;
            font-size: 16px; font-weight: bold; color: #333;
            height: 60px; /* Cao hơn chút cho logo lớn */
            line-height: 60px;
            background: #fff; border: 2px solid #ccc; border-radius: 8px;
            cursor: pointer;
        }
        .custom-select-trigger:after {
            content: '\25BC'; font-size: 14px; color: #666; margin-left: 10px;
        }
        /* Style cho logo hiển thị trên thanh trigger */
        .custom-select-trigger img {
            height: 40px; 
            width: auto; 
            margin-right: 15px; 
            vertical-align: middle; 
            object-fit: contain;
        }
        
        .custom-options {
            position: absolute; display: block; top: 100%; left: 0; right: 0;
            border: 2px solid #007bff; border-top: 0;
            background: #fff; transition: all 0.3s;
            opacity: 0; visibility: hidden; pointer-events: none; z-index: 10001;
            max-height: 400px; overflow-y: auto; /* Scroll dài hơn */
            border-radius: 0 0 8px 8px;
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        }
        .custom-select-wrapper.open .custom-options {
            opacity: 1; visibility: visible; pointer-events: auto;
        }
        .custom-option {
            position: relative; display: flex; align-items: center;
            padding: 12px 15px; font-size: 16px; color: #333;
            cursor: pointer; transition: all 0.2s; border-bottom: 1px solid #eee;
        }
        .custom-option:last-child { border-bottom: none; }
        .custom-option:hover { background-color: #e9ecef; color: #007bff; }
        .custom-option.selected { background-color: #e3f2fd; font-weight: bold; }
        
        /* Style cho logo trong danh sách */
        .custom-option img {
            height: 40px; 
            width: 90px;  /* Đủ rộng để hiện hết logo Vietcombank */
            object-fit: contain; /* Giữ tỷ lệ ảnh, không bị méo */
            object-position: left center;
            margin-right: 15px;
            padding: 2px; 
        }

        .modal-footer {
            padding: 20px 25px; background: #f8f9fa; border-top: 1px solid #ddd; text-align: right;
            border-radius: 0 0 12px 12px;
        }
        .btn-save {
            background: #28a745; color: white; border: none; padding: 12px 30px;
            border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 16px;
            display: inline-flex; align-items: center; gap: 8px;
            box-shadow: 0 3px 6px rgba(0,0,0,0.15);
        }
        .btn-save:hover { background: #218838; transform: translateY(-1px); }

        /* Notification */
        .toast-msg {
            position: fixed; bottom: 30px; right: 30px; background: #333; color: white;
            padding: 15px 30px; border-radius: 8px; z-index: 10000; font-family: Arial; font-size: 16px;
            opacity: 0; transition: opacity 0.5s; pointer-events: none;
        }
        .toast-msg.show { opacity: 1; }
    </style>
</head>
<body>
    <div class="print-controls">
        <button onclick="openSettings()" class="custom-btn btn-setting"><i class="fas fa-university"></i> Đổi ngân hàng</button>
        <a href="javascript:window.history.back()" class="custom-btn btn-back"><i class="fas fa-arrow-left"></i> Trở lại</a>
        <button onclick="window.print()" class="custom-btn btn-print"><i class="fas fa-print"></i> In Phiếu</button>
    </div>

    <div class="modal-backdrop" id="bankModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-university" style="color: #007bff;"></i> THÔNG TIN CHUYỂN KHOẢN</h3>
                <span class="modal-close" onclick="closeSettings()">&times;</span>
            </div>
            <div class="modal-body">
                
                <div class="form-group">
                    <label>Ngân hàng thụ hưởng:</label>
                    <div class="custom-select-wrapper" id="customBankSelect">
                        <div class="custom-select-trigger">
                            <div style="display:flex; align-items:center;">
                                <img id="triggerLogo" src="<?php echo $current_logo_url; ?>" alt="Logo">
                                <span id="triggerText"><?php echo $current_short_name; ?></span>
                            </div>
                        </div>
                        <div class="custom-options">
                            <?php foreach ($bank_list as $bin => $info): ?>
                            <div class="custom-option <?php echo ($bin == $current_bin) ? 'selected' : ''; ?>" 
                                 data-value="<?php echo $bin; ?>" 
                                 data-short="<?php echo $info['short_name']; ?>"
                                 data-fullname="<?php echo $info['full_name']; ?>"
                                 data-logo="<?php echo $info['logo']; ?>"> <img src="<?php echo $info['logo']; ?>" loading="lazy" alt="Logo">
                                <span><?php echo $info['short_name']; ?> - <?php echo $info['full_name']; ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <input type="hidden" id="bankBinInput" value="<?php echo $current_bin; ?>">
                    <input type="hidden" id="bankNameFullInput" value="<?php echo $current_bank_text; ?>">
                </div>

                <div class="form-group">
                    <label>Số tài khoản:</label>
                    <input type="text" id="accNoInput" class="form-control" value="<?php echo htmlspecialchars($current_acc_no); ?>" onkeyup="updateUI()">
                </div>
                <div class="form-group">
                    <label>Chủ tài khoản (VIẾT HOA):</label>
                    <input type="text" id="accNameInput" class="form-control" value="<?php echo htmlspecialchars($current_acc_name); ?>" onkeyup="updateUI()">
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="saveAndApply()" class="btn-save"><i class="fas fa-save"></i> LƯU VÀ ÁP DỤNG</button>
            </div>
        </div>
    </div>

    <div id="toast" class="toast-msg">Đã lưu thành công!</div>

    <div class="page">
        <div class="main-content">
            <header>
                <div class="page-header-container">
                    <div class="header-left-col">
                        <div class="logo-container">
                            <?php if (!empty($print_settings['company_logo'])): ?>
                                <img src="/quanlybanhang/<?php echo htmlspecialchars(stripslashes($print_settings['company_logo'])); ?>" alt="Logo">
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="header-center-col">
                        <div class="company-name"><?php echo htmlspecialchars($print_settings['company_name'] ?? 'TÊN CÔNG TY'); ?></div>
                        <div class="company-slogan"><?php echo htmlspecialchars($print_settings['company_specialty_items'] ?? 'XE ĐẠP - XE ĐẠP ĐIỆN'); ?></div>
                    </div>
                    <div class="header-right-col">
                        <div class="header-qr-code">
                             <img id="qrImage" src="<?php echo htmlspecialchars($qrImageUrl); ?>" alt="QR Code">
                        </div>
                    </div>
                </div>
                <div class="header-details-block">
                    <div class="detail-col">
                        <div><strong>ĐC:</strong> <?php echo htmlspecialchars($print_settings['company_address'] ?? 'Chưa có địa chỉ'); ?></div>
                        <div><strong>SĐT:</strong> <?php echo htmlspecialchars($print_settings['company_phone'] ?? 'Chưa có SĐT'); ?></div>
                    </div>
                    <div class="detail-col">
                        <div><strong>NH:</strong> <span id="display_bank_name"><?php echo htmlspecialchars($current_bank_text); ?></span></div>
                        <div><strong>STK:</strong> <span id="display_acc_no"><?php echo htmlspecialchars($print_settings['company_bank_accounts'] ?? $current_acc_no . ' (' . $current_acc_name . ')'); ?></span></div>
                    </div>
                </div>
            </header>

            <h1 class="title">PHIẾU GIAO HÀNG</h1>
            <div class="customer-info-grid">
                <div class="info-col">
                    <p><strong>Khách hàng:</strong> <?php echo htmlspecialchars($order['customer_name'] ?? 'Khách lẻ'); ?></p>
                    <p><strong>Địa chỉ:</strong> <?php echo htmlspecialchars($order['customer_addr']); ?></p>
                    <p><strong>SĐT:</strong> <?php echo htmlspecialchars($order['customer_phone']); ?></p>
                </div>
                <div class="info-col">
                    <p><strong>Số phiếu:</strong> <?php echo htmlspecialchars($order['output_code']); ?></p>
                    <p><strong>Ngày:</strong> <?php echo date('d/m/Y H:i', strtotime($order['sell_date'])); ?></p>
                    <p><strong>NVBH:</strong> <?php echo htmlspecialchars($order['staff_name']); ?></p>
                </div>
            </div>

            <table class="items-table">
                <thead>
                    <tr>
                        <th class="col-code">Mã</th>
                        <th class="col-name" class="text-left">Tên hàng</th>
                        <th class="col-unit">ĐVT</th>
                        <th class="col-qty">SL</th>
                        <th class="col-price" class="text-right">Đơn giá</th>
                        <th class="col-total" class="text-right">Thành tiền</th>
                        <th class="col-disc-p">%KM</th>
                        <th class="col-disc-m" class="text-right">Tiền KM</th>
                        <th class="col-final" class="text-right">Tổng</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($order_items as $item): 
                        $quantity = floatval($item['quantity'] ?? 0);
                        $price = floatval($item['price'] ?? 0);
                        $item_discount_percent = floatval($item['percent'] ?? 0);
                        $line_base_total = $quantity * $price;
                        $line_discount_amount = floatval($item['discount'] ?? 0);
                        $line_total_after_discount = $line_base_total - $line_discount_amount;
                        $item_note = $item['note'] ?? '';
                        
                        $product_id = intval($item['id'] ?? 0);
                        $unit_id = null;
                        $unit_name = 'Cái'; 

                        if ($product_id > 0) {
                            $stmt_product_unit->bind_param("i", $product_id);
                            $stmt_product_unit->execute();
                            $prod_result = $stmt_product_unit->get_result();
                            if ($prod_row = $prod_result->fetch_assoc()) {
                                $unit_id = $prod_row['prd_unit_id'];
                            }
                        }
                        if (isset($units_map[$unit_id])) {
                            $unit_name = $units_map[$unit_id];
                        }
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($item['code']); ?></td>
                        <td class="text-left">
                            <?php echo htmlspecialchars($item['name']); ?>
                            <?php if (!empty($item_note)): ?>
                                <div style="font-size: 8pt; font-style: italic;">(<?php echo htmlspecialchars($item_note); ?>)</div>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($unit_name); ?></td>
                        <td><?php echo number_format($quantity); ?></td>
                        <td class="text-right"><?php echo number_format($price); ?></td>
                        <td class="text-right"><?php echo number_format($line_base_total); ?></td>
                        <td><?php echo ($item_discount_percent > 0) ? number_format($item_discount_percent, 1) : ''; ?></td>
                        <td class="text-right"><?php echo ($line_discount_amount > 0) ? number_format($line_discount_amount) : '0'; ?></td>
                        <td class="text-right"><?php echo number_format($line_total_after_discount); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php $stmt_product_unit->close(); ?>
                    <tr>
                        <td colspan="2" class="text-left"><strong>Tổng cộng</strong></td>
                        <td></td>
                        <td><strong><?php echo number_format($total_quantity); ?></strong></td>
                        <td></td>
                        <td class="text-right"><strong><?php echo number_format($total_price_before_discount); ?></strong></td>
                        <td></td>
                        <td class="text-right"><strong><?php echo number_format($total_discount_on_items); ?></strong></td>
                        <td class="text-right"><strong><?php echo number_format($total_after_discount); ?></strong></td>
                    </tr>
                </tbody>
            </table>
            
            <div class="summary-section">
                <table class="summary-table">
                    <tr>
                        <td style="width: 40%;"></td>
                        <td class="summary-label" style="width: 30%;">Tổng tiền hàng:</td>
                        <td class="summary-value" style="width: 30%;"><?php echo number_format($total_price_before_discount); ?></td>
                    </tr>
                     <tr>
                        <td></td>
                        <td class="summary-label">Chiết khấu SP:</td>
                        <td class="summary-value"><?php echo number_format($total_discount_on_items); ?></td>
                    </tr>
                    <tr>
                        <td>
                            <?php 
                                $order_discount_amount = floatval($order['total_discount'] ?? 0);
                                if (floatval($order['discount_percent']) > 0) {
                                    echo 'CK HĐ (' . number_format($order['discount_percent'], 1) . '%):';
                                } else {
                                    echo 'Chiết khấu HĐ:';
                                }
                            ?>
                        </td>
                        <td class="summary-label">Tiền CK HĐ:</td>
                        <td class="summary-value"><?php echo number_format($order_discount_amount); ?></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td class="summary-label" style="font-size: 11pt;"><strong>Thanh toán:</strong></td>
                        <td class="summary-value" style="font-size: 12pt;"><?php echo number_format($final_total_money); ?></td>
                    </tr>
                </table>
            </div>

            <div class="footer-text">
                <strong>Bằng chữ: <?php echo $total_money_in_words; ?></strong>
            </div>

        </div>

        <footer class="signatures">
            <div class="signer">Kế toán<p>(Ký tên)</p></div>
            <div class="signer">NV Bán hàng<p>(Ký tên)</p></div>
            <div class="signer">Giao hàng<p>(Ký tên)</p></div>
            <div class="signer">Khách hàng<p>(Ký tên)</p></div>
        </footer>
    </div>

    <script>
        // --- LOGIC CUSTOM SELECT BOX ---
        const wrapper = document.getElementById('customBankSelect');
        const trigger = wrapper.querySelector('.custom-select-trigger');
        const options = wrapper.querySelectorAll('.custom-option');
        const binInput = document.getElementById('bankBinInput');
        const nameInput = document.getElementById('bankNameFullInput');
        const triggerLogo = document.getElementById('triggerLogo');
        const triggerText = document.getElementById('triggerText');

        // Mở dropdown khi click
        trigger.addEventListener('click', function() {
            wrapper.classList.toggle('open');
        });

        // Xử lý khi chọn 1 item
        options.forEach(option => {
            option.addEventListener('click', function() {
                // Xóa selected cũ
                options.forEach(opt => opt.classList.remove('selected'));
                // Thêm selected mới
                this.classList.add('selected');
                
                // Lấy data
                const bin = this.getAttribute('data-value');
                const short = this.getAttribute('data-short');
                const full = this.getAttribute('data-fullname');
                const logo = this.getAttribute('data-logo'); // Lấy link logo
                
                // Cập nhật UI trigger: Hiển thị LOGO trên thanh chọn
                triggerText.textContent = short;
                triggerLogo.src = logo; 
                
                // Cập nhật giá trị Input Hidden
                binInput.value = bin;
                nameInput.value = full;
                
                // Đóng dropdown & Cập nhật UI hóa đơn
                wrapper.classList.remove('open');
                updateUI();
            });
        });

        // Đóng dropdown khi click ra ngoài
        window.addEventListener('click', function(e) {
            if (!wrapper.contains(e.target)) {
                wrapper.classList.remove('open');
            }
        });

        // --- CÁC LOGIC CŨ ---

        function openSettings() {
            document.getElementById('bankModal').style.display = 'flex';
        }

        function closeSettings() {
            document.getElementById('bankModal').style.display = 'none';
        }

        // Đóng modal khi click ra vùng đen
        document.getElementById('bankModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeSettings();
            }
        });

        function updateUI() {
            var bin = binInput.value;
            var bankNameFull = nameInput.value;
            var accNo = document.getElementById('accNoInput').value.trim();
            var accName = document.getElementById('accNameInput').value.toUpperCase().trim();
            
            // Cập nhật Text trên Hóa đơn
            var displayAccText = accNo;
            if (accName) displayAccText += " (" + accName + ")";
            
            document.getElementById('display_bank_name').innerText = bankNameFull;
            document.getElementById('display_acc_no').innerText = displayAccText;

            // Cập nhật QR Code (Vẫn dùng link tạo QR để quét tiền)
            var amount = "<?php echo $qrAmount; ?>";
            var contentEncoded = "<?php echo $qrContent_encoded; ?>";
            var accNameEncoded = encodeURIComponent(accName);
            var realQrUrl = `https://img.vietqr.io/image/${bin}-${accNo}-compact2.png?amount=${amount}&addInfo=${contentEncoded}&accountName=${accNameEncoded}`;
            document.getElementById('qrImage').src = realQrUrl;
        }

        function saveAndApply() {
            var data = new FormData();
            data.append('action', 'save_bank_config');
            data.append('bin', binInput.value);
            data.append('bank_name_text', nameInput.value);
            data.append('acc_no', document.getElementById('accNoInput').value.trim());
            data.append('acc_name', document.getElementById('accNameInput').value.toUpperCase().trim());

            var btn = document.querySelector('.btn-save');
            var originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Đang lưu...';
            btn.disabled = true;

            fetch(window.location.href, {
                method: 'POST',
                body: data
            })
            .then(response => response.json())
            .then(result => {
                if(result.status === 'success') {
                    showToast('CẬP NHẬT THÀNH CÔNG!');
                    closeSettings();
                } else {
                    alert('Lỗi: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Có lỗi xảy ra khi lưu.');
            })
            .finally(() => {
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        }

        function showToast(msg) {
            var t = document.getElementById('toast');
            t.innerText = msg;
            t.classList.add('show');
            setTimeout(function(){ t.classList.remove('show'); }, 3000);
        }
    </script>
</body>
</html>