<?php
session_start();
require_once 'includes/config.php';
require_once 'includes/cai-dat-helper.php';
$_anh_bia_gian_hang = layAnhBiaTrang($pdo, 'gian_hang');

// Lấy thông tin thành viên đang đăng nhập
$thanh_vien_hien_tai = null;
$ma_ref_thanh_vien = '';
$id_tv = (int)($_SESSION['nguoi_dung_id'] ?? 0);
if ($id_tv > 0) {
    $stmt_tv = $pdo->prepare("SELECT id, ho_ten, ma_gioi_thieu FROM thanh_vien WHERE id = ? AND ma_gioi_thieu IS NOT NULL AND ma_gioi_thieu != '' LIMIT 1");
    $stmt_tv->execute([$id_tv]);
    $thanh_vien_hien_tai = $stmt_tv->fetch();
    if ($thanh_vien_hien_tai) $ma_ref_thanh_vien = $thanh_vien_hien_tai['ma_gioi_thieu'];
}

// Lấy tỷ lệ hoa hồng theo từng sản phẩm (map id_san_pham => ty_le_affiliate)
$ty_le_map = [];
try {
    $rows_cs = $pdo->query("SELECT id_san_pham, ty_le_affiliate FROM chinh_sach_kinh_doanh")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows_cs as $r) $ty_le_map[(int)$r['id_san_pham']] = (int)$r['ty_le_affiliate'];
} catch (Exception $e) {}

$tim_kiem = trim($_GET['q'] ?? '');
$filter_danh_muc = trim($_GET['danh_muc'] ?? '');
$filter_trang_thai = $_GET['trang_thai'] ?? [];
$filter_gia_tu = isset($_GET['gia_tu']) ? (int)$_GET['gia_tu'] : 0;
$filter_gia_den = isset($_GET['gia_den']) ? (int)$_GET['gia_den'] : 0;
$ma_gioi_thieu = isset($_GET['ref']) ? htmlspecialchars(trim($_GET['ref'])) : '';

if (!is_array($filter_trang_thai)) {
    $filter_trang_thai = $filter_trang_thai !== '' ? [$filter_trang_thai] : [];
}

$danh_sach_san_pham = [];
$danh_sach_danh_muc = [];

try {
    $danh_sach_danh_muc = $pdo->query("SELECT * FROM danh_muc_san_pham ORDER BY ten_danh_muc ASC")->fetchAll(PDO::FETCH_ASSOC);

    $sql = "SELECT * FROM san_pham_gian_hang WHERE trang_thai = 'hien_thi'";
    $params = [];

    if ($tim_kiem !== '') {
        $like = '%' . $tim_kiem . '%';
        $sql .= " AND (ten_san_pham LIKE ? OR danh_muc LIKE ? OR mo_ta LIKE ? OR ma_hieu LIKE ?)";
        array_push($params, $like, $like, $like, $like);
    }
    if ($filter_danh_muc !== '') {
        $sql .= " AND danh_muc = ?";
        $params[] = $filter_danh_muc;
    }
    if (!empty($filter_trang_thai)) {
        $conds = [];
        foreach ($filter_trang_thai as $s) {
            if (in_array($s, ['moi','noi_bat','ban_chay'])) $conds[] = "$s = 1";
        }
        if ($conds) $sql .= ' AND (' . implode(' OR ', $conds) . ')';
    }
    if ($filter_gia_tu > 0) {
        $sql .= " AND (CASE WHEN gia_khuyen_mai > 0 THEN gia_khuyen_mai ELSE gia_ban END) >= ?";
        $params[] = $filter_gia_tu;
    }
    if ($filter_gia_den > 0) {
        $sql .= " AND (CASE WHEN gia_khuyen_mai > 0 THEN gia_khuyen_mai ELSE gia_ban END) <= ?";
        $params[] = $filter_gia_den;
    }
    $sql .= " ORDER BY id DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $danh_sach_san_pham = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Lấy vị trí kho cho tất cả sản phẩm
    $kho_map = [];
    if (!empty($danh_sach_san_pham)) {
        $ids = array_column($danh_sach_san_pham, 'id');
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt_kho = $pdo->prepare("SELECT ql.id_san_pham, ql.vi_tri_kho, ql.so_luong_ton FROM quan_ly_kho_hang ql WHERE ql.id_san_pham IN ($placeholders) AND ql.so_luong_ton > 0");
        $stmt_kho->execute($ids);
        foreach ($stmt_kho->fetchAll(PDO::FETCH_ASSOC) as $k) {
            $kho_map[(int)$k['id_san_pham']][] = $k;
        }
    }
} catch (PDOException $e) {
    die("Lỗi tải dữ liệu gian hàng.");
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gian Hàng Nghệ Thuật - PHẠM NGỌC TV</title>
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Inter', system-ui, sans-serif; background: #f0f4f8; color: #1e293b; }
        a { text-decoration: none; color: inherit; }

        .khu-vuc-hero { background: #1864ab; color: white; padding: 50px 20px; text-align: center; background-size: cover; background-position: center; background-repeat: no-repeat; position: relative; min-height: 220px; display: flex; flex-direction: column; align-items: center; justify-content: center; }
        .khu-vuc-hero::before { content:''; position:absolute; inset:0; background:rgba(24,100,171,0.72); }
        .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.9; }
        .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); }

        /* ── LAYOUT ── */
        .page-wrapper { max-width: 1400px; margin: 0 auto; padding: 32px 24px 60px; }

        .trang-content { display: grid; grid-template-columns: 240px minmax(0, 1fr); gap: 28px; align-items: start; }

        /* ── SIDEBAR BỘ LỌC ── */
        .khung-bo-loc { background: #fff; border-radius: 0; padding: 24px; box-shadow: 0 4px 24px rgba(15,23,42,0.07); position: sticky; top: 20px; }
        .khung-bo-loc h2 { font-size: 1rem; font-weight: 800; color: #0f172a; margin-bottom: 20px; display: flex; align-items: center; gap: 8px; }
        .nhom-bo-loc { margin-bottom: 20px; }
        .nhom-bo-loc label { display: block; font-size: 0.82rem; font-weight: 700; color: #475569; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 8px; }
        .nhom-bo-loc select,
        .nhom-bo-loc input[type=number] { width: 100%; padding: 10px 14px; border: 1.5px solid #e2e8f0; border-radius: 0; background: #f8fafc; font-size: 0.92rem; color: #1e293b; outline: none; transition: border-color .2s; }
        .nhom-bo-loc select:focus,
        .nhom-bo-loc input[type=number]:focus { border-color: #2563eb; }
        .nhom-checkbox { display: flex; align-items: center; gap: 9px; margin-bottom: 9px; font-size: 0.92rem; color: #334155; cursor: pointer; }
        .nhom-checkbox input { width: 16px; height: 16px; accent-color: #2563eb; cursor: pointer; }
        .gia-range { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
        .nut-loc { width: 100%; padding: 11px; border: none; border-radius: 0; background: linear-gradient(135deg, #2563eb, #1d4ed8); color: #fff; font-weight: 700; font-size: 0.92rem; cursor: pointer; margin-bottom: 8px; transition: opacity .15s; }
        .nut-loc:hover { opacity: .9; }
        .nut-xoa-bo { display: block; text-align: center; width: 100%; padding: 10px; border-radius: 0; border: 1.5px solid #e2e8f0; color: #64748b; font-size: 0.88rem; font-weight: 600; transition: background .15s; }
        .nut-xoa-bo:hover { background: #f1f5f9; }
        .divider { border: none; border-top: 1.5px solid #f1f5f9; margin: 18px 0; }

        /* ── PANEL PHẢI ── */
        .products-panel { display: flex; flex-direction: column; gap: 20px; }

        /* ── TOOLBAR TÌM KIẾM ── */
        .toolbar { display: flex; align-items: center; gap: 14px; background: #fff; border-radius: 0; padding: 14px 18px; box-shadow: 0 4px 20px rgba(15,23,42,0.06); }
        .search-wrap { display: flex; flex: 1; align-items: center; gap: 0; background: #f1f5f9; border-radius: 0; overflow: hidden; border: 1.5px solid #e2e8f0; transition: border-color .2s; }
        .search-wrap:focus-within { border-color: #2563eb; background: #fff; }
        .search-wrap input { flex: 1; border: none; background: transparent; padding: 11px 16px; font-size: 0.95rem; color: #1e293b; outline: none; }
        .search-wrap button { border: none; background: linear-gradient(135deg, #2563eb, #1d4ed8); color: #fff; padding: 11px 20px; font-weight: 700; font-size: 0.9rem; cursor: pointer; transition: opacity .15s; white-space: nowrap; }
        .search-wrap button:hover { opacity: .9; }
        .count-badge { white-space: nowrap; font-size: 0.85rem; font-weight: 700; color: #64748b; background: #f1f5f9; padding: 8px 14px; border-radius: 0; }

        /* ── LƯỚI SẢN PHẨM ── */
        .luoi-san-pham { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 22px; }

        .the-san-pham { background: #fff; border-radius: 0; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 4px 20px rgba(15,23,42,0.07); border: 1px solid #f1f5f9; transition: transform .2s, box-shadow .2s; }
        .the-san-pham:hover { transform: translateY(-5px); box-shadow: 0 16px 40px rgba(15,23,42,0.13); }

        /* ảnh */
        .sp-img-wrap { position: relative; overflow: hidden; aspect-ratio: 4/3; background: #f8fafc; display: block; }
        .sp-img-wrap img { width: 100%; height: 100%; object-fit: cover; transition: transform .35s ease; display: block; }
        .the-san-pham:hover .sp-img-wrap img { transform: scale(1.06); }
        .sp-img-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 3.5rem; color: #cbd5e1; }

        /* badges */
        .badges { position: absolute; top: 10px; left: 10px; display: flex; flex-wrap: wrap; gap: 5px; }
        .badge { display: inline-flex; align-items: center; gap: 3px; border-radius: 999px; padding: 4px 10px; font-size: 0.72rem; font-weight: 800; backdrop-filter: blur(6px); }
        .badge-moi { background: rgba(219,234,254,0.92); color: #1d4ed8; }
        .badge-noi-bat { background: rgba(254,226,226,0.92); color: #b91c1c; }
        .badge-ban-chay { background: rgba(220,252,231,0.92); color: #15803d; }

        /* body card */
        .sp-body { padding: 16px 18px 20px; display: flex; flex-direction: column; gap: 8px; flex: 1; }
        .sp-ten { font-size: 0.95rem; font-weight: 700; letter-spacing: -0.03em; color: #0f172a; line-height: 1.35; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; min-height: calc(1.35em * 3); transition: color .15s, transform .15s; }
        .sp-ten:hover { color: #2563eb; }
        .sp-sku { font-size: 0.76rem; color: #94a3b8; }
        .sp-prices { display: flex; align-items: baseline; gap: 6px; margin-top: 4px; }
        .sp-gia-ban { font-size: 0.95rem; font-weight: 800; color: #dc2626; letter-spacing: -0.02em; }
        .sp-gia-goc { font-size: 0.84rem; font-weight: 700; color: #0f172a; }
        .sp-gia-cu { font-size: 0.78rem; color: #64748b; text-decoration: line-through; }

        .nut-xem-ct { display: block; text-align: center; margin-top: auto; padding: 10px 12px; border-radius: 12px; background: linear-gradient(135deg, #2563eb, #1d4ed8); color: #fff; font-weight: 700; font-size: 0.82rem; letter-spacing: 0.03em; text-transform: uppercase; transition: opacity .15s, transform .15s; }
        .nut-xem-ct:hover { opacity: .92; transform: translateY(-1px); }

        /* empty */
        .empty-state { grid-column: 1/-1; background: #fff; border-radius: 12px; padding: 48px 24px; text-align: center; color: #94a3b8; font-size: 1rem; box-shadow: 0 4px 20px rgba(15,23,42,0.06); }

        /* affiliate */
        .aff-bar { display: flex; align-items: center; justify-content: space-between; gap: 6px; margin-top: 10px; padding: 6px 10px; background: #ffffff; border-radius: 12px; border: 1px solid #e2e8f0; box-shadow: inset 0 0 0 1px rgba(15,23,42,0.03); width: 100%; flex-wrap: nowrap; overflow: hidden; }
        .aff-rate { font-size: 0.72rem; font-weight: 600; color: #0f766e; white-space: nowrap; min-width: 0; }
        .btn-copy-link { display: inline-flex; align-items: center; gap: 4px; padding: 4px 7px; border-radius: 10px; background: #2563eb; color: #fff; font-size: 0.68rem; font-weight: 700; border: none; cursor: pointer; transition: background .15s, transform .15s; white-space: nowrap; min-width: 0; flex-shrink: 1; }
        .btn-copy-link:hover { background: #1d4ed8; transform: translateY(-1px); }
        .btn-copy-link.copied { background: #16a34a; }

        /* ── NÚT BỘ LỌC MOBILE ── */
        .nut-toggle-loc { display: none; width: 100%; padding: 12px 18px; background: linear-gradient(135deg, #2563eb, #1d4ed8); color: #fff; border: none; border-radius: 8px; font-size: 0.95rem; font-weight: 700; cursor: pointer; margin-bottom: 16px; text-align: left; align-items: center; justify-content: space-between; }
        .nut-toggle-loc .mui-ten { transition: transform .25s; }
        .nut-toggle-loc.mo .mui-ten { transform: rotate(180deg); }
        .noi-dung-bo-loc { overflow: hidden; transition: max-height .3s ease; }

        /* ── RESPONSIVE ── */
        @media (max-width: 1024px) { .trang-content { grid-template-columns: 1fr; } .khung-bo-loc { position: static; } }
        @media (max-width: 860px) {
            .luoi-san-pham { grid-template-columns: repeat(2, minmax(0, 1fr)); }
        }
        @media (max-width: 768px) {
            .nut-toggle-loc { display: flex; }
            .noi-dung-bo-loc { max-height: 0; }
            .noi-dung-bo-loc.hien { max-height: 600px; }
            .khung-bo-loc h2 { display: none; }
        }
        @media (max-width: 600px) {
            .page-wrapper { padding: 20px 14px 40px; }
            .luoi-san-pham { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
            .toolbar { flex-wrap: wrap; }
        }
        @media (max-width: 420px) {
            .page-wrapper { padding: 16px 10px 36px; }
            .luoi-san-pham { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
            .toolbar { flex-wrap: wrap; }
            .aff-bar { gap: 4px; padding: 4px 8px; }
            .aff-rate { font-size: 0.68rem; }
            .btn-copy-link { padding: 3px 6px; font-size: 0.66rem; }
        }
    </style>
</head>
<body>

    <div class="khu-vuc-hero"<?php if($_anh_bia_gian_hang): ?> style="background-image:url('<?php echo htmlspecialchars($_anh_bia_gian_hang); ?>')"<?php endif; ?>>
        <a href="index.php" class="nut-tro-ve">⬅ Trở về Sảnh chính</a>
        <h1>🛍️ Gian Hàng Trưng Bày</h1>
        <p>Khám phá bộ sưu tập nhạc cụ, thiết bị âm thanh và sản phẩm nghệ thuật chất lượng cao.</p>
    </div>

<div class="page-wrapper">

    <div class="trang-content">

        <!-- SIDEBAR BỘ LỌC -->
        <aside class="khung-bo-loc">
            <h2>🔍 Bộ lọc</h2>
            <button type="button" class="nut-toggle-loc" onclick="toggleBoLoc(this)">
                <span>🔍 Bộ lọc sản phẩm</span>
                <span class="mui-ten">▼</span>
            </button>
            <div class="noi-dung-bo-loc">
            <form method="GET" action="gian-hang.php">
                <input type="hidden" name="ref" value="<?= htmlspecialchars($ma_gioi_thieu) ?>">
                <input type="hidden" name="q" value="<?= htmlspecialchars($tim_kiem) ?>">

                <div class="nhom-bo-loc">
                    <label>Danh mục</label>
                    <select name="danh_muc">
                        <option value="">Tất cả danh mục</option>
                        <?php foreach ($danh_sach_danh_muc as $dm): ?>
                            <option value="<?= htmlspecialchars($dm['slug']) ?>" <?= $filter_danh_muc === $dm['slug'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($dm['ten_danh_muc']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <hr class="divider">

                <div class="nhom-bo-loc">
                    <label>Trạng thái</label>
                    <label class="nhom-checkbox"><input type="checkbox" name="trang_thai[]" value="moi" <?= in_array('moi', $filter_trang_thai) ? 'checked' : '' ?>> ✨ Hàng mới</label>
                    <label class="nhom-checkbox"><input type="checkbox" name="trang_thai[]" value="noi_bat" <?= in_array('noi_bat', $filter_trang_thai) ? 'checked' : '' ?>> ⭐ Nổi bật</label>
                    <label class="nhom-checkbox"><input type="checkbox" name="trang_thai[]" value="ban_chay" <?= in_array('ban_chay', $filter_trang_thai) ? 'checked' : '' ?>> 🔥 Bán chạy</label>
                </div>

                <hr class="divider">

                <div class="nhom-bo-loc">
                    <label>Khoảng giá (₫)</label>
                    <div class="gia-range">
                        <input type="number" name="gia_tu" min="0" value="<?= $filter_gia_tu ?: '' ?>" placeholder="Từ">
                        <input type="number" name="gia_den" min="0" value="<?= $filter_gia_den ?: '' ?>" placeholder="Đến">
                    </div>
                </div>

                <button type="submit" class="nut-loc">Áp dụng bộ lọc</button>
                <a href="gian-hang.php<?= $ma_gioi_thieu ? '?ref=' . urlencode($ma_gioi_thieu) : '' ?>" class="nut-xoa-bo">Xóa bộ lọc</a>
            </form>
            </div>
        </aside>

        <!-- PANEL SẢN PHẨM -->
        <section class="products-panel">

            <!-- TOOLBAR TÌM KIẾM -->
            <div class="toolbar">
                <form class="search-wrap" method="GET" action="gian-hang.php" style="flex:1;">
                    <input type="hidden" name="ref" value="<?= htmlspecialchars($ma_gioi_thieu) ?>">
                    <?php if ($filter_danh_muc !== ''): ?><input type="hidden" name="danh_muc" value="<?= htmlspecialchars($filter_danh_muc) ?>"><?php endif; ?>
                    <?php if ($filter_gia_tu > 0): ?><input type="hidden" name="gia_tu" value="<?= (int)$filter_gia_tu ?>"><?php endif; ?>
                    <?php if ($filter_gia_den > 0): ?><input type="hidden" name="gia_den" value="<?= (int)$filter_gia_den ?>"><?php endif; ?>
                    <?php foreach ($filter_trang_thai as $s): ?><input type="hidden" name="trang_thai[]" value="<?= htmlspecialchars($s) ?>"><?php endforeach; ?>
                    <input type="text" name="q" value="<?= htmlspecialchars($tim_kiem) ?>" placeholder="Tìm theo tên, SKU, mô tả...">
                    <button type="submit">🔍 Tìm kiếm</button>
                </form>
                <div class="count-badge"><?= count($danh_sach_san_pham) ?> sản phẩm</div>
            </div>

            <!-- LƯỚI SẢN PHẨM -->
            <div class="luoi-san-pham">
                <?php if (empty($danh_sach_san_pham)): ?>
                    <div class="empty-state">😔 Không tìm thấy sản phẩm phù hợp. Hãy thử thay đổi bộ lọc.</div>
                <?php endif; ?>

                <?php foreach ($danh_sach_san_pham as $sp):
                    $is_affiliate = ((string)($sp['loai_phan_phoi'] ?? 'noi_bo') === 'affiliate');
                    $url_ct = $is_affiliate && !empty($sp['link_affiliate']) ? $sp['link_affiliate'] : 'chi-tiet-san-pham.php?id=' . (int)$sp['id'] . ($ma_gioi_thieu ? '&ref=' . urlencode($ma_gioi_thieu) : '');
                    $gia_hien_thi = (!empty($sp['gia_khuyen_mai']) && $sp['gia_khuyen_mai'] > 0) ? (int)$sp['gia_khuyen_mai'] : (int)($sp['gia_ban'] ?: $sp['gia_goc']);
                    $gia_goc_hien = (int)($sp['gia_goc'] ?: $sp['gia_ban']);
                    $co_khuyen_mai = !empty($sp['gia_khuyen_mai']) && $sp['gia_khuyen_mai'] > 0;
                ?>
                <div class="the-san-pham">
                    <a href="<?= htmlspecialchars($url_ct) ?>" class="sp-img-wrap"<?= $is_affiliate ? ' target="_blank" rel="noopener noreferrer"' : '' ?>>
                        <?php if (!empty($sp['hinh_anh'])): ?>
                            <img src="<?= htmlspecialchars($sp['hinh_anh']) ?>" alt="<?= htmlspecialchars($sp['ten_san_pham']) ?>" loading="lazy">
                        <?php else: ?>
                            <div class="sp-img-placeholder">🎵</div>
                        <?php endif; ?>
                        <div class="badges">
                            <?php if (!empty($sp['moi'])): ?><span class="badge badge-moi">✨ Mới</span><?php endif; ?>
                            <?php if (!empty($sp['noi_bat'])): ?><span class="badge badge-noi-bat">⭐ Nổi bật</span><?php endif; ?>
                            <?php if (!empty($sp['ban_chay'])): ?><span class="badge badge-ban-chay">🔥 Bán chạy</span><?php endif; ?>
                        </div>
                    </a>
                    <div class="sp-body">
                        <a href="<?= htmlspecialchars($url_ct) ?>" class="sp-ten"<?= $is_affiliate ? ' target="_blank" rel="noopener noreferrer"' : '' ?>><?= htmlspecialchars($sp['ten_san_pham']) ?></a>
                        <?php if (!$is_affiliate && (!empty($sp['ma_hieu']) || !empty($kho_map[(int)$sp['id']]))): ?>
                            <span class="sp-sku">
                                <?= !empty($sp['ma_hieu']) ? 'SKU: ' . htmlspecialchars($sp['ma_hieu']) : '' ?>
                                <?php if (!empty($kho_map[(int)$sp['id']])): ?>
                                    <?= !empty($sp['ma_hieu']) ? ' &nbsp;·&nbsp; ' : '' ?>📦 <?= implode(', ', array_map(fn($k) => htmlspecialchars($k['vi_tri_kho'] ?? 'Kho chính'), $kho_map[(int)$sp['id']])) ?>
                                <?php endif; ?>
                            </span>
                        <?php endif; ?>
                        <div class="sp-prices">
                            <?php if ($co_khuyen_mai): ?>
                                <span class="sp-gia-ban"><?= number_format($gia_hien_thi) ?> ₫</span>
                                <span class="sp-gia-cu"><?= number_format($gia_goc_hien) ?> ₫</span>
                            <?php else: ?>
                                <span class="sp-gia-goc"><?= number_format($gia_hien_thi) ?> ₫</span>
                            <?php endif; ?>
                        </div>
                        <a href="<?= htmlspecialchars($url_ct) ?>" class="nut-xem-ct"<?= $is_affiliate ? ' target="_blank" rel="noopener noreferrer"' : '' ?>>Xem chi tiết →</a>

                        <?php if (!$is_affiliate && $ma_ref_thanh_vien !== ''):
                            $ty_le_sp = $ty_le_map[(int)$sp['id']] ?? 10;
                            $link_aff = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
                                . '://' . $_SERVER['HTTP_HOST']
                                . '/congdongnghethuat/chi-tiet-san-pham.php?id=' . (int)$sp['id']
                                . '&ref=' . urlencode($ma_ref_thanh_vien);
                        ?>
                        <div class="aff-bar">
                            <span class="aff-rate">🤝 HH <?= $ty_le_sp ?>%</span>
                            <button class="btn-copy-link" onclick="copyAffLink(this, '<?= htmlspecialchars($link_aff, ENT_QUOTES) ?>')">
                                🔗 Copy link
                            </button>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </section>
    </div>
</div>

<script>
function toggleBoLoc(btn) {
    btn.classList.toggle('mo');
    document.querySelector('.noi-dung-bo-loc').classList.toggle('hien');
}
function copyAffLink(btn, url) {
    navigator.clipboard.writeText(url).then(function() {
        btn.textContent = '✅ Đã copy!';
        btn.classList.add('copied');
        setTimeout(function() {
            btn.innerHTML = '🔗 Copy link';
            btn.classList.remove('copied');
        }, 2000);
    }).catch(function() {
        var el = document.createElement('textarea');
        el.value = url;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        btn.textContent = '✅ Đã copy!';
        btn.classList.add('copied');
        setTimeout(function() {
            btn.innerHTML = '🔗 Copy link';
            btn.classList.remove('copied');
        }, 2000);
    });
}
</script>

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