<?php
session_start();
// KIỂM TRA BẢO MẬT (Chỉ người có mật khẩu mới được vào)
if (!isset($_SESSION['da_dang_nhap']) || $_SESSION['da_dang_nhap'] !== true) {
    header("Location: login.php");
    exit;
}

require 'config.php';

// ==========================================
// 1. XỬ LÝ CÁC HÀNH ĐỘNG: XÓA, XÓA NHIỀU, SỬA
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $loai_tab = $_POST['loai_tab'] ?? '';
    
    // Xác định đang thao tác ở bảng nào
    $bang = 'khaosat_canhan';
    if ($loai_tab == 'doanhnghiep') $bang = 'khaosat_doanhnghiep';
    if ($loai_tab == 'ungvien') $bang = 'ung_vien';

    try {
        if ($action === 'xoa' && !empty($_POST['id'])) {
            // Xóa 1 dòng
            $conn->prepare("DELETE FROM $bang WHERE id = ?")->execute([$_POST['id']]);
        } 
        elseif ($action === 'xoa_nhieu' && !empty($_POST['ids'])) {
            // Xóa hàng loạt
            $inQuery = implode(',', array_fill(0, count($_POST['ids']), '?'));
            $stmt = $conn->prepare("DELETE FROM $bang WHERE id IN ($inQuery)");
            $stmt->execute($_POST['ids']);
        } 
        elseif ($action === 'sua' && !empty($_POST['id'])) {
            // Sửa thông tin liên hệ
            $id = $_POST['id'];
            if ($loai_tab == 'doanhnghiep') {
                $stmt = $conn->prepare("UPDATE $bang SET ten_doanh_nghiep=?, nguoi_dai_dien=?, so_dien_thoai=?, email=? WHERE id=?");
                $stmt->execute([$_POST['ten_doanh_nghiep'], $_POST['nguoi_dai_dien'], $_POST['so_dien_thoai'], $_POST['email'], $id]);
            } elseif ($loai_tab == 'ungvien') {
                $stmt = $conn->prepare("UPDATE $bang SET ho_ten=?, so_dien_thoai=?, nam_sinh=?, cong_viec=?, trinh_do_van_hoa=?, email=? WHERE id=?");
                $stmt->execute([$_POST['ho_ten'], $_POST['so_dien_thoai'], $_POST['nam_sinh'], $_POST['cong_viec'], $_POST['trinh_do_van_hoa'], $_POST['email'], $id]);
            } else {
                $stmt = $conn->prepare("UPDATE $bang SET ho_ten=?, so_dien_thoai=?, email=? WHERE id=?");
                $stmt->execute([$_POST['ho_ten'], $_POST['so_dien_thoai'], $_POST['email'], $id]);
            }
        }
    } catch(PDOException $e) {
        die("Lỗi thao tác: " . $e->getMessage());
    }
    
    // Tải lại trang để tránh lỗi gửi lại form (Form resubmission)
    header("Location: bang-dieu-khien.php");
    exit;
}

// ==========================================
// 2. XỬ LÝ TÌM KIẾM VÀ LỌC THỜI GIAN
// ==========================================
$tu_khoa = $_GET['tu_khoa'] ?? '';
$tu_ngay = $_GET['tu_ngay'] ?? '';
$den_ngay = $_GET['den_ngay'] ?? '';

// Xây dựng câu điều kiện WHERE cho SQL
$sql_cond = "";
$params_cn = []; $params_dn = []; $params_uv = [];

if ($tu_ngay != '') {
    $sql_cond .= " AND DATE(ngay_tao) >= ?";
    $params_cn[] = $tu_ngay; $params_dn[] = $tu_ngay; $params_uv[] = $tu_ngay;
}
if ($den_ngay != '') {
    $sql_cond .= " AND DATE(ngay_tao) <= ?";
    $params_cn[] = $den_ngay; $params_dn[] = $den_ngay; $params_uv[] = $den_ngay;
}

$cond_cn = $sql_cond; $cond_dn = $sql_cond; $cond_uv = $sql_cond;

if ($tu_khoa != '') {
    $tk = "%$tu_khoa%";
    $cond_cn .= " AND (ho_ten LIKE ? OR so_dien_thoai LIKE ? OR email LIKE ?)";
    array_push($params_cn, $tk, $tk, $tk);
    
    $cond_dn .= " AND (ten_doanh_nghiep LIKE ? OR nguoi_dai_dien LIKE ? OR so_dien_thoai LIKE ?)";
    array_push($params_dn, $tk, $tk, $tk);
    
    $cond_uv .= " AND (ho_ten LIKE ? OR so_dien_thoai LIKE ? OR email LIKE ?)";
    array_push($params_uv, $tk, $tk, $tk);
}

// Truy xuất dữ liệu đã lọc
$stmt_cn = $conn->prepare("SELECT * FROM khaosat_canhan WHERE 1=1 $cond_cn ORDER BY ngay_tao DESC");
$stmt_cn->execute($params_cn);
$ds_canhan = $stmt_cn->fetchAll(PDO::FETCH_ASSOC);

$stmt_dn = $conn->prepare("SELECT * FROM khaosat_doanhnghiep WHERE 1=1 $cond_dn ORDER BY ngay_tao DESC");
$stmt_dn->execute($params_dn);
$ds_doanhnghiep = $stmt_dn->fetchAll(PDO::FETCH_ASSOC);

$stmt_uv = $conn->prepare("SELECT * FROM ung_vien WHERE 1=1 $cond_uv ORDER BY ngay_tao DESC");
$stmt_uv->execute($params_uv);
$ds_ungvien = $stmt_uv->fetchAll(PDO::FETCH_ASSOC);

// Đếm số lượng ứng viên cho biểu đồ
$dem_phung_su = 0; $dem_tiem_nang = 0; $dem_thieu_cam_ket = 0;
foreach($ds_ungvien as $uv) {
    if($uv['phan_loai'] == 'Chuyên gia Phụng sự') $dem_phung_su++;
    elseif($uv['phan_loai'] == 'Tư vấn tiềm năng') $dem_tiem_nang++;
    else $dem_thieu_cam_ket++;
}

// Hàm hỗ trợ đọc JSON câu trả lời
$stmt_all_qh = $conn->query("SELECT id, noi_dung_cau_hoi FROM danh_sach_cau_hoi");
$map_cau_hoi = [];
while($row = $stmt_all_qh->fetch(PDO::FETCH_ASSOC)){ $map_cau_hoi[$row['id']] = $row['noi_dung_cau_hoi']; }

function hien_thi_dap_an(string $json_str, array $map_cau_hoi): string {
    $arr = json_decode($json_str, true);
    if(!$arr) return '<span class="text-muted">Chưa có dữ liệu</span>';
    $html = '<ul class="list-unstyled mb-0 text-start small">';
    foreach($arr as $id => $ans) {
        $q_text = isset($map_cau_hoi[$id]) ? $map_cau_hoi[$id] : "Câu hỏi #$id";
        $a_text = is_array($ans) ? implode(', ', $ans) : $ans;
        $html .= "<li class='mb-2'><strong>" . htmlspecialchars($q_text) . "</strong><br><span class='text-primary fw-bold'>&rarr; " . htmlspecialchars($a_text) . "</span></li>";
    }
    return $html . '</ul>';
}
?>

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bảng Điều Khiển - CRM PHẠM NGỌC TV</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f0f2f5; font-family: Arial, sans-serif; }
        .dashboard-header { background-color: #1e2b3c; color: white; padding: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .nav-tabs .nav-link { font-weight: bold; color: #495057; }
        .nav-tabs .nav-link.active { color: #0d6efd; border-bottom: 3px solid #0d6efd; }
        .table-wrapper { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-top: 20px; }
        .filter-box { background: white; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 5px solid #0d6efd; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    </style>
</head>
<body>

    <div class="dashboard-header d-flex justify-content-between align-items-center">
        <div>
            <h3 class="mb-0">HỆ THỐNG QUẢN TRỊ DỮ LIỆU</h3>
            <small>Thương hiệu PHẠM NGỌC TV - Bảo vệ cuộc sống</small>
        </div>
        <div>
            <a href="quan-ly.php" class="btn btn-outline-light btn-sm me-2">Soạn Câu Hỏi</a>
            <a href="index.php" class="btn btn-primary btn-sm"><i class="bi bi-house-fill me-1"></i>🏠 Trang Chủ</a>
        </div>
    </div>

    <div class="container-fluid mt-4">
        
        <div class="filter-box">
            <form method="GET" action="" class="row align-items-end">
                <div class="col-md-3 mb-2 mb-md-0">
                    <label class="form-label fw-bold small text-muted">Từ khóa (Tên, SĐT, Email)</label>
                    <input type="text" name="tu_khoa" class="form-control form-control-sm" value="<?= htmlspecialchars($tu_khoa) ?>" placeholder="Nhập để tìm...">
                </div>
                <div class="col-md-3 mb-2 mb-md-0">
                    <label class="form-label fw-bold small text-muted">Từ ngày</label>
                    <input type="date" name="tu_ngay" class="form-control form-control-sm" value="<?= htmlspecialchars($tu_ngay) ?>">
                </div>
                <div class="col-md-3 mb-2 mb-md-0">
                    <label class="form-label fw-bold small text-muted">Đến ngày</label>
                    <input type="date" name="den_ngay" class="form-control form-control-sm" value="<?= htmlspecialchars($den_ngay) ?>">
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary btn-sm w-100 fw-bold">Lọc Dữ Liệu</button>
                    <?php if($tu_khoa || $tu_ngay || $den_ngay): ?>
                        <a href="bang-dieu-khien.php" class="btn btn-outline-secondary btn-sm w-100 mt-1">Xóa bộ lọc</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <div class="row mb-4">
            <div class="col-md-4 offset-md-4 bg-white rounded shadow-sm">
                <div class="d-flex justify-content-between align-items-center p-3" style="cursor:pointer;" onclick="toggleBieuDo()">
                    <h6 class="text-secondary fw-bold mb-0">📊 Tỷ lệ Phân loại Ứng viên</h6>
                    <span id="iconBieuDo" class="text-muted">▲</span>
                </div>
                <div id="khungBieuDo" class="px-3 pb-3">
                    <div style="position: relative; height: 250px; width: 100%; display: flex; justify-content: center;">
                        <canvas id="bieuDoUngVien"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#canhan">1. Cá Nhân (<?= count($ds_canhan) ?>)</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#doanhnghiep">2. Doanh Nghiệp (<?= count($ds_doanhnghiep) ?>)</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#ungvien">3. Ứng Viên (<?= count($ds_ungvien) ?>)</button></li>
        </ul>

        <div class="tab-content">
            
            <div class="tab-pane fade show active" id="canhan">
                <div class="table-wrapper table-responsive">
                    <form method="POST" onsubmit="return confirm('Bạn chắc chắn muốn xóa các mục đã chọn?');">
                        <input type="hidden" name="action" value="xoa_nhieu">
                        <input type="hidden" name="loai_tab" value="canhan">
                        <button type="submit" class="btn btn-danger btn-sm mb-3">Xóa Dòng Đã Chọn</button>
                        <a href="xuat-excel.php?loai=ca_nhan" class="btn btn-success btn-sm mb-3 ms-2 text-white">📥 Tải Excel (Danh sách này)</a>
                        
                        <table class="table table-hover table-bordered align-middle text-center">
                            <thead class="table-primary">
                                <tr>
                                    <th><input type="checkbox" onclick="toggleCheck(this, 'canhan')"></th>
                                    <th>ID</th> <th>Thời gian</th> <th>Thông tin liên hệ</th> <th>Công cụ</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($ds_canhan as $row): ?>
                                <tr>
                                    <td><input type="checkbox" name="ids[]" value="<?= $row['id'] ?>" class="chk-canhan"></td>
                                    <td>#<?= $row['id'] ?></td>
                                    <td><?= date('d/m/Y H:i', strtotime($row['ngay_tao'])) ?></td>
                                    <td class="text-start">
                                        <strong><?= htmlspecialchars($row['ho_ten']) ?></strong><br>
                                        📞 <?= htmlspecialchars($row['so_dien_thoai']) ?> <br> ✉️ <?= htmlspecialchars($row['email']) ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-info text-white mb-1" data-bs-toggle="modal" data-bs-target="#modalXemCN<?= $row['id'] ?>">Đọc</button>
                                        <button type="button" class="btn btn-sm btn-warning mb-1" data-bs-toggle="modal" data-bs-target="#modalSuaCN<?= $row['id'] ?>">Sửa</button>
                                        <a href="xuat-pdf.php?id=<?= $row['id'] ?>&loai=ca_nhan" target="_blank" class="btn btn-sm btn-dark mb-1">PDF</a>
                                        <a href="https://zalo.me/<?= preg_replace('/[^0-9]/', '', $row['so_dien_thoai']) ?>" target="_blank" class="btn btn-sm btn-primary mb-1">Zalo</a>
                                        
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Xóa hồ sơ này?');">
                                            <input type="hidden" name="action" value="xoa">
                                            <input type="hidden" name="loai_tab" value="canhan">
                                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-danger mb-1">Xóa</button>
                                        </form>

                                        <div class="modal fade" id="modalSuaCN<?= $row['id'] ?>">
                                            <div class="modal-dialog text-start">
                                                <div class="modal-content">
                                                    <div class="modal-header bg-warning"><h5 class="modal-title">Sửa thông tin: <?= htmlspecialchars($row['ho_ten']) ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                                                    <div class="modal-body">
                                                        <form method="POST">
                                                            <input type="hidden" name="action" value="sua">
                                                            <input type="hidden" name="loai_tab" value="canhan">
                                                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                                            <label>Họ tên</label><input type="text" name="ho_ten" class="form-control mb-2" value="<?= htmlspecialchars($row['ho_ten']) ?>">
                                                            <label>Số điện thoại</label><input type="text" name="so_dien_thoai" class="form-control mb-2" value="<?= htmlspecialchars($row['so_dien_thoai']) ?>">
                                                            <label>Email</label><input type="text" name="email" class="form-control mb-3" value="<?= htmlspecialchars($row['email']) ?>">
                                                            <button type="submit" class="btn btn-warning w-100">Cập Nhật</button>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="modal fade" id="modalXemCN<?= $row['id'] ?>">
                                            <div class="modal-dialog modal-lg text-start"><div class="modal-content"><div class="modal-header bg-primary text-white"><h5 class="modal-title">Chi tiết: <?= htmlspecialchars($row['ho_ten']) ?></h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body"><?= hien_thi_dap_an($row['cau_tra_loi'], $map_cau_hoi) ?></div></div></div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </form>
                </div>
            </div>

            <div class="tab-pane fade" id="doanhnghiep">
                <div class="table-wrapper table-responsive">
                    <form method="POST" onsubmit="return confirm('Bạn chắc chắn muốn xóa các mục đã chọn?');">
                        <input type="hidden" name="action" value="xoa_nhieu"><input type="hidden" name="loai_tab" value="doanhnghiep">
                        <button type="submit" class="btn btn-danger btn-sm mb-3">Xóa Dòng Đã Chọn</button>
                        <a href="xuat-excel.php?loai=doanh_nghiep" class="btn btn-success btn-sm mb-3 ms-2 text-white">📥 Tải Excel (Danh sách này)</a>
                        <table class="table table-hover table-bordered align-middle text-center">
                            <thead class="table-success">
                                <tr><th><input type="checkbox" onclick="toggleCheck(this, 'doanhnghiep')"></th><th>ID</th> <th>Thời gian</th> <th>Thông tin Doanh nghiệp</th> <th>Công cụ</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach($ds_doanhnghiep as $row): ?>
                                <tr>
                                    <td><input type="checkbox" name="ids[]" value="<?= $row['id'] ?>" class="chk-doanhnghiep"></td>
                                    <td>#<?= $row['id'] ?></td>
                                    <td><?= date('d/m/Y H:i', strtotime($row['ngay_tao'])) ?></td>
                                    <td class="text-start"><strong><?= htmlspecialchars($row['ten_doanh_nghiep']) ?></strong><br>Đại diện: <?= htmlspecialchars($row['nguoi_dai_dien']) ?><br>📞 <?= htmlspecialchars($row['so_dien_thoai']) ?></td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-success text-white mb-1" data-bs-toggle="modal" data-bs-target="#modalXemDN<?= $row['id'] ?>">Đọc</button>
                                        <button type="button" class="btn btn-sm btn-warning mb-1" data-bs-toggle="modal" data-bs-target="#modalSuaDN<?= $row['id'] ?>">Sửa</button>
                                        <a href="xuat-pdf.php?id=<?= $row['id'] ?>&loai=doanh_nghiep" target="_blank" class="btn btn-sm btn-dark mb-1">PDF</a>
                                        <a href="https://zalo.me/<?= preg_replace('/[^0-9]/', '', $row['so_dien_thoai']) ?>" target="_blank" class="btn btn-sm btn-primary mb-1">Zalo</a>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Xóa hồ sơ này?');"><input type="hidden" name="action" value="xoa"><input type="hidden" name="loai_tab" value="doanhnghiep"><input type="hidden" name="id" value="<?= $row['id'] ?>"><button type="submit" class="btn btn-sm btn-danger mb-1">Xóa</button></form>

                                        <div class="modal fade" id="modalSuaDN<?= $row['id'] ?>"><div class="modal-dialog text-start"><div class="modal-content"><div class="modal-header bg-warning"><h5 class="modal-title">Sửa DN: <?= htmlspecialchars($row['ten_doanh_nghiep']) ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><form method="POST"><input type="hidden" name="action" value="sua"><input type="hidden" name="loai_tab" value="doanhnghiep"><input type="hidden" name="id" value="<?= $row['id'] ?>"><label>Tên DN</label><input type="text" name="ten_doanh_nghiep" class="form-control mb-2" value="<?= htmlspecialchars($row['ten_doanh_nghiep']) ?>"><label>Đại diện</label><input type="text" name="nguoi_dai_dien" class="form-control mb-2" value="<?= htmlspecialchars($row['nguoi_dai_dien']) ?>"><label>SĐT</label><input type="text" name="so_dien_thoai" class="form-control mb-2" value="<?= htmlspecialchars($row['so_dien_thoai']) ?>"><label>Email</label><input type="text" name="email" class="form-control mb-3" value="<?= htmlspecialchars($row['email']) ?>"><button type="submit" class="btn btn-warning w-100">Cập Nhật</button></form></div></div></div></div>
                                        
                                        <div class="modal fade" id="modalXemDN<?= $row['id'] ?>"><div class="modal-dialog modal-lg text-start"><div class="modal-content"><div class="modal-header bg-success text-white"><h5 class="modal-title">Chi tiết: <?= htmlspecialchars($row['ten_doanh_nghiep']) ?></h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body"><?= hien_thi_dap_an($row['cau_tra_loi'], $map_cau_hoi) ?></div></div></div></div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </form>
                </div>
            </div>

            <div class="tab-pane fade" id="ungvien">
                <div class="table-wrapper table-responsive">
                    <form method="POST" onsubmit="return confirm('Bạn chắc chắn muốn xóa các mục đã chọn?');">
                        <input type="hidden" name="action" value="xoa_nhieu"><input type="hidden" name="loai_tab" value="ungvien">
                        <button type="submit" class="btn btn-danger btn-sm mb-3">Xóa Dòng Đã Chọn</button>
                        <a href="xuat-excel.php?loai=ung_vien" class="btn btn-success btn-sm mb-3 ms-2 text-white">📥 Tải Excel (Danh sách này)</a>
                        <table class="table table-hover table-bordered align-middle text-center">
                            <thead class="table-dark">
                                <tr><th><input type="checkbox" onclick="toggleCheck(this, 'ungvien')"></th><th>ID</th> <th>Ứng viên</th> <th>Điểm</th> <th>Công cụ</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach($ds_ungvien as $row): ?>
                                <tr>
                                    <td><input type="checkbox" name="ids[]" value="<?= $row['id'] ?>" class="chk-ungvien"></td>
                                    <td>#<?= $row['id'] ?></td>
                                    <td class="text-start">
                                        <strong><?= htmlspecialchars($row['ho_ten']) ?></strong> (<?= htmlspecialchars($row['nam_sinh']) ?>)<br>
                                        🎓 Trình độ: <?= htmlspecialchars($row['trinh_do_van_hoa']) ?><br>
                                        💼 Nghề nghiệp: <?= htmlspecialchars($row['cong_viec']) ?><br>
                                        📞 <?= htmlspecialchars($row['so_dien_thoai']) ?>
                                    </td>
                                    <td>
                                        <h5 class="text-danger mb-0"><?= $row['diem_so'] ?></h5>
                                        <small class="badge bg-secondary"><?= htmlspecialchars($row['phan_loai']) ?></small>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-dark mb-1" data-bs-toggle="modal" data-bs-target="#modalXemUV<?= $row['id'] ?>">Đọc</button>
                                        <button type="button" class="btn btn-sm btn-warning mb-1" data-bs-toggle="modal" data-bs-target="#modalSuaUV<?= $row['id'] ?>">Sửa</button>
                                        <a href="xuat-pdf.php?id=<?= $row['id'] ?>&loai=ung_vien" target="_blank" class="btn btn-sm btn-secondary mb-1">PDF</a>
                                        <a href="https://zalo.me/<?= preg_replace('/[^0-9]/', '', $row['so_dien_thoai']) ?>" target="_blank" class="btn btn-sm btn-primary mb-1">Zalo</a>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Xóa hồ sơ này?');"><input type="hidden" name="action" value="xoa"><input type="hidden" name="loai_tab" value="ungvien"><input type="hidden" name="id" value="<?= $row['id'] ?>"><button type="submit" class="btn btn-sm btn-danger mb-1">Xóa</button></form>

                                        <div class="modal fade" id="modalSuaUV<?= $row['id'] ?>"><div class="modal-dialog text-start"><div class="modal-content"><div class="modal-header bg-warning"><h5 class="modal-title">Sửa thông tin: <?= htmlspecialchars($row['ho_ten']) ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><form method="POST"><input type="hidden" name="action" value="sua"><input type="hidden" name="loai_tab" value="ungvien"><input type="hidden" name="id" value="<?= $row['id'] ?>"><label>Họ tên</label><input type="text" name="ho_ten" class="form-control mb-2" value="<?= htmlspecialchars($row['ho_ten']) ?>"><label>Số điện thoại</label><input type="text" name="so_dien_thoai" class="form-control mb-2" value="<?= htmlspecialchars($row['so_dien_thoai']) ?>"><label>Năm sinh</label><input type="text" name="nam_sinh" class="form-control mb-2" value="<?= htmlspecialchars($row['nam_sinh']) ?>"><label>Công việc</label><input type="text" name="cong_viec" class="form-control mb-2" value="<?= htmlspecialchars($row['cong_viec']) ?>"><label>Trình độ</label><select name="trinh_do_van_hoa" class="form-select mb-2"><option value="<?= htmlspecialchars($row['trinh_do_van_hoa']) ?>"><?= htmlspecialchars($row['trinh_do_van_hoa']) ?> (Giữ nguyên)</option><option value="Phổ thông trung học">Phổ thông trung học</option><option value="Trung cấp / Cao đẳng">Trung cấp / Cao đẳng</option><option value="Đại học">Đại học</option><option value="Trên Đại học">Trên Đại học</option></select><label>Email</label><input type="text" name="email" class="form-control mb-3" value="<?= htmlspecialchars($row['email']) ?>"><button type="submit" class="btn btn-warning w-100">Cập Nhật</button></form></div></div></div></div>

                                        <div class="modal fade" id="modalXemUV<?= $row['id'] ?>"><div class="modal-dialog modal-lg text-start"><div class="modal-content"><div class="modal-header bg-dark text-white"><h5 class="modal-title">Chi tiết: <?= htmlspecialchars($row['ho_ten']) ?></h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body"><?= hien_thi_dap_an($row['cau_tra_loi'], $map_cau_hoi) ?></div></div></div></div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </form>
                </div>
            </div>

        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // Vẽ biểu đồ tròn
        var ctx = document.getElementById('bieuDoUngVien').getContext('2d');
        new Chart(ctx, {
            type: 'pie',
            data: {
                labels: ['Phụng sự', 'Tiềm năng', 'Thiếu cam kết'],
                datasets: [{
                    data: [<?= $dem_phung_su ?>, <?= $dem_tiem_nang ?>, <?= $dem_thieu_cam_ket ?>],
                    backgroundColor: ['#198754', '#ffc107', '#dc3545'], borderWidth: 1
                }]
            },
            options: { responsive: true, maintainAspectRatio: false }
        });

        // Chọn tất cả Checkbox
        function toggleCheck(source, tab) {
            let checkboxes = document.querySelectorAll('.chk-' + tab);
            checkboxes.forEach(function(chk) { chk.checked = source.checked; });
        }

        // Ẩn/hiện khung biểu đồ
        function toggleBieuDo() {
            const khung = document.getElementById('khungBieuDo');
            const icon = document.getElementById('iconBieuDo');
            const an = khung.style.display === 'none';
            khung.style.display = an ? 'block' : 'none';
            icon.textContent = an ? '▲' : '▼';
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>