<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once 'includes/config.php';

if (!isset($_SESSION['nguoi_dung_id']) || $_SESSION['vai_tro'] !== 'admin') {
    die("<h2 style='color:red;text-align:center;padding:50px;'>TRUY CẬP BỊ TỪ CHỐI!</h2>");
}

// Thêm cột linh_vuc nếu chưa có
try {
    $pdo->exec("ALTER TABLE yeu_cau_dat_lich ADD COLUMN IF NOT EXISTS so_luong INT NOT NULL DEFAULT 1");
    $pdo->exec("ALTER TABLE yeu_cau_dat_lich ADD COLUMN IF NOT EXISTS ma_gioi_thieu VARCHAR(50) DEFAULT NULL");
    $pdo->exec("ALTER TABLE yeu_cau_dat_lich ADD COLUMN IF NOT EXISTS nguoi_gioi_thieu_id INT DEFAULT NULL");
    $pdo->exec("ALTER TABLE yeu_cau_dat_lich ADD COLUMN IF NOT EXISTS linh_vuc VARCHAR(20) DEFAULT 'nhac'");
    $pdo->exec("ALTER TABLE yeu_cau_dat_lich ADD COLUMN IF NOT EXISTS so_tien DECIMAL(15,0) DEFAULT 0");
    $pdo->exec("ALTER TABLE yeu_cau_dat_lich ADD COLUMN IF NOT EXISTS tinh_thanh VARCHAR(100) DEFAULT NULL");
    $pdo->exec("ALTER TABLE yeu_cau_dat_lich ADD COLUMN IF NOT EXISTS dia_chi VARCHAR(255) DEFAULT NULL");
} catch (Exception $e) {}

// 1. CẬP NHẬT TRẠNG THÁI
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['cap_nhat_trang_thai'])) {
    $id_yeu_cau    = intval($_POST['id_yeu_cau']);
    $trang_thai_moi = $_POST['trang_thai'];
    $tab_back      = $_POST['tab'] ?? 'nhac';
    $so_tien_thu   = (float)str_replace([',','.','₫',' '], '', $_POST['so_tien_thuc_thu'] ?? 0);
    $phuong_thuc   = $_POST['phuong_thuc_tt'] ?? 'chuyen_khoan';

    $stmt = $pdo->prepare("UPDATE yeu_cau_dat_lich SET trang_thai = ? WHERE id = ?");
    $stmt->execute([$trang_thai_moi, $id_yeu_cau]);

    // Nếu hoàn thành + có số tiền → tạo đơn hàng
    if ($trang_thai_moi === 'hoan_thanh' && $so_tien_thu > 0) {
        // Kiểm tra chưa có đơn hàng cho yêu cầu này
        $da_co = $pdo->prepare("SELECT id FROM don_hang WHERE yeu_cau_id = ? LIMIT 1");
        $da_co->execute([$id_yeu_cau]);
        if (!$da_co->fetch()) {
            $yc = $pdo->prepare("SELECT * FROM yeu_cau_dat_lich WHERE id = ?");
            $yc->execute([$id_yeu_cau]);
            $yc = $yc->fetch();

            if ($yc) {
                // Tạo đơn hàng
                $ins = $pdo->prepare("
                    INSERT INTO don_hang (yeu_cau_id, ten_khach_hang, so_dien_thoai, dich_vu, linh_vuc, so_luong, so_tien_goc, so_tien_thuc_thu, phuong_thuc_tt, ma_gioi_thieu, nguoi_gioi_thieu_id, ghi_chu)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $ins->execute([
                    $id_yeu_cau,
                    $yc['ten_khach_hang'],
                    $yc['so_dien_thoai'],
                    $yc['dich_vu_quan_tam'],
                    $yc['linh_vuc'] ?? 'nhac',
                    $yc['so_luong'] ?? 1,
                    $yc['so_tien'] ?? 0,
                    $so_tien_thu,
                    $phuong_thuc,
                    $yc['ma_gioi_thieu'],
                    $yc['nguoi_gioi_thieu_id'],
                    $yc['ghi_chu']
                ]);
                $don_hang_id = $pdo->lastInsertId();

                // Tính hoa hồng affiliate nếu có mã giới thiệu
                if (!empty($yc['nguoi_gioi_thieu_id'])) {
                    // Tìm chính sách hoa hồng phù hợp
                    $cs = $pdo->query("
                        SELECT * FROM chinh_sach_affiliate
                        WHERE trang_thai = 1
                        ORDER BY id DESC LIMIT 1
                    ")->fetch();

                    $hoa_hong = 0;
                    if ($cs) {
                        $hoa_hong = $cs['loai_hoa_hong'] === 'phan_tram'
                            ? round($so_tien_thu * $cs['gia_tri'] / 100)
                            : $cs['gia_tri'];
                    } else {
                        // Mặc định 10% nếu chưa cài chính sách
                        $hoa_hong = round($so_tien_thu * 0.10);
                    }

                    if ($hoa_hong > 0) {
                        $ins_hh = $pdo->prepare("
                            INSERT INTO lich_su_affiliate (nguoi_gioi_thieu_id, nguoi_duoc_gioi_thieu_id, so_tien_hoa_hong, trang_thai, ten_noi_dung)
                            VALUES (?, ?, ?, 'cho_duyet', ?)
                        ");
                        $ins_hh->execute([
                            $yc['nguoi_gioi_thieu_id'],
                            null,
                            $hoa_hong,
                            $yc['dich_vu_quan_tam']
                        ]);

                        // Đánh dấu đã tính hoa hồng
                        $pdo->prepare("UPDATE don_hang SET hoa_hong_da_tinh = 1 WHERE id = ?")->execute([$don_hang_id]);
                    }
                }

                // Cộng điểm uy tín cho người giới thiệu khi đơn hoàn thành
                if (!empty($yc['nguoi_gioi_thieu_id'])) {
                    $pdo->prepare("
                        UPDATE thanh_vien
                        SET diem_uy_tin = LEAST(diem_uy_tin + 10, 1000),
                            cap_bac = CASE
                                WHEN diem_uy_tin + 10 >= 500 THEN 'tinh_hoa'
                                WHEN diem_uy_tin + 10 >= 100 THEN 'chuyen_nghiep'
                                ELSE 'tieu_chuan'
                            END
                        WHERE id = ?
                    ")->execute([$yc['nguoi_gioi_thieu_id']]);
                }
            } // end if ($yc)
        } // end if (!$da_co->fetch())
    } // end if hoan_thanh

    header("Location: admin-quan-ly-hoat-dong.php?tab=" . $tab_back . "&saved=1");
    exit;
}

// 2. CẬP NHẬT THÔNG TIN YÊU CẦU
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['cap_nhat_yeu_cau'])) {
    $id_yeu_cau = intval($_POST['id_yeu_cau']);
    $tab_back   = $_POST['tab'] ?? 'nhac';
    $ten_khach_hang = trim($_POST['ten_khach_hang'] ?? '');
    $so_dien_thoai  = trim($_POST['so_dien_thoai'] ?? '');
    $tinh_thanh     = trim($_POST['tinh_thanh'] ?? '');
    $dia_chi        = trim($_POST['dia_chi'] ?? '');
    $dich_vu        = trim($_POST['dich_vu_quan_tam'] ?? '');
    $ngay_su_kien   = !empty($_POST['ngay_su_kien']) ? $_POST['ngay_su_kien'] : null;
    $so_luong       = max(1, intval($_POST['so_luong'] ?? 1));
    $ma_gioi_thieu  = trim($_POST['ma_gioi_thieu'] ?? '');
    $ghi_chu        = trim($_POST['ghi_chu'] ?? '');

    $stmt = $pdo->prepare("UPDATE yeu_cau_dat_lich SET ten_khach_hang = ?, so_dien_thoai = ?, tinh_thanh = ?, dia_chi = ?, dich_vu_quan_tam = ?, ngay_su_kien = ?, so_luong = ?, ma_gioi_thieu = ?, ghi_chu = ? WHERE id = ?");
    $stmt->execute([$ten_khach_hang, $so_dien_thoai, $tinh_thanh !== '' ? $tinh_thanh : null, $dia_chi !== '' ? $dia_chi : null, $dich_vu, $ngay_su_kien, $so_luong, $ma_gioi_thieu, $ghi_chu, $id_yeu_cau]);

    header("Location: admin-quan-ly-hoat-dong.php?tab=" . $tab_back . "&saved=1");
    exit;
}

// 3. XÓA YÊU CẦU
if (isset($_GET['hanh_dong']) && $_GET['hanh_dong'] == 'xoa') {
    $id_xoa = intval($_GET['id']);
    $tab_back = $_GET['tab'] ?? 'nhac';
    $stmt = $pdo->prepare("DELETE FROM yeu_cau_dat_lich WHERE id = ?");
    if ($stmt->execute([$id_xoa])) {
        header("Location: admin-quan-ly-hoat-dong.php?tab=" . $tab_back);
        exit;
    }
}

// 4. LẤY DỮ LIỆU THEO LĨNH VỰC
$yeu_cau_nhac = $pdo->query("SELECT * FROM yeu_cau_dat_lich WHERE (linh_vuc IN ('nhac', 'dich_vu', 'khoa_hoc') OR linh_vuc IS NULL) ORDER BY ngay_tao DESC")->fetchAll();
$yeu_cau_hoa  = $pdo->query("SELECT * FROM yeu_cau_dat_lich WHERE linh_vuc = 'hoa' ORDER BY ngay_tao DESC")->fetchAll();
$dem_nhac_cho = $pdo->query("SELECT COUNT(*) FROM yeu_cau_dat_lich WHERE trang_thai = 'cho_xu_ly' AND (linh_vuc IN ('nhac', 'dich_vu', 'khoa_hoc') OR linh_vuc IS NULL)")->fetchColumn();
$dem_hoa_cho  = $pdo->query("SELECT COUNT(*) FROM yeu_cau_dat_lich WHERE trang_thai = 'cho_xu_ly' AND linh_vuc = 'hoa'")->fetchColumn();

$tab_hien_tai = $_GET['tab'] ?? 'nhac';
$thong_bao = isset($_GET['saved']) ? "<div class='alert-success'>✅ Đã cập nhật thành công!</div>" : "";

$edit_id = isset($_GET['edit_id']) ? intval($_GET['edit_id']) : 0;
$yeu_cau_dang_sua = null;
if ($edit_id > 0) {
    $stmt_edit = $pdo->prepare("SELECT * FROM yeu_cau_dat_lich WHERE id = ?");
    $stmt_edit->execute([$edit_id]);
    $yeu_cau_dang_sua = $stmt_edit->fetch();
}

function hienThiTrangThai($trang_thai) {
    $map = [
        'cho_xu_ly'  => '<span style="background:#fff3cd;color:#856404;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:bold;border:1px solid #ffeeba;">📝 Đăng ký chưa thanh toán</span>',
        'da_lien_he' => '<span style="background:#cce5ff;color:#004085;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:bold;border:1px solid #b8daff;">📞 Đã liên hệ</span>',
        'hoan_thanh' => '<span style="background:#d4edda;color:#155724;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:bold;border:1px solid #c3e6cb;">✅ Hoàn thành</span>',
        'da_phan_lop' => '<span style="background:#d1fae5;color:#065f46;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:bold;border:1px solid #a7f3d0;">🏫 Đã phân lớp</span>',
        'huy'        => '<span style="background:#f8d7da;color:#721c24;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:bold;border:1px solid #f5c6cb;">❌ Đã hủy</span>',
    ];
    return $map[$trang_thai] ?? '<span style="background:#e2e3e5;color:#383d41;padding:3px 9px;border-radius:20px;font-size:12px;">Chưa rõ</span>';
}

function renderBang($danh_sach, $tab) {
    global $pdo;
    if (count($danh_sach) === 0): ?>
        <tr><td colspan="4" style="text-align:center;padding:40px;color:#999;font-style:italic;">Chưa có yêu cầu nào.</td></tr>
    <?php return; endif;
    foreach ($danh_sach as $yc): ?>
    <tr>
        <td>
            <strong style="color:#004085;font-size:14px;"><?php echo htmlspecialchars($yc['ten_khach_hang']); ?></strong><br>
            <span style="color:#c82333;font-weight:bold;font-size:13px;">📞 <?php echo htmlspecialchars($yc['so_dien_thoai']); ?></span><br>
            <span style="color:#888;font-size:11px;"><?php echo date('H:i - d/m/Y', strtotime($yc['ngay_tao'])); ?></span>
        </td>
        <td>
            <strong style="color:#1864ab;font-size:13px;"><?php echo htmlspecialchars($yc['dich_vu_quan_tam']); ?></strong>
            <?php if (!empty($yc['ngay_su_kien']) && $yc['ngay_su_kien'] != '0000-00-00'): ?>
                <br><span style="font-size:12px;color:#28a745;font-weight:bold;">📅 <?php echo date('d/m/Y', strtotime($yc['ngay_su_kien'])); ?></span>
            <?php endif; ?>
            <?php if (!empty($yc['tinh_thanh'])): ?>
                <br><span style="font-size:12px;color:#1d4ed8;font-weight:bold;">📍 <?php echo htmlspecialchars($yc['tinh_thanh']); ?></span>
            <?php endif; ?>
            <?php if (!empty($yc['dia_chi'])): ?>
                <br><span style="font-size:12px;color:#475569;">🏠 <?php echo htmlspecialchars($yc['dia_chi']); ?></span>
            <?php endif; ?>
            <?php if (!empty($yc['so_luong'])): ?>
                <br><span style="font-size:12px;color:#0056b3;font-weight:bold;">📦 SL: <?php echo (int)$yc['so_luong']; ?></span>
            <?php endif; ?>
            <?php if (!empty($yc['ma_gioi_thieu'])): ?>
                <br><span style="font-size:12px;color:#6f42c1;font-weight:bold;">🔗 <?php echo htmlspecialchars($yc['ma_gioi_thieu']); ?></span>
            <?php endif; ?>
        </td>
        <td>
            <?php echo hienThiTrangThai($yc['trang_thai']); ?>
            <?php if (!empty($yc['ghi_chu'])): ?>
                <div style="background:#f1f3f5;padding:8px 10px;border-radius:6px;font-size:12px;color:#555;margin-top:6px;border-left:3px solid #ced4da;">💬 "<?php echo nl2br(htmlspecialchars($yc['ghi_chu'])); ?>"</div>
            <?php else: ?>
                <div style="font-size:12px;color:#adb5bd;font-style:italic;margin-top:6px;">Không có ghi chú.</div>
            <?php endif; ?>
        </td>
        <td>
            <?php
            $da_co_don = $pdo->prepare("SELECT id FROM don_hang WHERE yeu_cau_id = ? LIMIT 1");
            $da_co_don->execute([$yc['id']]);
            $don_ton_tai = $da_co_don->fetch();
            ?>
            <form method="POST" style="display:flex;flex-direction:column;gap:6px;">
                <input type="hidden" name="id_yeu_cau" value="<?php echo $yc['id']; ?>">
                <input type="hidden" name="tab" value="<?php echo htmlspecialchars($tab); ?>">
                <div style="display:flex;gap:5px;">
                    <select name="trang_thai" id="sel_<?php echo $yc['id']; ?>" onchange="toggleTienRow(<?php echo $yc['id']; ?>,this.value)" style="padding:5px;border:1px solid #ccc;border-radius:4px;font-size:12px;">
                        <option value="cho_xu_ly"  <?php if($yc['trang_thai']=='cho_xu_ly')  echo 'selected'; ?>>Chờ xử lý</option>
                        <option value="da_lien_he" <?php if($yc['trang_thai']=='da_lien_he') echo 'selected'; ?>>Đã liên hệ</option>
                        <option value="hoan_thanh" <?php if($yc['trang_thai']=='hoan_thanh') echo 'selected'; ?>>Hoàn thành</option>
                        <option value="da_phan_lop" <?php if($yc['trang_thai']=='da_phan_lop') echo 'selected'; ?>>Đã phân lớp</option>
                        <option value="huy"        <?php if($yc['trang_thai']=='huy')        echo 'selected'; ?>>Hủy bỏ</option>
                    </select>
                    <button type="submit" name="cap_nhat_trang_thai" style="background:#004085;color:white;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;font-size:12px;font-weight:bold;">Lưu</button>
                </div>
                <?php if (!$don_ton_tai): ?>
                <div id="row_tien_<?php echo $yc['id']; ?>" style="display:<?php echo $yc['trang_thai']=='hoan_thanh' ? 'flex' : 'none'; ?>;flex-direction:column;gap:4px;background:#f0fff4;padding:8px;border-radius:6px;border:1px solid #c3e6cb;">
                    <label style="font-size:11px;font-weight:bold;color:#155724;">💰 Nhập doanh thu thực thu:</label>
                    <input type="number" name="so_tien_thuc_thu" placeholder="Số tiền (VNĐ)" style="padding:5px;border:1px solid #c3e6cb;border-radius:4px;font-size:12px;">
                    <select name="phuong_thuc_tt" style="padding:5px;border:1px solid #c3e6cb;border-radius:4px;font-size:12px;">
                        <option value="chuyen_khoan">Chuyển khoản</option>
                        <option value="tien_mat">Tiền mặt</option>
                        <option value="the">Thẻ</option>
                        <option value="khac">Khác</option>
                    </select>
                </div>
                <?php else: ?>
                <span style="font-size:11px;color:#28a745;font-weight:bold;">✅ Đã tạo đơn hàng</span>
                <?php endif; ?>
            </form>
            <div style="display:flex;flex-direction:column;gap:6px;margin-top:6px;">
                <a href="?tab=<?php echo $tab; ?>&edit_id=<?php echo $yc['id']; ?>" style="color:#0d6efd;font-size:12px;font-weight:bold;text-decoration:none;">✏️ Sửa</a>
                <a href="?hanh_dong=xoa&id=<?php echo $yc['id']; ?>&tab=<?php echo $tab; ?>" style="color:#dc3545;font-size:12px;font-weight:bold;text-decoration:none;" onclick="return confirm('Xóa yêu cầu này?')">🗑 Xóa</a>
            </div>
        </td>
    </tr>
    <?php endforeach;
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Xử lý Yêu cầu Đặt lịch - Admin</title>
    <link rel="stylesheet" href="includes/admin-style.css">
</head>
<body>
    <?php require_once 'includes/menu-admin.php'; ?>

    <div class="khu-vuc-du-lieu">
        <div class="thanh-tren">📞 Xử lý Yêu cầu Đặt lịch</div>

        <div class="noi-dung-chinh">
            <?php echo $thong_bao; ?>

            <?php if ($yeu_cau_dang_sua): ?>
            <div style="background:#fff8e1;padding:16px;border:1px solid #ffe082;border-radius:8px;margin-bottom:16px;">
                <div style="font-weight:bold;color:#8a6d3b;margin-bottom:10px;">✏️ Chỉnh sửa yêu cầu #<?php echo $yeu_cau_dang_sua['id']; ?></div>
                <form method="POST" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:10px;">
                    <input type="hidden" name="id_yeu_cau" value="<?php echo $yeu_cau_dang_sua['id']; ?>">
                    <input type="hidden" name="tab" value="<?php echo htmlspecialchars($tab_hien_tai); ?>">
                    <input type="hidden" name="cap_nhat_yeu_cau" value="1">
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Tên khách hàng</label>
                        <input type="text" name="ten_khach_hang" value="<?php echo htmlspecialchars($yeu_cau_dang_sua['ten_khach_hang']); ?>" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Số điện thoại</label>
                        <input type="text" name="so_dien_thoai" value="<?php echo htmlspecialchars($yeu_cau_dang_sua['so_dien_thoai']); ?>" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Dịch vụ quan tâm</label>
                        <input type="text" name="dich_vu_quan_tam" value="<?php echo htmlspecialchars($yeu_cau_dang_sua['dich_vu_quan_tam']); ?>" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Ngày sự kiện</label>
                        <input type="date" name="ngay_su_kien" value="<?php echo htmlspecialchars($yeu_cau_dang_sua['ngay_su_kien']); ?>" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Tỉnh / Thành</label>
                        <input type="text" name="tinh_thanh" value="<?php echo htmlspecialchars($yeu_cau_dang_sua['tinh_thanh']); ?>" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;" placeholder="Ví dụ: Hà Nội">
                    </div>
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Địa chỉ cụ thể</label>
                        <input type="text" name="dia_chi" value="<?php echo htmlspecialchars($yeu_cau_dang_sua['dia_chi']); ?>" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;" placeholder="Số nhà, đường, phường/xã...">
                    </div>
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Số lượng</label>
                        <input type="number" name="so_luong" value="<?php echo (int)$yeu_cau_dang_sua['so_luong']; ?>" min="1" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;">
                    </div>
                    <div>
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Mã giới thiệu</label>
                        <input type="text" name="ma_gioi_thieu" value="<?php echo htmlspecialchars($yeu_cau_dang_sua['ma_gioi_thieu']); ?>" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;">
                    </div>
                    <div style="grid-column:1 / -1;">
                        <label style="display:block;font-size:12px;font-weight:bold;margin-bottom:4px;">Ghi chú</label>
                        <textarea name="ghi_chu" rows="3" style="width:100%;padding:7px;border:1px solid #ccc;border-radius:4px;"><?php echo htmlspecialchars($yeu_cau_dang_sua['ghi_chu']); ?></textarea>
                    </div>
                    <div style="grid-column:1 / -1;display:flex;gap:8px;align-items:center;">
                        <button type="submit" style="background:#28a745;color:white;border:none;padding:8px 14px;border-radius:4px;cursor:pointer;font-weight:bold;">💾 Lưu thay đổi</button>
                        <a href="admin-quan-ly-hoat-dong.php?tab=<?php echo htmlspecialchars($tab_hien_tai); ?>" style="color:#6c757d;font-size:13px;">Hủy</a>
                    </div>
                </form>
            </div>
            <?php endif; ?>

            <div class="thanh-menu-nd">
                <button class="nut-tab-nd <?php echo $tab_hien_tai == 'nhac' ? 'dang-chon' : ''; ?>" onclick="chuyenTab('nhac')">
                    🎵 Âm Nhạc
                    <?php if ($dem_nhac_cho > 0): ?>
                        <span style="background:#dc3545;color:white;border-radius:10px;padding:1px 7px;font-size:11px;margin-left:5px;"><?php echo $dem_nhac_cho; ?></span>
                    <?php endif; ?>
                </button>
                <button class="nut-tab-nd <?php echo $tab_hien_tai == 'hoa' ? 'dang-chon' : ''; ?>" onclick="chuyenTab('hoa')">
                    🎨 Hội Họa
                    <?php if ($dem_hoa_cho > 0): ?>
                        <span style="background:#dc3545;color:white;border-radius:10px;padding:1px 7px;font-size:11px;margin-left:5px;"><?php echo $dem_hoa_cho; ?></span>
                    <?php endif; ?>
                </button>
            </div>

            <!-- TAB ÂM NHẠC -->
            <div id="tab-nhac" class="khoi-noi-dung" style="display:<?php echo $tab_hien_tai == 'nhac' ? 'block' : 'none'; ?>;">
                <div class="khung-bang-header">
                    <h3 style="color:#1864ab;">🎵 Yêu cầu từ Không gian Âm nhạc</h3>
                    <span style="font-size:13px;color:#666;"><?php echo count($yeu_cau_nhac); ?> yêu cầu</span>
                </div>
                <div class="bang-cuon">
                    <table class="bang-du-lieu">
                        <thead>
                            <tr>
                                <th style="width:22%;">Khách hàng</th>
                                <th style="width:28%;">Dịch vụ quan tâm</th>
                                <th style="width:30%;">Tiến độ & Ghi chú</th>
                                <th style="width:20%;">Thao tác</th>
                            </tr>
                        </thead>
                        <tbody><?php renderBang($yeu_cau_nhac, 'nhac'); ?></tbody>
                    </table>
                </div>
            </div>

            <!-- TAB HỘI HỌA -->
            <div id="tab-hoa" class="khoi-noi-dung" style="display:<?php echo $tab_hien_tai == 'hoa' ? 'block' : 'none'; ?>;">
                <div class="khung-bang-header">
                    <h3 style="color:#28a745;">🎨 Yêu cầu từ Không gian Hội họa</h3>
                    <span style="font-size:13px;color:#666;"><?php echo count($yeu_cau_hoa); ?> yêu cầu</span>
                </div>
                <div class="bang-cuon">
                    <table class="bang-du-lieu">
                        <thead>
                            <tr>
                                <th style="width:22%;">Khách hàng</th>
                                <th style="width:28%;">Dịch vụ quan tâm</th>
                                <th style="width:30%;">Tiến độ & Ghi chú</th>
                                <th style="width:20%;">Thao tác</th>
                            </tr>
                        </thead>
                        <tbody><?php renderBang($yeu_cau_hoa, 'hoa'); ?></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
    function chuyenTab(tab) {
        document.getElementById('tab-nhac').style.display = tab === 'nhac' ? 'block' : 'none';
        document.getElementById('tab-hoa').style.display  = tab === 'hoa'  ? 'block' : 'none';
        document.querySelectorAll('.nut-tab-nd').forEach(function(b) { b.classList.remove('dang-chon'); });
        event.currentTarget.classList.add('dang-chon');
        window.history.replaceState({}, '', '?tab=' + tab);
    }
    function toggleTienRow(id, val) {
        var row = document.getElementById('row_tien_' + id);
        if (row) row.style.display = (val === 'hoan_thanh') ? 'flex' : 'none';
    }
    </script>
</body>
</html>
