<?php
session_start();
require_once 'includes/config.php';
require_once 'includes/format-currency.php';
require_once 'includes/cai-dat-helper.php';
$_anh_bia_hoi_hoa = layAnhBiaTrang($pdo, 'hoi_hoa');

$ma_gioi_thieu_thanh_vien = '';
$id_thanh_vien_hien_tai = (int)($_SESSION['nguoi_dung_id'] ?? $_SESSION['user_id'] ?? 0);
if ($id_thanh_vien_hien_tai > 0) {
    $stmt_tv = $pdo->prepare("SELECT ma_gioi_thieu FROM thanh_vien WHERE id = ? LIMIT 1");
    $stmt_tv->execute([$id_thanh_vien_hien_tai]);
    $tv_row = $stmt_tv->fetch();
    if ($tv_row) $ma_gioi_thieu_thanh_vien = $tv_row['ma_gioi_thieu'] ?? '';
}

function tao_link_gioi_thieu($ma_gioi_thieu, $loai_noi_dung, $id_noi_dung) {
    if (empty($ma_gioi_thieu) || empty($loai_noi_dung) || empty($id_noi_dung)) return '';
    return 'hoi-hoa.php?ref=' . urlencode($ma_gioi_thieu) . '&item=' . urlencode($loai_noi_dung) . '&id=' . (int)$id_noi_dung;
}

$affiliateItemType = '';
$affiliateItemId = 0;
$affiliateItemTitle = '';
$affiliateItemPrice = 0;
if (isset($_GET['ref']) && trim($_GET['ref']) !== '') {
    $ma_gioi_thieu_san = strtoupper(trim($_GET['ref']));
}
if (isset($_GET['item']) && in_array($_GET['item'], ['khoa_hoc', 'dich_vu', 'tin_tuc'], true)) {
    $affiliateItemType = trim($_GET['item']);
}
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $affiliateItemId = (int)$_GET['id'];
}

$autoOpenBooking = (isset($_GET['autobook']) && (string)$_GET['autobook'] === '1');

if (!empty($affiliateItemType) && $affiliateItemId > 0) {
    switch ($affiliateItemType) {
        case 'khoa_hoc':
            $stmt_affiliate_item = $pdo->prepare("SELECT ten_khoa_hoc AS ten_noi_dung, gia FROM chuong_trinh_dao_tao WHERE id = ? LIMIT 1");
            break;
        case 'dich_vu':
            $stmt_affiliate_item = $pdo->prepare("SELECT ten_dich_vu AS ten_noi_dung, gia FROM dich_vu_su_kien WHERE id = ? LIMIT 1");
            break;
        default:
            $stmt_affiliate_item = $pdo->prepare("SELECT tieu_de AS ten_noi_dung, 0 AS gia FROM tin_tuc_su_kien WHERE id = ? LIMIT 1");
            break;
    }
    $stmt_affiliate_item->execute([$affiliateItemId]);
    $affiliateItemData = $stmt_affiliate_item->fetch();
    if ($affiliateItemData) {
        $affiliateItemTitle = $affiliateItemData['ten_noi_dung'] ?? '';
        $affiliateItemPrice = (float)($affiliateItemData['gia'] ?? 0);
    }
}

function hien_thi_mo_ta_an_toan($noi_dung) {
    if ($noi_dung === null) {
        return '';
    }
    $noi_dung = trim((string)$noi_dung);
    if ($noi_dung === '') {
        return '';
    }
    $noi_dung = html_entity_decode($noi_dung, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    $noi_dung = preg_replace('#</p>#i', '<br>', $noi_dung);
    $noi_dung = preg_replace('#<p[^>]*>#i', '', $noi_dung);
    $noi_dung = strip_tags($noi_dung, '<br>');
    $noi_dung = preg_replace('/\s+/', ' ', $noi_dung);
    $noi_dung = str_replace(['<br>', '<br />'], ['<br>', '<br>'], $noi_dung);
    return $noi_dung;
}

$tin_tuc_db = $pdo->query("SELECT * FROM tin_tuc_su_kien WHERE JSON_CONTAINS(phan_loai, '\"hoa\"') OR (JSON_CONTAINS(phan_loai, '\"chung\"') AND NOT JSON_CONTAINS(phan_loai, '\"nhac\"')) ORDER BY id DESC")->fetchAll();
$khoa_hoc_db = $pdo->query("SELECT * FROM chuong_trinh_dao_tao WHERE JSON_CONTAINS(phan_loai, '\"hoa\"') OR (JSON_CONTAINS(phan_loai, '\"chung\"') AND NOT JSON_CONTAINS(phan_loai, '\"nhac\"')) ORDER BY id DESC")->fetchAll();
$dich_vu_db = $pdo->query("SELECT * FROM dich_vu_su_kien WHERE JSON_CONTAINS(phan_loai, '\"hoa\"') OR (JSON_CONTAINS(phan_loai, '\"chung\"') AND NOT JSON_CONTAINS(phan_loai, '\"nhac\"')) ORDER BY id DESC")->fetchAll();

$sql_hoi_hoa = "SELECT id, ho_ten, vai_tro, diem_uy_tin, anh_dai_dien, linh_vuc_chi_tiet, tinh_thanh,
                    gioi_thieu_ban_than, gioi_thieu_to_chuc, nganh_nghe_chinh
             FROM thanh_vien
             WHERE linh_vuc = 'hoi_hoa'
                OR linh_vuc_chi_tiet LIKE '%hội họa%'
                OR linh_vuc_chi_tiet LIKE '%họa%'
                OR linh_vuc_chi_tiet LIKE '%vẽ%'
                OR linh_vuc_chi_tiet LIKE '%painting%'
                OR linh_vuc_chi_tiet LIKE '%sơn%'
                OR linh_vuc_chi_tiet LIKE '%tranh%'
             ORDER BY diem_uy_tin DESC";
$stmt_hoi_hoa = $pdo->prepare($sql_hoi_hoa);
$stmt_hoi_hoa->execute();
$chuyen_gia_hoi_hoa = $stmt_hoi_hoa->fetchAll();
$tong_so_thanh_vien = count($chuyen_gia_hoi_hoa);

$ds_tinh_thanh = $pdo->query("SELECT DISTINCT tinh_thanh FROM thanh_vien WHERE tinh_thanh IS NOT NULL AND tinh_thanh != '' ORDER BY tinh_thanh ASC")->fetchAll(PDO::FETCH_COLUMN);
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Không gian Hội họa - PHẠM NGỌC TV</title>
    <link rel="icon" type="image/png" href="images/icon.png">
    <link rel="apple-touch-icon" href="images/icon.png">
    <link rel="stylesheet" href="includes/style.css">
    <style>
        body { background-color: #f8f7f2; margin: 0; color: #333; }
        .khu-vuc-hero { background: linear-gradient(135deg, #a05a0f 0%, #d4891b 100%); color: white; padding: 50px 20px; text-align: center; background-size: cover; background-position: center; position: relative; }
        .khu-vuc-hero::before { content:''; position:absolute; inset:0; background:rgba(100,50,5,0.65); }
        .khu-vuc-hero > * { position: relative; z-index: 1; }
        .khu-vuc-hero h1 { margin: 10px 0; font-size: 32px; }
        .khu-vuc-hero p { margin: 0; font-size: 16px; opacity: 0.95; }
        .nut-tro-ve { display: inline-block; padding: 8px 20px; background: rgba(255,255,255,0.2); color: white; text-decoration: none; border-radius: 20px; font-size: 14px; margin-bottom: 20px; }
        .nut-tro-ve:hover { background: rgba(255,255,255,0.3); }
        .thanh-menu-tab { display: flex; background: white; border-bottom: 1px solid #dee2e6; max-width: 1200px; margin: 0 auto; }
        .nut-tab { flex: 1; padding: 18px 10px; background: none; border: none; border-bottom: 3px solid transparent; font-size: 14px; font-weight: bold; color: #495057; cursor: pointer; text-transform: uppercase; transition: 0.2s; }
        .nut-tab:hover { color: #a05a0f; }
        .nut-tab.dang-chon { color: #a05a0f; border-bottom-color: #a05a0f; }
        .vung-noi-dung { max-width: 1200px; margin: 0 auto; padding: 30px 20px; box-sizing: border-box; }
        .noi-dung-tab { display: none; animation: hienThiMượt 0.4s ease; }
        .noi-dung-tab.hien-thi { display: block; }
        @keyframes hienThiMượt { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .thanh-cong-cu-loc { display: flex; gap: 15px; align-items: center; margin-bottom: 25px; background: #ffffff; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6; box-shadow: 0 2px 8px rgba(0,0,0,0.02); }
        .o-nhap-tim-kiem { flex: 2; padding: 12px 15px; border: 1px solid #ced4da; border-radius: 6px; font-size: 14px; background: #fcfcfc; box-sizing: border-box; }
        .o-nhap-tim-kiem:focus { border-color: #a05a0f; outline: none; background: #fff; }
        .bo-loc-tinh-thanh { flex: 1; padding: 12px 15px; border: 1px solid #ced4da; border-radius: 6px; font-size: 14px; background: #fff; cursor: pointer; box-sizing: border-box; }
        .chi-so-hien-thi { font-size: 14px; color: #666; min-width: 140px; text-align: right; }
        .luoi-the { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 30px; }
        .the-dich-vu { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #e1e8ed; transition: 0.3s; display: flex; flex-direction: column; }
        .the-dich-vu:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); border-color: #a05a0f; }
        .anh-the { width: 100%; aspect-ratio: 600 / 350; display: flex; align-items: center; justify-content: center; font-size: 50px; background: #fff8e8; border-bottom: 1px solid #f1f3f5; overflow: hidden; }
        .anh-the-img { width: 100%; height: 100%; object-fit: contain; object-position: center; display: block; }
        .noi-dung-the { padding: 25px; flex: 1; }
        .mo-ta-the { font-size: 14px; color: #555; line-height: 1.6; margin-bottom: 20px; max-height: calc(1.6em * 3); overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 3; line-clamp: 3; -webkit-box-orient: vertical; }
        .mo-ta-the.mo-ta-dai { max-height: none; -webkit-line-clamp: unset; line-clamp: unset; }
        .action-row { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; margin-top: 20px; }
        .nut-xem-them { display: inline-flex; align-items: center; gap: 6px; margin-top: 12px; color: #a05a0f; font-weight: 700; text-decoration: none; cursor: pointer; border: none; background: none; padding: 0; font-size: 14px; }
        .nut-xem-them:hover { text-decoration: underline; }
        .ten-the { font-size: 18px; font-weight: bold; color: #a05a0f; margin: 0 0 10px 0; }
        .gia-the { font-size: 16px; font-weight: bold; color: #e03131; margin-bottom: 20px; }
        .nut-hanh-dong { display: block; width: 100%; padding: 12px; text-align: center; background: #a05a0f; color: white; text-decoration: none; border-radius: 6px; font-weight: bold; cursor: pointer; border: none; font-size: 14px; transition: 0.2s; box-sizing: border-box; }
        .nut-hanh-dong:hover { background: #864d0c; }
        .link-gioi-thieu { display: inline-flex; align-items: center; gap: 6px; margin-top: 10px; font-size: 13px; font-weight: 600; color: #28a745; text-decoration: none; cursor: pointer; }
        .link-gioi-thieu:hover { color: #1e7e34; text-decoration: underline; }
        .the-ho-so { background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.04); border: 1px solid #e1e8ed; display: flex; flex-direction: column; transition: 0.3s; }
        .the-ho-so:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(0,0,0,0.08); }
        .phan-dau-ho-so { padding: 20px; display: flex; align-items: center; gap: 15px; border-bottom: 1px solid #f1f3f5; }
        .anh-ho-so { width: 65px; height: 65px; border-radius: 50%; object-fit: cover; background: #f8efe0; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: bold; color: #a05a0f; border: 1px solid #e7d1a7; }
        .thong-tin-nghe-danh { display: flex; flex-direction: column; gap: 6px; }
        .nhan-chuyen-mon { font-size: 12px; padding: 4px 10px; background: #fdf4e3; color: #a05a0f; border-radius: 4px; border: 1px solid #efd3a4; width: fit-content; font-weight: 500; }
        .phan-noi-dung-ho-so { padding: 20px; flex: 1; font-size: 14px; color: #495057; display: flex; flex-direction: column; gap: 10px; }
        .dong-uy-tin { color: #d39e00; font-weight: bold; display: flex; align-items: center; gap: 6px; }
        .dong-tinh-thanh { color: #666; display: flex; align-items: center; gap: 6px; font-size: 13px; }
        .tieu-su-trich-doan { font-style: italic; color: #555; line-height: 1.5; margin-top: 5px; }
        .modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(46, 23, 4, 0.72); z-index: 1000; align-items: center; justify-content: center; backdrop-filter: blur(4px); padding: 16px; box-sizing: border-box; }
        .modal-overlay.show { display: flex; }
        .modal-box { background: linear-gradient(145deg, #ffffff 0%, #fffaf1 100%); padding: 24px; border-radius: 18px; width: 100%; max-width: 560px; box-shadow: 0 26px 55px rgba(68, 42, 10, 0.12); position: relative; border: 1px solid #edd7b4; max-height: calc(100vh - 48px); overflow-y: auto; -webkit-overflow-scrolling: touch; }
        .modal-box h3 { margin-top: 0; margin-bottom: 8px; color: #5b2f04; font-size: 24px; font-weight: 800; }
        .modal-box .modal-subtitle { margin: 10px 0 18px; padding: 14px 16px; border-radius: 16px; background: rgba(160, 90, 15, 0.08); color: #8d4900; font-size: 13px; font-weight: 600; }
        .modal-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
        .modal-form-grid .field-group { display: flex; flex-direction: column; }
        .modal-form-grid .field-group.full { grid-column: 1 / -1; }
        .modal-form-grid .field-group label { font-size: 12px; color: #7e5c2a; margin-bottom: 6px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; }
        .modal-form-grid .field-group input,
        .modal-form-grid .field-group textarea { width: 100%; padding: 14px 16px; border-radius: 14px; border: 1px solid #e6cf9f; background: #fffcf7; font-size: 14px; color: #3e2b09; box-sizing: border-box; }
        .modal-form-grid .field-group input:focus,
        .modal-form-grid .field-group textarea:focus { border-color: #a05a0f; outline: none; box-shadow: 0 0 0 4px rgba(160,90,15,0.15); }
        .modal-form-grid .field-group input[readonly] { background: #fef3db; border-color: #ecd0a1; font-weight: 700; letter-spacing: 0.06em; text-align: center; color: #6b3d09; }
        .modal-form-grid .field-group.small { min-width: 120px; }
        .modal-box form { margin-top: 8px; }
        .form-actions { display:flex; gap:12px; align-items:center; justify-content:flex-end; grid-column: 1 / -1; margin-top: 16px; }
        .form-actions .nut-hanh-dong { width: 100%; max-width: 220px; }
        .nut-hanh-dong.secondary { background:#fff; color:#a05a0f; border:1px solid #e6cf9f; padding:12px 16px; min-width:140px; }
        .nut-hanh-dong.secondary:hover { background:#fff7e8; }
        .modal-box .dong-modal { position: absolute; top: 18px; right: 18px; cursor: pointer; font-size: 24px; color: #7c6d4b; line-height: 1; }
        .modal-box .dong-modal:hover { color: #bf3b44; }
        .payment-heading { margin: 0 0 12px; color: #5b2f04; font-size: 18px; font-weight: 700; }
        .payment-details { display: grid; gap: 10px; background: #fffaf1; padding: 16px; border-radius: 14px; border: 1px solid #efd3a4; }
        .payment-details div { line-height: 1.5; color: #5b3b16; }
        .payment-qr { display: grid; gap: 10px; justify-items: center; margin-top: 10px; }
        .qr-box { width: 160px; height: 160px; border-radius: 18px; background: #fff; display: flex; align-items: center; justify-content: center; border: 1px solid #efd3a4; }
        .qr-image { width: 140px; height: 140px; display: block; }
        .qr-text { font-size: 13px; color: #6f4f2b; }
        @media (max-width:768px) {
            .modal-box { padding: 18px; }
            .modal-form-grid { grid-template-columns: 1fr; }
            .modal-form-grid .field-group.small { min-width: auto; }
            .form-actions { flex-direction: column-reverse; align-items: stretch; }
        }
        @media (max-width: 768px) {
            .modal-overlay { align-items: flex-end; padding: 0; }
            .modal-box { padding: 18px; border-radius: 12px 12px 0 0; width: 100%; max-width: 100%; max-height: 92vh; margin: 0; border-left: none; border-right: none; }
            body.modal-open { overflow: hidden; }
        }
    </style>
</head>
<body>
    <div class="khu-vuc-hero"<?php if($_anh_bia_hoi_hoa): ?> style="background-image:url('<?php echo htmlspecialchars($_anh_bia_hoi_hoa); ?>')"<?php endif; ?>>
        <a href="index.php" class="nut-tro-ve">⬅ Trở về Sảnh chính</a>
        <h1>Không gian Hội họa</h1>
        <p>Kết nối lớp học vẽ, dịch vụ sáng tác, triển lãm và các hoạt động nghệ thuật</p>
    </div>

    <div style="background: white; border-bottom: 1px solid #dee2e6;">
        <div class="thanh-menu-tab">
            <button class="nut-tab dang-chon" onclick="moTab(event, 'tab-tin-tuc')">Tin tức & Sự kiện</button>
            <button class="nut-tab" onclick="moTab(event, 'tab-dao-tao')">Chương trình Đào tạo</button>
            <button class="nut-tab" onclick="moTab(event, 'tab-dich-vu')">Dịch vụ Đặt lịch</button>
            <button class="nut-tab" onclick="moTab(event, 'tab-ho-so')">Hồ sơ Thành viên</button>
        </div>
    </div>

    <div class="vung-noi-dung">
        <div id="tab-tin-tuc" class="noi-dung-tab hien-thi">
            <div class="luoi-the">
                <?php if (count($tin_tuc_db) > 0): ?>
                    <?php foreach ($tin_tuc_db as $tin): ?>
                        <div class="the-dich-vu">
                            <div class="anh-the">
                                <?php if (!empty($tin['anh_bia'])): ?>
                                    <img src="<?php echo htmlspecialchars($tin['anh_bia'], ENT_QUOTES); ?>" alt="<?php echo htmlspecialchars($tin['tieu_de'], ENT_QUOTES); ?>" class="anh-the-img">
                                <?php else: ?>
                                    <?php echo $tin['bieu_tuong']; ?>
                                <?php endif; ?>
                            </div>
                            <div class="noi-dung-the">
                                <div style="font-size: 12px; color: #a05a0f; font-weight: bold; margin-bottom: 10px;">
                                    <?php echo ($tin['loai_tin'] == 'su_kien') ? 'SỰ KIỆN SẮP TỚI' : (($tin['loai_tin'] == 'tin_moi') ? 'TIN MỚI' : 'TIN NỔI BẬT'); ?>
                                </div>
                                <h3 class="ten-the"><?php echo htmlspecialchars($tin['tieu_de']); ?></h3>
                                <?php if (!empty($tin['ngay_dien_ra'])): ?>
                                    <div style="font-size:13px; color:#495057; font-weight:600; margin: 8px 0 12px;">Ngày diễn ra: <?php echo date('d/m/Y', strtotime($tin['ngay_dien_ra'])); ?></div>
                                <?php endif; ?>
                                <div class="mo-ta-the"><?php echo hien_thi_mo_ta_an_toan($tin['mo_ta'] ?? ''); ?></div>
                                <div class="action-row">
                                    <a href="chi-tiet-tin-tuc.php?id=<?php echo (int)$tin['id']; ?>" class="nut-hanh-dong secondary">Xem chi tiết ➜</a>
                                    <?php
                                    $link_chia_se_full = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/chi-tiet-tin-tuc.php?id=' . (int)$tin['id'];
                                    if (!empty($ma_gioi_thieu_thanh_vien)) {
                                        $link_chia_se_full .= '&ref=' . urlencode($ma_gioi_thieu_thanh_vien);
                                    }
                                    ?>
                                    <button type="button" class="nut-hanh-dong secondary" onclick="moModalChiaSe('<?php echo htmlspecialchars($link_chia_se_full, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($tin['tieu_de'], ENT_QUOTES); ?>')">🔗 Chia sẻ</button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p style="grid-column: 1/-1; text-align:center; color:#999;">Bảng tin hệ thống hiện tại đang được cập nhật.</p>
                <?php endif; ?>
            </div>
        </div>

        <div id="tab-dao-tao" class="noi-dung-tab">
            <div class="luoi-the">
                <?php if (count($khoa_hoc_db) > 0): ?>
                    <?php foreach ($khoa_hoc_db as $kh):
                        $kh_ngay = isset($kh['ngay_dien_ra']) && $kh['ngay_dien_ra'] ? date('Y-m-d', strtotime($kh['ngay_dien_ra'])) : '';
                    ?>
                        <div class="the-dich-vu" data-id="<?php echo (int)$kh['id']; ?>" data-item-type="khoa_hoc" data-ngay-dien-ra="<?php echo $kh_ngay; ?>">
                            <div class="anh-the">
                                <?php if (!empty($kh['anh_bia'])): ?>
                                    <img src="<?php echo htmlspecialchars($kh['anh_bia'], ENT_QUOTES); ?>" alt="<?php echo htmlspecialchars($kh['ten_khoa_hoc'], ENT_QUOTES); ?>" class="anh-the-img">
                                <?php else: ?>
                                    <?php echo $kh['bieu_tuong']; ?>
                                <?php endif; ?>
                            </div>
                            <div class="noi-dung-the">
                                <h3 class="ten-the"><?php echo htmlspecialchars($kh['ten_khoa_hoc']); ?></h3>
                                <?php if (!empty($kh['ngay_dien_ra'])): ?>
                                    <div style="font-size:13px; color:#495057; font-weight:600; margin: 8px 0 12px;">Ngày khai giảng: <?php echo date('d/m/Y', strtotime($kh['ngay_dien_ra'])); ?></div>
                                <?php endif; ?>
                                <div class="mo-ta-the"><?php echo hien_thi_mo_ta_an_toan($kh['mo_ta'] ?? ''); ?></div>
                                <button type="button" class="nut-xem-them" onclick="toggleMoTa(this)">Xem thêm</button>
                                <div class="gia-the"><?php echo dinh_dang_tien($kh['gia'], 'khoa_hoc'); ?></div>
                            </div>
                            <div style="padding: 0 25px 25px;">
                                <button class="nut-hanh-dong" onclick="moFormDatLich('Tư vấn: <?php echo htmlspecialchars($kh['ten_khoa_hoc'], ENT_QUOTES); ?>', 'khoa_hoc', <?php echo (int)$kh['id']; ?>, <?php echo (float)$kh['gia']; ?>)">Đăng ký Tư vấn</button>
                                <?php if (!empty($ma_gioi_thieu_thanh_vien)): ?>
                                    <?php $link_khoa_hoc = tao_link_gioi_thieu($ma_gioi_thieu_thanh_vien, 'khoa_hoc', $kh['id']); ?>
                                    <?php if (!empty($link_khoa_hoc)): ?>
                                        <?php $link_khoa_hoc_full = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/' . $link_khoa_hoc; ?>
                                        <button type="button" class="link-gioi-thieu" onclick="moModalChiaSe('<?php echo htmlspecialchars($link_khoa_hoc_full, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($kh['ten_khoa_hoc'], ENT_QUOTES); ?>')" style="border:none; background:none; cursor:pointer; padding:0;">🔗 Link giới thiệu</button>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p style="grid-column: 1/-1; text-align:center; color:#999;">Hiện tại chưa có khóa học nào được thiết lập.</p>
                <?php endif; ?>
            </div>
        </div>

        <div id="tab-dich-vu" class="noi-dung-tab">
            <div style="text-align: center; max-width: 800px; margin: 0 auto 40px;">
                <h2 style="color: #a05a0f;">Dịch Vụ Cung Cấp Sự Kiện</h2>
                <p style="color: #666;">Hệ thống cung cấp dịch vụ sáng tác, triển lãm, tư vấn và chuẩn bị tác phẩm cho các sự kiện nghệ thuật.</p>
            </div>
            <div class="luoi-the">
                <?php if (count($dich_vu_db) > 0): ?>
                    <?php foreach ($dich_vu_db as $dv):
                        $dv_ngay = isset($dv['ngay_tao']) && $dv['ngay_tao'] ? date('Y-m-d', strtotime($dv['ngay_tao'])) : '';
                    ?>
                        <div class="the-dich-vu" data-id="<?php echo (int)$dv['id']; ?>" data-item-type="dich_vu" data-ngay-dang="<?php echo $dv_ngay; ?>">
                            <div class="anh-the">
                                <?php if (!empty($dv['anh_bia'])): ?>
                                    <img src="<?php echo htmlspecialchars($dv['anh_bia'], ENT_QUOTES); ?>" alt="<?php echo htmlspecialchars($dv['ten_dich_vu'], ENT_QUOTES); ?>" class="anh-the-img">
                                <?php else: ?>
                                    <?php echo $dv['bieu_tuong']; ?>
                                <?php endif; ?>
                            </div>
                            <div class="noi-dung-the">
                                <h3 class="ten-the"><?php echo htmlspecialchars($dv['ten_dich_vu']); ?></h3>
                                <?php if (!empty($dv['ngay_tao'])): ?>
                                    <div style="font-size:13px; color:#495057; font-weight:600; margin: 8px 0 12px;">Ngày đăng: <?php echo date('d/m/Y', strtotime($dv['ngay_tao'])); ?></div>
                                <?php endif; ?>
                                <div class="mo-ta-the"><?php echo hien_thi_mo_ta_an_toan($dv['mo_ta'] ?? ''); ?></div>
                                <button type="button" class="nut-xem-them" onclick="toggleMoTa(this)">Xem thêm</button>
                                <?php if (!empty($dv['gia'])): ?>
                                    <div class="gia-the"><?php echo dinh_dang_tien($dv['gia'], 'dich_vu'); ?></div>
                                <?php endif; ?>
                            </div>
                            <div style="padding: 0 25px 25px;">
                                <button class="nut-hanh-dong" onclick="moFormDatLich('Đặt lịch: <?php echo htmlspecialchars($dv['ten_dich_vu'], ENT_QUOTES); ?>', 'dich_vu', <?php echo (int)$dv['id']; ?>, <?php echo (float)$dv['gia']; ?>)">Đặt Lịch Ngay</button>
                                <?php if (!empty($ma_gioi_thieu_thanh_vien)): ?>
                                    <?php $link_dich_vu = tao_link_gioi_thieu($ma_gioi_thieu_thanh_vien, 'dich_vu', $dv['id']); ?>
                                    <?php if (!empty($link_dich_vu)): ?>
                                        <?php $link_dich_vu_full = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/' . $link_dich_vu; ?>
                                        <button type="button" class="link-gioi-thieu" onclick="moModalChiaSe('<?php echo htmlspecialchars($link_dich_vu_full, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($dv['ten_dich_vu'], ENT_QUOTES); ?>')" style="border:none; background:none; cursor:pointer; padding:0;">🔗 Link giới thiệu</button>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p style="grid-column: 1/-1; text-align:center; color:#999;">Hiện tại chưa có dịch vụ nào được thiết lập.</p>
                <?php endif; ?>
            </div>
        </div>

        <div id="tab-ho-so" class="noi-dung-tab">
            <div class="thanh-cong-cu-loc">
                <input type="text" id="o_tim_kiem" class="o-nhap-tim-kiem" placeholder="Tìm theo tên, nghề nghiệp, lĩnh vực..." onkeyup="xuLyLocThanhVien()">
                <select id="bo_loc_tinh" class="bo-loc-tinh-thanh" onchange="xuLyLocThanhVien()">
                    <option value="tat_ca">📍 Tất cả tỉnh thành</option>
                    <?php foreach ($ds_tinh_thanh as $tinh): ?>
                        <option value="<?php echo htmlspecialchars($tinh); ?>"><?php echo htmlspecialchars($tinh); ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="chi-so-hien-thi">Hiển thị: <strong id="so_luong_hien_thi" style="color: #a05a0f;">
                    <?php echo $tong_so_thanh_vien; ?></strong> thành viên</div>
            </div>

            <div class="luoi-the" id="luoi_ho_so_nghe_si">
                <?php if ($tong_so_thanh_vien > 0): ?>
                    <?php foreach ($chuyen_gia_hoi_hoa as $tv):
                        $ten_nghe_si = !empty($tv['ho_ten']) ? htmlspecialchars($tv['ho_ten']) : 'Thành viên hệ thống';
                        $chuyen_mon = !empty($tv['linh_vuc_chi_tiet']) ? htmlspecialchars($tv['linh_vuc_chi_tiet']) : (($tv['vai_tro'] == 'to_chuc') ? 'Tổ chức' : 'Nghệ sĩ Hội họa');
                        $tinh_thanh_hien_thi = !empty($tv['tinh_thanh']) ? htmlspecialchars($tv['tinh_thanh']) : 'Chưa cập nhật vị trí';
                        $tieu_su = ($tv['vai_tro'] == 'to_chuc') ? ($tv['gioi_thieu_to_chuc'] ?? '') : ($tv['gioi_thieu_ban_than'] ?? '');
                    ?>
                        <div class="the-ho-so card-thanh-vien"
                            data-ten="<?php echo mb_strtolower($ten_nghe_si, 'UTF-8'); ?>"
                            data-nganh="<?php echo mb_strtolower($chuyen_mon, 'UTF-8'); ?>"
                            data-tinh="<?php echo mb_strtolower(htmlspecialchars($tv['tinh_thanh'] ?? ''), 'UTF-8'); ?>">
                            <div class="phan-dau-ho-so">
                                <?php if (!empty($tv['anh_dai_dien'])): ?>
                                    <img src="<?php echo htmlspecialchars($tv['anh_dai_dien']); ?>" class="anh-ho-so">
                                <?php else: ?>
                                    <div class="anh-ho-so"><?php echo mb_substr($ten_nghe_si, 0, 1, 'UTF-8'); ?></div>
                                <?php endif; ?>
                                <div class="thong-tin-nghe-danh">
                                    <h3 style="margin: 0; font-size: 16px; color: #a05a0f;"><?php echo $ten_nghe_si; ?></h3>
                                    <span class="nhan-chuyen-mon"><?php echo $chuyen_mon; ?></span>
                                </div>
                            </div>
                            <div class="phan-noi-dung-ho-so">
                                <div class="dong-uy-tin">⭐ Uy tín: <?php echo $tv['diem_uy_tin'] ?? 0; ?>/100</div>
                                <div class="dong-tinh-thanh">📍 <?php echo $tinh_thanh_hien_thi; ?></div>
                                <?php if (!empty($tieu_su)): ?>
                                    <div class="tieu-su-trich-doan">"<?php echo htmlspecialchars(mb_strimwidth($tieu_su, 0, 120, '...')); ?>"</div>
                                <?php else: ?>
                                    <div class="tieu-su-trich-doan" style="color:#adb5bd;">Chưa cập nhật thông tin tiểu sử năng lực.</div>
                                <?php endif; ?>
                            </div>
                            <a href="chi-tiet-ho-so.php?id=<?php echo $tv['id']; ?>" class="nut-hanh-dong" style="border-radius: 0;">XEM NĂNG LỰC HỢP TÁC</a>
                        </div>
                    <?php endforeach; ?>
                    <div id="ho-so-xem-them-row" style="display:none; text-align:center; margin-top:20px;">
                        <button type="button" class="nut-hanh-dong secondary" id="btnXemThemHoSo" onclick="xemThemHoSo()">Xem thêm thành viên</button>
                    </div>
                <?php else: ?>
                    <div id="khong_co_du_lieu" style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666; border: 1px dashed #ccc; border-radius: 8px; background: white;">
                        Hệ thống đang cập nhật danh sách chuyên gia lĩnh vực Hội họa.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div id="modalDatLich" class="modal-overlay">
        <div class="modal-box">
            <span class="dong-modal" onclick="dongFormDatLich()">&times;</span>
            <h3>Gửi Yêu Cầu Đặt Lịch</h3>
            <form action="xu-ly-dat-lich.php" method="POST">
                <input type="hidden" name="linh_vuc" id="linh_vuc_input" value="hoi_hoa">
                <div class="modal-form-grid">
                    <div class="field-group full">
                        <label>Dịch vụ / Khóa học đang quan tâm</label>
                        <input type="text" id="inputDichVu" name="dich_vu_quan_tam" readonly placeholder="Đang chọn dịch vụ">
                    </div>
                    <div class="field-group small">
                        <label>Số lượng</label>
                        <input type="number" name="so_luong" min="1" value="1" required placeholder="Số lượng">
                    </div>
                    <div class="field-group small" id="don_gia_row" style="display:none;">
                        <label>Đơn giá</label>
                        <input type="text" id="don_gia_input" readonly placeholder="Đơn giá">
                    </div>
                    <?php if (!empty($ma_gioi_thieu_san)) :?>
                        <div class="field-group small" id="ma_gioi_thue_row">
                            <label>Mã SPNT</label>
                            <input type="text" name="ma_gioi_thieu" id="ma_gioi_thieu_input" value="<?php echo htmlspecialchars($ma_gioi_thieu_san ?? ''); ?>" readonly placeholder="Mã SPNT">
                        </div>
                    <?php endif; ?>
                    <div class="field-group small">
                        <label>Điện thoại</label>
                        <input type="tel" name="so_dien_thoai" required placeholder="Điện thoại">
                    </div>
                    <div class="field-group small">
                        <label>Ngày sự kiện</label>
                        <input type="date" name="ngay_su_kien" placeholder="Ngày sự kiện">
                    </div>
                    <div class="field-group">
                        <label>Tỉnh / Thành</label>
                        <input type="text" name="tinh_thanh" placeholder="Ví dụ: Hà Nội">
                    </div>
                    <div class="field-group full">
                        <label>Địa chỉ cụ thể</label>
                        <input type="text" name="dia_chi" placeholder="Số nhà, đường, phường/xã...">
                    </div>
                    <div class="field-group full">
                        <label>Họ và tên</label>
                        <input type="text" name="ten_khach_hang" required placeholder="Họ và tên">
                    </div>
                    <div class="field-group full">
                        <label>Yêu cầu ngắn</label>
                        <textarea name="ghi_chu" rows="3" placeholder="Yêu cầu ngắn"></textarea>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="submit" class="nut-hanh-dong">ĐĂNG KÝ</button>
                    <button type="button" class="nut-hanh-dong secondary" onclick="showPaymentInfo()">THANH TOÁN</button>
                </div>
            </form>
        </div>
    </div>

    <div id="paymentPopup" class="modal-overlay" style="display:none;">
        <div class="modal-box">
            <span class="dong-modal" onclick="hidePaymentPopup()">&times;</span>
            <h3>Thanh toán</h3>
            <div class="payment-heading">Thông tin thanh toán</div>
            <div class="payment-details">
                <div><strong>Ngân hàng:</strong> MB Bank</div>
                <div><strong>Số tài khoản:</strong> 68228568888</div>
                <div><strong>Chủ tài khoản:</strong> PHẠM LINH NGỌC</div>
                <div><strong>Chi nhánh:</strong> Hà Nội</div>
                <div><strong>Nội dung chuyển khoản:</strong> <span id="paymentLabel"></span></div>
                <div><strong>Số tiền:</strong> <span id="paymentAmount"></span></div>
                <div class="payment-qr">
                    <div class="qr-box">
                        <div class="qr-image" id="paymentQrContainer"></div>
                    </div>
                    <div class="qr-text">Quét mã để thanh toán</div>
                </div>
                <div style="margin-top: 12px; font-size: 13px; color: #33475b;">Sau khi thanh toán, giữ lại xác nhận và liên hệ chúng tôi để xác nhận đơn hàng.</div>
            </div>
            <button type="button" class="nut-hanh-dong secondary" onclick="hidePaymentPopup()" style="margin-top: 16px; width: 100%;">ĐÓNG</button>
        </div>
    </div>

    <div id="modalChiaSe" class="modal-overlay" style="display:none;">
        <div class="modal-box">
            <span class="dong-modal" onclick="dongModalChiaSe()">&times;</span>
            <h3>Chia sẻ nội dung</h3>
            <div class="modal-subtitle" id="tieuDeChiaSe"></div>
            <div style="margin-bottom: 16px;">
                <label style="display: block; font-size: 12px; color: #7e5c2a; margin-bottom: 8px; font-weight: 600; text-transform: uppercase;">Link chia sẻ</label>
                <div style="display: flex; gap: 8px;">
                    <input type="text" id="linkChiaSe" readonly style="flex: 1; padding: 12px 14px; border: 1px solid #e6cf9f; border-radius: 8px; background: #fffcf7; font-size: 13px; color: #3e2b09; box-sizing: border-box;">
                    <button type="button" class="nut-hanh-dong" onclick="saoChepLink()" style="min-width: 120px; padding: 12px 16px;">📋 Sao chép</button>
                </div>
            </div>
            <div style="margin-bottom: 16px;">
                <label style="display: block; font-size: 12px; color: #7e5c2a; margin-bottom: 8px; font-weight: 600; text-transform: uppercase;">Chia sẻ lên mạng xã hội</label>
                <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <button type="button" class="nut-hanh-dong secondary" onclick="chiaSeLenFacebook()" style="flex: 1; min-width: 100px; padding: 10px 12px; font-size: 13px;">👍 Facebook</button>
                    <button type="button" class="nut-hanh-dong secondary" onclick="chiaSeLenZalo()" style="flex: 1; min-width: 100px; padding: 10px 12px; font-size: 13px;">💬 Zalo</button>
                    <button type="button" class="nut-hanh-dong secondary" onclick="chiaSeLenTwitter()" style="flex: 1; min-width: 100px; padding: 10px 12px; font-size: 13px;">𝕏 Twitter</button>
                </div>
            </div>
            <button type="button" class="nut-hanh-dong secondary" onclick="dongModalChiaSe()" style="width: 100%;">ĐÓNG</button>
        </div>
    </div>

    <script>
        function moTab(suKien, tenTab) {
            var noiDungTabs = document.getElementsByClassName("noi-dung-tab");
            for (var i = 0; i < noiDungTabs.length; i++) {
                noiDungTabs[i].classList.remove("hien-thi");
            }
            var nutTabs = document.getElementsByClassName("nut-tab");
            for (var i = 0; i < nutTabs.length; i++) {
                nutTabs[i].classList.remove("dang-chon");
            }
            document.getElementById(tenTab).classList.add("hien-thi");
            suKien.currentTarget.classList.add("dang-chon");
        }

        function xuLyLocThanhVien() {
            var tuKhoa = document.getElementById("o_tim_kiem").value.toLowerCase().normalize("NFC");
            var tinhThanh = document.getElementById("bo_loc_tinh").value.toLowerCase().normalize("NFC");
            var danhSachCard = document.getElementsByClassName("card-thanh-vien");
            var demSoLuong = 0;

            for (var i = 0; i < danhSachCard.length; i++) {
                var ten = danhSachCard[i].getAttribute("data-ten").toLowerCase().normalize("NFC");
                var nganh = danhSachCard[i].getAttribute("data-nganh").toLowerCase().normalize("NFC");
                var tinh = danhSachCard[i].getAttribute("data-tinh").toLowerCase().normalize("NFC");
                var khopTuKhoa = !tuKhoa || ten.includes(tuKhoa) || nganh.includes(tuKhoa);
                var khopTinhThanh = (tinhThanh === "tat_ca") || tinh === tinhThanh;

                if (khopTuKhoa && khopTinhThanh) {
                    danhSachCard[i].style.display = "flex";
                    demSoLuong++;
                } else {
                    danhSachCard[i].style.display = "none";
                }
            }
            document.getElementById("so_luong_hien_thi").innerText = demSoLuong;
            capNhatHoSoAnHien();
        }

        function capNhatHoSoAnHien() {
            var cards = document.querySelectorAll('#tab-ho-so .card-thanh-vien');
            var visibleCards = [];
            cards.forEach(function(card) {
                if (card.style.display !== 'none') {
                    visibleCards.push(card);
                }
            });
            var xemThemRow = document.getElementById('ho-so-xem-them-row');
            if (!xemThemRow) {
                return;
            }
            if (visibleCards.length > 6) {
                visibleCards.forEach(function(card, index) {
                    card.style.display = index < 6 ? 'flex' : 'none';
                });
                xemThemRow.style.display = 'block';
            } else {
                visibleCards.forEach(function(card) {
                    card.style.display = 'flex';
                });
                xemThemRow.style.display = 'none';
            }
        }

        function xemThemHoSo() {
            var cards = document.querySelectorAll('#tab-ho-so .card-thanh-vien');
            cards.forEach(function(card) {
                card.style.display = 'flex';
            });
            var xemThemRow = document.getElementById('ho-so-xem-them-row');
            if (xemThemRow) {
                xemThemRow.style.display = 'none';
            }
        }

        function toggleMoTa(button) {
            var moTa = button.parentNode.querySelector('.mo-ta-the');
            if (!moTa) return;
            var expanded = moTa.classList.toggle('mo-ta-dai');
            button.innerText = expanded ? 'Thu gọn' : 'Xem thêm';
        }

        var autoOpenItemType = '<?php echo htmlspecialchars($affiliateItemType); ?>';
        var autoOpenItemId = <?php echo json_encode($affiliateItemId); ?>;
        var autoOpenItemTitle = '<?php echo htmlspecialchars($affiliateItemTitle, ENT_QUOTES); ?>';
        var autoOpenItemPrice = <?php echo json_encode($affiliateItemPrice); ?>;
        var autoOpenBooking = <?php echo $autoOpenBooking ? 'true' : 'false'; ?>;

        document.addEventListener('DOMContentLoaded', function() {
            capNhatHoSoAnHien();
            if (autoOpenBooking && autoOpenItemTitle && autoOpenItemId > 0) {
                moFormDatLich(autoOpenItemTitle, autoOpenItemType || 'hoi_hoa', autoOpenItemId, autoOpenItemPrice);
            }
        });

        var modal = document.getElementById("modalDatLich");
        var currentReferralCode = '<?php echo htmlspecialchars($ma_gioi_thieu_san ?? ''); ?>';

        function moFormDatLich(tenDichVu, itemType, itemId, gia = 0) {
            document.getElementById("inputDichVu").value = tenDichVu;
            var manualInput = document.getElementById('ma_gioi_thieu_input');
            var codeRow = document.getElementById('ma_gioi_thue_row');
            if (currentReferralCode && manualInput && codeRow) {
                manualInput.value = currentReferralCode;
                codeRow.style.display = 'block';
            } else if (codeRow) {
                codeRow.style.display = 'none';
            }

            var priceRow = document.getElementById('don_gia_row');
            var priceInput = document.getElementById('don_gia_input');
            if (priceRow && priceInput) {
                if (gia > 0) {
                    priceRow.style.display = 'block';
                    priceInput.value = gia.toLocaleString('vi-VN', { style: 'currency', currency: 'VND' });
                } else {
                    priceRow.style.display = 'none';
                    priceInput.value = '';
                }
            }

            var formActions = document.querySelector('.form-actions');
            var paymentBtn = formActions ? formActions.querySelector('button[type="button"]') : null;
            if (paymentBtn) {
                paymentBtn.style.display = (gia > 0) ? 'block' : 'none';
            }
            try {
                var dateInput = document.querySelector('input[name="ngay_su_kien"]');
                if (dateInput) {
                    var selector = '.the-dich-vu[data-item-type="' + itemType + '"][data-id="' + itemId + '"]';
                    var card = document.querySelector(selector);
                    if (card) {
                        var cardDate = card.getAttribute('data-ngay-dang') || card.getAttribute('data-ngay-dien-ra') || '';
                        dateInput.value = cardDate || '';
                    }
                }
            } catch (e) {}

            hidePaymentPopup();
            modal.classList.remove('closing');
            modal.style.display = 'flex';
            setTimeout(function(){ modal.classList.add('show'); }, 10);
            document.body.classList.add('modal-open');
        }

        function showPaymentInfo() {
            var nameInput = document.querySelector('input[name="ten_khach_hang"]');
            var phoneInput = document.querySelector('input[name="so_dien_thoai"]');
            if (!nameInput || !phoneInput) return;
            var name = nameInput.value.trim();
            var phone = phoneInput.value.trim();
            if (!name || !phone) {
                alert('Vui lòng nhập Họ và tên và Số điện thoại trước khi thanh toán.');
                return;
            }

            var formattedAmount = document.getElementById('don_gia_input') ? document.getElementById('don_gia_input').value : '';
            var rawAmount = formattedAmount ? formattedAmount.replace(/[^0-9]/g, '') : '';
            var displayAmount = formattedAmount || 'Liên hệ ngay';
            document.getElementById('paymentLabel').innerText = name + ' - ' + phone;
            document.getElementById('paymentAmount').innerText = displayAmount;
            if (modal) {
                modal.classList.remove('show');
                modal.style.display = 'none';
            }

            var form = document.querySelector('#modalDatLich form');
            var formData = new FormData(form);
            fetch('xu-ly-dat-lich.php', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: formData
            }).catch(function() {});

            var qrContainer = document.getElementById('paymentQrContainer');
            if (qrContainer) {
                var BANK_ID = 'MB';
                var ACCOUNT = '68228568888';
                var note = (name + ' ' + phone).replace(/[^a-zA-Z0-9 ]/g, '').trim().slice(0, 50);
                var qrSrc = 'https://img.vietqr.io/image/' + BANK_ID + '-' + ACCOUNT + '-compact2.png'
                    + '?addInfo=' + encodeURIComponent(note)
                    + '&accountName=' + encodeURIComponent('PHAM LINH NGOC');
                if (rawAmount && parseInt(rawAmount) > 0) {
                    qrSrc += '&amount=' + rawAmount;
                }
                qrContainer.innerHTML = '<img src="' + qrSrc + '" alt="QR thanh toán" style="width:200px;height:200px;border-radius:8px;" onerror="this.outerHTML=\'<div style=\'color:#dc3545;text-align:center;padding:10px;font-size:13px;\'>Không tải được QR, vui lòng chuyển khoản thủ công</div>\'">';
            }

            var paymentPopup = document.getElementById('paymentPopup');
            if (paymentPopup) {
                paymentPopup.style.display = 'flex';
                paymentPopup.classList.add('show');
            }
            document.body.classList.add('modal-open');
        }

        function hidePaymentPopup() {
            var paymentPopup = document.getElementById('paymentPopup');
            if (paymentPopup) {
                paymentPopup.classList.remove('show');
                paymentPopup.style.display = 'none';
            }
            document.body.classList.remove('modal-open');
        }

        function dongFormDatLich() {
            if (!modal.classList.contains('show')) {
                modal.style.display = 'none';
                document.body.classList.remove('modal-open');
                return;
            }
            modal.classList.remove('show');
            modal.classList.add('closing');
            document.body.classList.remove('modal-open');
            var box = modal.querySelector('.modal-box');
            var finished = false;
            var cleanup = function() {
                if (finished) return; finished = true;
                modal.style.display = 'none';
                modal.classList.remove('closing');
            };
            if (box) {
                var onEnd = function() { cleanup(); box.removeEventListener('animationend', onEnd); };
                box.addEventListener('animationend', onEnd);
                setTimeout(cleanup, 320);
            } else {
                setTimeout(cleanup, 220);
            }
        }
        var modalChiaSe = document.getElementById('modalChiaSe');
        var linkChiaSeHienTai = '';
        var tieuDeChiaSeHienTai = '';

        function moModalChiaSe(link, tieuDe) {
            linkChiaSeHienTai = link;
            tieuDeChiaSeHienTai = tieuDe;
            document.getElementById('linkChiaSe').value = link;
            document.getElementById('tieuDeChiaSe').innerText = tieuDe;
            modalChiaSe.style.display = 'flex';
            setTimeout(function(){ modalChiaSe.classList.add('show'); }, 10);
            document.body.classList.add('modal-open');
        }

        function dongModalChiaSe() {
            modalChiaSe.classList.remove('show');
            modalChiaSe.style.display = 'none';
            document.body.classList.remove('modal-open');
        }

        function saoChepLink() {
            var linkInput = document.getElementById('linkChiaSe');
            linkInput.select();
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(linkInput.value).then(function(){
                    var btn = event.target;
                    var oldText = btn.innerText;
                    btn.innerText = '✓ Đã sao chép';
                    setTimeout(function(){ btn.innerText = oldText; }, 2000);
                }).catch(function(){ fallbackCopyText(linkInput.value); });
            } else {
                fallbackCopyText(linkInput.value);
            }
        }

        function chiaSeLenFacebook() {
            var url = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(linkChiaSeHienTai);
            window.open(url, '_blank', 'width=600,height=400');
        }

        function chiaSeLenZalo() {
            var text = tieuDeChiaSeHienTai + ' - ' + linkChiaSeHienTai;
            var url = 'https://zalo.me/?text=' + encodeURIComponent(text);
            window.open(url, '_blank');
        }

        function chiaSeLenTwitter() {
            var text = tieuDeChiaSeHienTai + ' ' + linkChiaSeHienTai;
            var url = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(text);
            window.open(url, '_blank', 'width=600,height=400');
        }

        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
            if (event.target == modalChiaSe) {
                dongModalChiaSe();
            }
        }
    </script>

    <?php require_once 'includes/menu-dien-thoai.php'; ?>
</body>
</html>