// =============================================
// ADMIN PANEL ROUTER & NAVIGATION
// =============================================
function adminNav(page, el) {
    currentAdminPage = page;
    document.querySelectorAll('.admin-nav-item').forEach(n => n.classList.remove('active'));
    if (el) el.classList.add('active');
    const titles = {
        dashboard: t('admin_dashboard'),
        'admin-trainings': t('admin_trainings'),
        'admin-testings': t('admin_testings'),
        'admin-notices': t('admin_notices'),
        'admin-officers': t('admin_management'),
        'admin-employees': t('admin_employees'),
        'admin-trainees': t('admin_trainees'),
        'admin-equipment': t('admin_equipment'),
        'admin-gallery': t('admin_gallery'),
        'admin-videos': t('admin_videos'),
        'admin-facilities': t('admin_facilities'),
        'admin-sliders': t('admin_sliders'),
        'admin-settings': t('admin_settings'),
        'admin-reports': t('admin_reports')
    };
    document.getElementById('admin-page-title').textContent = titles[page] || t('admin_dashboard');
    renderAdminPage();
    document.getElementById('admin-sidebar')?.classList.remove('open');
}

async function renderAdminPage() {
    const c = document.getElementById('admin-content');
    c.innerHTML = '<div class="flex justify-center items-center h-64"><div class="loader"></div></div>';

    const entityMap = {
        dashboard: ['stats', 'trainings', 'testings', 'trainees', 'notices'],
        'admin-trainings': ['trainings'], 'admin-testings': ['testings'], 'admin-notices': ['notices'],
        'admin-officers': ['officers'], 'admin-employees': ['employees'], 'admin-trainees': ['trainees'],
        'admin-equipment': ['equipment'], 'admin-gallery': ['gallery'], 'admin-videos': ['videos'],
        'admin-facilities': ['facilities'], 'admin-sliders': ['sliders']
    };

    const entities = entityMap[currentAdminPage] || [];
    await Promise.all(entities.map(e => {
        try {
            return e === 'stats' ? api('stats').then(v => { siteStats = v || {}; }).catch(() => { }) : refreshEntity(e);
        } catch (err) { return Promise.resolve(); }
    }));

    const renders = {
        dashboard: adminDashboard,
        'admin-trainings': () => adminCrudList('trainings', t('admin_trainings'), [t('col_image'), t('col_title'), t('col_category'), t('col_date'), t('col_status')]),
        'admin-testings': () => adminCrudList('testings', t('admin_testing_services'), [t('col_image'), t('col_title'), t('col_type'), t('col_turnaround')]),
        'admin-notices': () => adminCrudList('notices', t('admin_notices'), [t('col_title'), t('col_date'), t('col_type')]),
        'admin-officers': () => adminCrudList('officers', t('admin_management'), [t('col_photo'), t('col_name'), t('col_designation'), t('col_email')]),
        'admin-employees': () => adminCrudList('employees', t('admin_employees'), [t('col_photo'), t('col_name'), t('col_designation'), t('col_department')]),
        'admin-trainees': () => adminCrudList('trainees', t('admin_trainees'), [t('col_name'), t('col_email'), t('col_organization')]),
        'admin-equipment': () => adminCrudList('equipment', t('admin_equipment'), [t('col_image'), t('col_name'), t('col_capacity'), t('col_standard')]),
        'admin-gallery': () => adminCrudList('gallery', t('admin_gallery'), [t('col_image'), t('col_title'), t('col_category')]),
        'admin-videos': () => adminCrudList('videos', t('admin_videos'), [t('col_title'), t('col_category'), t('col_url')]),
        'admin-facilities': () => adminCrudList('facilities', t('admin_facilities'), [t('col_image'), t('col_type'), t('col_title'), t('col_capacity')]),
        'admin-sliders': () => adminCrudList('sliders', t('admin_sliders'), [t('col_image'), t('col_title'), t('col_subtitle'), t('col_order')]),
        'admin-settings': adminSettings,
        'admin-reports': adminReports
    };

    const fn = renders[currentAdminPage] || adminDashboard;
    c.innerHTML = '<div class="fade-in">' + fn() + '</div>';
}

// =============================================
// ADMIN: Trainee Notes System
// =============================================
function getTraineeNotes(userEmail) {
    const data = localStorage.getItem(`pwdta_admin_notes_${userEmail}`);
    return data ? JSON.parse(data) : [];
}

function saveTraineeNotes(userEmail, notes) {
    localStorage.setItem(`pwdta_admin_notes_${userEmail}`, JSON.stringify(notes));
}

function addTraineeNote(userEmail) {
    const noteText = document.getElementById('admin-note-input')?.value.trim();
    if (!noteText) { showToast(t('err_note_empty'), 'error'); return; }
    const notes = getTraineeNotes(userEmail);
    notes.unshift({ id: Date.now(), text: noteText, date: new Date().toISOString(), admin: currentUser?.name || 'Admin' });
    saveTraineeNotes(userEmail, notes);
    showToast(t('toast_note_saved'), 'success');
    viewAdminTraineeDashboard(userEmail);
}

function deleteTraineeNote(userEmail, noteId) {
    let notes = getTraineeNotes(userEmail);
    notes = notes.filter(n => n.id !== noteId);
    saveTraineeNotes(userEmail, notes);
    viewAdminTraineeDashboard(userEmail);
}

// =============================================
// ADMIN: Enhanced Dashboard
// =============================================
function adminDashboard() {
    let totalEnrolled = 0, totalInterested = 0;
    const allPrograms = [...trainings.map(tr => ({ ...tr, type: 'training' })), ...testings.map(ts => ({ ...ts, type: 'testing' }))];
    allPrograms.forEach(p => { const s = getProgramStats(p.id); totalEnrolled += s.enrolledCount; totalInterested += s.interestedCount; });

    const ongoingTrainings = trainings.filter(t => t.status === 'ongoing').length;
    const upcomingTrainings = trainings.filter(t => t.status === 'upcoming').length;

    const overviewHTML = allPrograms.length > 0
        ? allPrograms.map(p => {
            const s = getProgramStats(p.id);
            const total = s.enrolledCount + s.interestedCount;
            const barPct = total > 0 ? Math.round((s.enrolledCount / total) * 100) : 50;
            return `<div class="flex items-center gap-3 p-3 rounded-xl cursor-pointer hover:shadow-md transition-all group" style="border:1px solid var(--border)" onclick="viewProgramEnrollments(${p.id},'${p.type}')">
                <div class="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style="background:${p.type === 'training' ? 'var(--primary-glow)' : 'var(--accent-glow)'}"><i class="fas ${p.type === 'training' ? 'fa-chalkboard-teacher' : 'fa-flask'} text-sm" style="color:${p.type === 'training' ? 'var(--primary)' : 'var(--accent)'}"></i></div>
                <div class="flex-1 min-w-0">
                    <div class="text-sm font-medium truncate">${escAttr(p.title)}</div>
                    <div class="flex items-center gap-1 mt-0.5">
                        <span class="badge ${p.type === 'training' ? 'badge-info' : 'badge-warning'}" style="font-size:9px">${p.type === 'training' ? t('type_training') : t('type_testing')}</span>
                        ${p.type === 'training' && p.status ? `<span class="badge ${p.status === 'ongoing' ? 'badge-success' : p.status === 'upcoming' ? 'badge-info' : 'badge-warning'}" style="font-size:9px">${escAttr(p.status)}</span>` : ''}
                    </div>
                    <div class="w-full h-1.5 rounded-full mt-1.5 overflow-hidden" style="background:#f1f5f9">
                        <div class="h-full rounded-full" style="width:${barPct}%;background:linear-gradient(90deg,#059669,#34d399)"></div>
                    </div>
                </div>
                <div class="flex gap-2 shrink-0">
                    <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold" style="background:#ecfdf5;color:#059669;border:1px solid #a7f3d0"><i class="fas fa-user-check text-[8px]"></i>${s.enrolledCount}</span>
                    <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold" style="background:#fef2f2;color:#dc2626;border:1px solid #fecaca"><i class="far fa-heart text-[8px]"></i>${s.interestedCount}</span>
                </div>
                <i class="fas fa-chevron-right text-xs text-gray-300 group-hover:text-gray-500 transition"></i>
            </div>`;
        }).join('')
        : `<div class="text-center py-8 text-gray-400 text-sm">${t('dash_no_programs')}</div>`;

    return `
    <!-- Top Stats Row -->
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">${[
            { n: siteStats.trainings ?? trainings.length ?? 0, l: t('admin_trainings'), c: '#003366', i: 'fa-chalkboard-teacher', bg: '#eff6ff', sub: `${ongoingTrainings} ${t('dash_active')}` },
            { n: siteStats.testings ?? testings.length ?? 0, l: t('admin_testings'), c: '#d97706', i: 'fa-flask', bg: '#fffbeb', sub: `${testings.length} ${t('dash_services')}` },
            { n: siteStats.notices ?? notices.length ?? 0, l: t('admin_notices'), c: '#dc2626', i: 'fa-bullhorn', bg: '#fef2f2', sub: `${notices.filter(n => n.type === 'important').length} ${t('dash_urgent')}` },
            { n: siteStats.trainees ?? trainees.length ?? 0, l: t('admin_trainees'), c: '#059669', i: 'fa-user-graduate', bg: '#ecfdf5', sub: `${totalEnrolled} ${t('dash_enrolled')}` }
        ].map(s => `<div class="stat-card relative overflow-hidden">
        <div class="absolute top-0 right-0 w-16 h-16 rounded-full -mr-4 -mt-4 opacity-10" style="background:${s.c}"></div>
        <div class="flex items-center justify-between">
            <div>
                <div class="text-xs text-gray-500">${s.l}</div>
                <div class="text-2xl font-bold mt-1" style="color:${s.c}">${s.n}</div>
                <div class="text-[10px] text-gray-400 mt-0.5">${s.sub}</div>
            </div>
            <div class="w-11 h-11 rounded-xl flex items-center justify-center" style="background:${s.bg}"><i class="fas ${s.i}" style="color:${s.c}"></i></div>
        </div>
    </div>`).join('')}</div>

    <!-- Enrollment Stats Row -->
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="stat-card border-l-4 border-green-500">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-lg flex items-center justify-center" style="background:#ecfdf5"><i class="fas fa-user-check text-green-600"></i></div>
                <div><div class="text-xs text-gray-500">${t('dash_total_enrolled')}</div><div class="text-2xl font-bold text-green-700">${totalEnrolled}</div></div>
            </div>
        </div>
        <div class="stat-card border-l-4 border-red-400">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-lg flex items-center justify-center" style="background:#fef2f2"><i class="fas fa-heart text-red-500"></i></div>
                <div><div class="text-xs text-gray-500">${t('dash_total_interested')}</div><div class="text-2xl font-bold text-red-700">${totalInterested}</div></div>
            </div>
        </div>
        <div class="stat-card border-l-4 border-blue-500">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-lg flex items-center justify-center" style="background:#eff6ff"><i class="fas fa-play-circle text-blue-600"></i></div>
                <div><div class="text-xs text-gray-500">${t('dash_ongoing_courses')}</div><div class="text-2xl font-bold text-blue-700">${ongoingTrainings}</div></div>
            </div>
        </div>
        <div class="stat-card border-l-4 border-purple-500">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-lg flex items-center justify-center" style="background:#f5f3ff"><i class="fas fa-calendar-plus text-purple-600"></i></div>
                <div><div class="text-xs text-gray-500">${t('dash_upcoming_courses')}</div><div class="text-2xl font-bold text-purple-700">${upcomingTrainings}</div></div>
            </div>
        </div>
    </div>

    <!-- Program Overview -->
    <div class="admin-card mb-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="font-semibold text-sm flex items-center gap-2"><i class="fas fa-list-alt text-indigo-500"></i> ${t('dash_program_overview')}</h3>
            <button class="btn-outline btn-sm" onclick="exportEnrollmentReport()"><i class="fas fa-download mr-1"></i>${t('btn_report')}</button>
        </div>
        
    </div>

    <!-- Bottom Grid -->
    <div class="grid lg:grid-cols-3 gap-4 mt-6">
        <!-- Recent Enrollments -->
        <div class="admin-card">
            <div class="flex items-center justify-between mb-3">
                <h3 class="font-semibold text-sm flex items-center gap-2"><i class="fas fa-user-plus text-green-500"></i> ${t('dash_recent_enrollments')}</h3>
                <button class="text-[10px] text-blue-500 hover:underline" onclick="adminNav('admin-trainees',document.querySelector('[onclick*=trainees]'))">${t('btn_view_all')}</button>
            </div>
            <div class="space-y-2">${trainees.slice(0, 5).map(te => {
            const initial = (te.name || 'U')[0].toUpperCase();
            const colors = ['#312E81', '#06B6D4', '#059669', '#D97706', '#DC2626'];
            const color = colors[(te.name || 'A').charCodeAt(0) % colors.length];
            return `<div class="flex items-center gap-3 p-2.5 rounded-lg hover:bg-gray-50 transition cursor-pointer" onclick="viewAdminTraineeDashboard('${escAttr(te.email || '')}')">
                    <div class="w-9 h-9 rounded-full flex items-center justify-center text-xs font-bold text-white" style="background:${color}">${initial}</div>
                    <div class="flex-1 min-w-0"><div class="text-sm font-medium truncate">${escAttr(te.name || '-')}</div><div class="text-[10px] text-gray-400">${escAttr(te.org || te.organization || '-')}</div></div>
                    <i class="fas fa-chevron-right text-[8px] text-gray-300"></i>
                </div>`;
        }).join('') || `<p class="text-xs text-gray-400 text-center py-4">${t('dash_no_enrollments')}</p>`}</div>
        </div>

        <!-- Recent Notices -->
        <div class="admin-card">
            <div class="flex items-center justify-between mb-3">
                <h3 class="font-semibold text-sm flex items-center gap-2"><i class="fas fa-bullhorn text-orange-500"></i> ${t('dash_recent_notices')}</h3>
                <button class="text-[10px] text-blue-500 hover:underline" onclick="adminNav('admin-notices',document.querySelector('[onclick*=notices]'))">${t('btn_view_all')}</button>
            </div>
            <div class="space-y-2">${notices.slice(0, 5).map(n => `<div class="flex items-center gap-3 p-2.5 rounded-lg hover:bg-gray-50 transition">
                <div class="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style="background:${n.type === 'important' ? '#fef2f2' : n.type === 'new' ? '#eff6ff' : '#f5f3ff'}"><i class="fas ${n.type === 'important' ? 'fa-exclamation-triangle text-red-500' : n.type === 'new' ? 'fa-bell text-blue-500' : 'fa-info-circle text-purple-500'} text-xs"></i></div>
                <div class="flex-1 min-w-0"><div class="text-sm font-medium truncate">${escAttr(n.title)}</div><div class="text-[10px] text-gray-400">${n.date || ''}</div></div>
                <span class="badge ${n.type === 'important' ? 'badge-danger' : n.type === 'new' ? 'badge-info' : 'badge-warning'}" style="font-size:8px">${escAttr(n.type)}</span>
            </div>`).join('') || `<p class="text-xs text-gray-400 text-center py-4">${t('dash_no_notices')}</p>`}</div>
        </div>

        <!-- Quick Actions -->
        <div class="admin-card">
            <h3 class="font-semibold mb-3 text-sm flex items-center gap-2"><i class="fas fa-bolt text-yellow-500"></i> ${t('dash_quick_actions')}</h3>
            <div class="space-y-2">
                <button class="w-full text-left p-3 rounded-lg text-sm hover:bg-green-50 transition flex items-center gap-3 group" style="border:1px solid var(--border)" onclick="openAdminForm('trainings')"><div class="w-8 h-8 rounded-lg flex items-center justify-center bg-green-100 group-hover:bg-green-200 transition"><i class="fas fa-plus text-green-600 text-xs"></i></div><span>${t('dash_add_training')}</span></button>
                <button class="w-full text-left p-3 rounded-lg text-sm hover:bg-blue-50 transition flex items-center gap-3 group" style="border:1px solid var(--border)" onclick="openAdminForm('notices')"><div class="w-8 h-8 rounded-lg flex items-center justify-center bg-blue-100 group-hover:bg-blue-200 transition"><i class="fas fa-bullhorn text-blue-600 text-xs"></i></div><span>${t('dash_add_notice')}</span></button>
                <button class="w-full text-left p-3 rounded-lg text-sm hover:bg-purple-50 transition flex items-center gap-3 group" style="border:1px solid var(--border)" onclick="openAdminForm('testings')"><div class="w-8 h-8 rounded-lg flex items-center justify-center bg-purple-100 group-hover:bg-purple-200 transition"><i class="fas fa-flask text-purple-600 text-xs"></i></div><span>${t('dash_add_testing')}</span></button>
                <button class="w-full text-left p-3 rounded-lg text-sm hover:bg-orange-50 transition flex items-center gap-3 group" style="border:1px solid var(--border)" onclick="adminNav('admin-reports',document.querySelector('[onclick*=reports]'))"><div class="w-8 h-8 rounded-lg flex items-center justify-center bg-orange-100 group-hover:bg-orange-200 transition"><i class="fas fa-chart-pie text-orange-600 text-xs"></i></div><span>${t('dash_view_reports')}</span></button>
                <button class="w-full text-left p-3 rounded-lg text-sm hover:bg-red-50 transition flex items-center gap-3 group" style="border:1px solid var(--border)" onclick="exportFullReport()"><div class="w-8 h-8 rounded-lg flex items-center justify-center bg-red-100 group-hover:bg-red-200 transition"><i class="fas fa-file-export text-red-600 text-xs"></i></div><span>${t('dash_export_full_report')}</span></button>
            </div>
        </div>
    </div>`;
}

// =============================================
// ADMIN: Recent Activity Tracker
// =============================================
function getRecentAdminActivity() {
    const data = localStorage.getItem('pwdta_admin_activity');
    return data ? JSON.parse(data) : [];
}

function logAdminActivity(action, detail) {
    const activities = getRecentAdminActivity();
    activities.unshift({ action, detail, date: new Date().toISOString(), admin: currentUser?.name || 'Admin' });
    if (activities.length > 50) activities.length = 50;
    localStorage.setItem('pwdta_admin_activity', JSON.stringify(activities));
}

// =============================================
// ADMIN: Enhanced CRUD List
// =============================================
function adminCrudList(entity, title, columns) {
    let data = [];
    if (entity === 'trainings') data = trainings;
    else if (entity === 'testings') data = testings;
    else if (entity === 'notices') data = notices;
    else if (entity === 'officers') data = officers;
    else if (entity === 'employees') data = employees;
    else if (entity === 'trainees') data = trainees;
    else if (entity === 'equipment') data = equipment;
    else if (entity === 'gallery') data = galleryItems;
    else if (entity === 'videos') data = videoItems;
    else if (entity === 'facilities') data = facilities;
    else if (entity === 'sliders') data = sliders;

    let displayColumns = [...columns];
    if (entity === 'trainings' || entity === 'testings') {
        displayColumns.push(t('col_enrolled'));
        displayColumns.push(t('col_interested'));
    }

    const entityIcons = {
        trainings: 'fa-chalkboard-teacher', testings: 'fa-flask', notices: 'fa-bullhorn',
        officers: 'fa-user-tie', employees: 'fa-users', trainees: 'fa-user-graduate',
        equipment: 'fa-tools', gallery: 'fa-images', videos: 'fa-video',
        facilities: 'fa-building', sliders: 'fa-images'
    };
    const entityIcon = entityIcons[entity] || 'fa-database';

    const ths = displayColumns.map(c => `<th>${c}</th>`).join('');
    const rows = data.map((item, idx) => {
        let tds = getAdminRowCells(item, entity);
        const rowId = `row-${entity}-${item.id ?? idx}`;
        return `<tr id="${rowId}" class="hover:bg-gray-50 transition">${tds}<td><div class="flex gap-1">
            <button class="btn-primary btn-sm" onclick="openAdminForm('${entity}',${item.id ?? 0})" title="${t('btn_edit')}"><i class="fas fa-edit"></i></button>
            <button class="btn-danger btn-sm" onclick="adminDelete('${entity}',${item.id ?? 0})" title="${t('btn_delete')}"><i class="fas fa-trash"></i></button>
            ${entity === 'trainings' || entity === 'testings' ? `<button class="btn-outline btn-sm" onclick="viewProgramEnrollments(${item.id ?? 0},'${entity === 'trainings' ? 'training' : 'testing'}')" title="${t('btn_enrollments')}"><i class="fas fa-users"></i></button>` : ''}
            ${entity === 'trainees' && item.email ? `<button class="btn-outline btn-sm" onclick="viewAdminTraineeDashboard('${escAttr(item.email)}')" title="${t('btn_dashboard')}"><i class="fas fa-user-circle"></i></button>` : ''}
        </div></td></tr>`;
    }).join('');

    return `
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 mb-6">
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl flex items-center justify-center" style="background:var(--primary-glow)"><i class="fas ${entityIcon}" style="color:var(--primary)"></i></div>
            <div><h3 class="font-bold text-lg">${title}</h3><div class="text-xs text-gray-400">${data.length} ${t('crud_records')}</div></div>
        </div>
        <div class="flex items-center gap-2 flex-wrap">
            <div class="relative">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
                <input type="text" id="admin-table-search" placeholder="${t('crud_search')}" class="pl-9 pr-4 py-2 rounded-lg border text-sm w-48 focus:ring-2 focus:ring-blue-400 focus:border-blue-400 transition" style="border-color:var(--border)" oninput="filterAdminTable(this.value)">
            </div>
            <button class="btn-outline btn-sm" onclick="exportEntityCSV('${entity}')" title="${t('btn_export')}"><i class="fas fa-download mr-1"></i>${t('btn_export')}</button>
            <button class="btn-primary" onclick="openAdminForm('${entity}')"><i class="fas fa-plus mr-2"></i>${t('admin_add_new')}</button>
        </div>
    </div>

    <div class="admin-card overflow-x-auto">
        <table class="admin-table" id="admin-crud-table">
            <thead><tr>${ths}<th style="width:120px">${t('admin_actions')}</th></tr></thead>
            <tbody>${rows || `<tr><td colspan="${displayColumns.length + 1}" class="text-center py-12 text-gray-400">
                <div class="flex flex-col items-center gap-3"><div class="w-16 h-16 rounded-full flex items-center justify-center bg-gray-100"><i class="fas ${entityIcon} text-2xl text-gray-300"></i></div>
                <p>${t('admin_no_records')}</p><button class="btn-primary btn-sm" onclick="openAdminForm('${entity}')"><i class="fas fa-plus mr-1"></i>${t('btn_add_new_short')}</button></div>
            </td></tr>`}</tbody>
        </table>
    </div>`;
}

function filterAdminTable(query) {
    const table = document.getElementById('admin-crud-table');
    if (!table) return;
    const q = query.toLowerCase();
    table.querySelectorAll('tbody tr').forEach(row => {
        row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
}

function exportEntityCSV(entity) {
    let data = [];
    if (entity === 'trainings') data = trainings;
    else if (entity === 'testings') data = testings;
    else if (entity === 'notices') data = notices;
    else if (entity === 'officers') data = officers;
    else if (entity === 'employees') data = employees;
    else if (entity === 'trainees') data = trainees;
    else if (entity === 'equipment') data = equipment;
    else if (entity === 'gallery') data = galleryItems;
    else if (entity === 'videos') data = videoItems;
    else if (entity === 'facilities') data = facilities;
    else if (entity === 'sliders') data = sliders;

    if (data.length === 0) { showToast(t('err_no_export_data'), 'error'); return; }

    const keys = Object.keys(data[0]);
    let csv = keys.join(',') + '\n';
    data.forEach(item => {
        csv += keys.map(k => `"${String(item[k] || '').replace(/"/g, '""')}"`).join(',') + '\n';
    });

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${entity}_export_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
    URL.revokeObjectURL(link.href);
    showToast(t('toast_export_success'), 'success');
}

function getAdminRowCells(item, entity) {
    // Image Thumbnail Helper
    const thumb = (img) => `<img src="${img ? escAttr(img) : ''}" class="w-10 h-10 rounded-lg object-cover border bg-gray-50" style="border-color:var(--border)" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2240%22 height=%2240%22 viewBox=%220 0 24 24%22 fill=%22none%22 stroke=%22%23cbd5e1%22 stroke-width=%222%22%3E%3Crect x=%223%22 y=%223%22 width=%2218%22 height=%2218%22 rx=%222%22/%3E%3Ccircle cx=%228.5%22 cy=%228.5%22 r=%221.5%22/%3E%3Cpath d=%22m21 15-5-5L5 21%22/%3E%3C/svg%3E'"">`;

    // ✅ সংশোধিত কোড
    if (entity === 'trainings') {
        fields = `
    <div class="form-group">
        <label>${t('form_title_req')}</label>
        <input type="text" id="af-title" required value="${escAttr(isEdit ? (item.title || '') : '')}" placeholder="${t('form_training_title_ph')}">
    </div>
    <div class="form-group">
        <label>${t('form_description')}</label>
        <textarea id="af-desc" rows="3" placeholder="${t('form_detailed_desc_ph')}">${escAttr(isEdit ? (item.desc || '') : '')}</textarea>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_category')}</label>
            <select id="af-category">
                <option value="Short Course" ${isEdit && item.category === 'Short Course' ? 'selected' : ''}>Short Course</option>
                <option value="Workshop" ${isEdit && item.category === 'Workshop' ? 'selected' : ''}>Workshop</option>
                <option value="Seminar" ${isEdit && item.category === 'Seminar' ? 'selected' : ''}>Seminar</option>
                <option value="Long Course" ${isEdit && item.category === 'Long Course' ? 'selected' : ''}>Long Course</option>
            </select>
        </div>
        <div class="form-group">
            <label>${t('form_status')}</label>
            <select id="af-status">
                <option value="upcoming" ${isEdit && item.status === 'upcoming' ? 'selected' : ''}>Upcoming</option>
                <option value="ongoing" ${isEdit && item.status === 'ongoing' ? 'selected' : ''}>Ongoing</option>
                <option value="completed" ${isEdit && item.status === 'completed' ? 'selected' : ''}>Completed</option>
            </select>
        </div>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_start_date')}</label>
            <input type="date" id="af-start" value="${isEdit ? (item.start || '') : ''}">
        </div>
        <div class="form-group">
            <label>${t('form_end_date')}</label>
            <input type="date" id="af-end" value="${isEdit ? (item.end || '') : ''}">
        </div>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_fee')}</label>
            <input type="number" id="af-fee" value="${isEdit ? (item.fee || 0) : 0}" min="0" step="0.01">
        </div>
        <div class="form-group">
            <label>${t('form_duration')}</label>
            <input type="text" id="af-duration" value="${escAttr(isEdit ? (item.duration || '') : '')}" placeholder="e.g. 10 Days">
        </div>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_capacity')}</label>
            <input type="number" id="af-capacity" value="${isEdit ? (item.capacity || 30) : 30}" min="0">
        </div>
        <div class="form-group">
            <label>${t('form_venue')}</label>
            <input type="text" id="af-venue" value="${escAttr(isEdit ? (item.venue || '') : '')}">
        </div>
    </div>
    ${imgField(isEdit ? (item.img || '') : '')}`;
    } else if (entity === 'testings') {   // ← ✅ else if যোগ করা হয়েছে!
        fields = `<div class="form-group"><label>${t('form_test_name_req')}</label><input type="text" id="af-title" required value="${escAttr(isEdit ? (item.title || '') : '')}"></div><div class="form-group"><label>${t('form_description')}</label><textarea id="af-desc" rows="3">${escAttr(isEdit ? (item.desc || '') : '')}</textarea></div><div class="form-row"><div class="form-group"><label>${t('form_test_type')}</label><select id="af-testType"><option value="Concrete" ${isEdit && item.testType === 'Concrete' ? 'selected' : ''}>Concrete</option><option value="Soil" ${isEdit && item.testType === 'Soil' ? 'selected' : ''}>Soil</option><option value="Steel" ${isEdit && item.testType === 'Steel' ? 'selected' : ''}>Steel</option><option value="Bitumen" ${isEdit && item.testType === 'Bitumen' ? 'selected' : ''}>Bitumen</option><option value="Brick" ${isEdit && item.testType === 'Brick' ? 'selected' : ''}>Brick</option><option value="Timber" ${isEdit && item.testType === 'Timber' ? 'selected' : ''}>Timber</option></select></div><div class="form-group"><label>${t('form_turnaround_days')}</label><input type="number" id="af-turnaround" value="${isEdit ? (item.turnaround || 3) : 3}" min="1"></div></div>${imgField(isEdit ? (item.img || '') : '')}`;
    } else if (entity === 'notices') {
        if (entity === 'testings') {
            const stats = getProgramStats(item.id);
            return `<td>${thumb(item.img)}</td><td class="font-medium">${escAttr(item.title)}</td><td><span class="badge badge-info">${escAttr(item.testType || '-')}</span></td><td class="text-xs">${escAttr(item.turnaround || '-')}</td><td class="text-center"><button onclick="viewProgramEnrollments(${item.id},'testing')" class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold cursor-pointer" style="background:#ecfdf5;color:#059669;border:1px solid #a7f3d0"><i class="fas fa-user-check text-[10px]"></i> ${stats.enrolledCount}</button></td><td class="text-center"><button onclick="viewProgramEnrollments(${item.id},'testing')" class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold cursor-pointer" style="background:#fef2f2;color:#dc2626;border:1px solid #fecaca"><i class="far fa-heart text-[10px]"></i> ${stats.interestedCount}</button></td>`;
        }
        if (entity === 'notices') return `<td class="font-medium">${escAttr(item.title)}</td><td class="text-xs">${item.date || '-'}</td><td><span class="badge ${item.type === 'important' ? 'badge-danger' : item.type === 'new' ? 'badge-info' : 'badge-warning'}">${escAttr(item.type || '-')}</span></td>`;
        if (entity === 'officers') {
            const officerImg = item.img ? escAttr(item.img) : getDefaultPersonSVG(item.name);
            return `<td><img src="${officerImg}" class="w-10 h-10 rounded-full object-cover" onerror="handleImgError(this,'person','')"></td><td class="font-medium">${escAttr(item.name)}</td><td>${escAttr(item.designation || '-')}</td><td class="text-xs">${escAttr(item.email || '-')}</td>`;
        }
        if (entity === 'employees') {
            const empImg = item.img ? escAttr(item.img) : getDefaultPersonSVG(item.name);
            return `<td><div class="w-10 h-10 rounded-full overflow-hidden border" style="border-color:var(--border)"><img src="${empImg}" class="w-full h-full object-cover" onerror="handleImgError(this,'person','')"></div></td><td class="font-medium">${escAttr(item.name || '-')}</td><td>${escAttr(item.designation || '-')}</td><td class="text-xs">${escAttr(item.department || '-')}</td>`;
        }
        if (entity === 'trainees') return `<td class="font-medium">${escAttr(item.name || '-')}</td><td class="text-xs">${escAttr(item.email || '-')}</td><td class="text-xs">${escAttr(item.org || item.organization || '-')}</td>`;
        if (entity === 'equipment') {
            return `<td>${thumb(item.img)}</td><td class="font-medium">${escAttr(item.name || '-')}</td><td class="text-xs">${escAttr(item.capacity || '-')}</td><td class="text-xs">${escAttr(item.standard || '-')}</td>`;
        }
        if (entity === 'gallery') {
            return `<td>${thumb(item.img)}</td><td class="font-medium">${escAttr(item.title || '-')}</td><td><span class="badge badge-info">${escAttr(item.category || '-')}</span></td>`;
        }
        if (entity === 'videos') return `<td class="font-medium">${escAttr(item.title || '-')}</td><td><span class="badge badge-info">${escAttr(item.category || '-')}</span></td><td class="text-xs text-blue-600">${item.url ? '<i class="fas fa-external-link-alt mr-1"></i>Link' : '-'}</td>`;
        if (entity === 'facilities') {
            return `<td>${thumb(item.img)}</td><td><span class="badge badge-info">${escAttr(item.type || '-')}</span></td><td class="font-medium">${escAttr(item.title || item.type || '-')}</td><td class="text-xs">${item.capacity || '-'}</td>`;
        }
        if (entity === 'sliders') {
            return `<td>${thumb(item.img)}</td><td class="font-medium">${escAttr(item.title || '-')}</td><td class="text-xs">${escAttr(item.subtitle || '-')}</td><td class="text-xs">${item.order ?? '-'}</td>`;
        }
        return '<td>-</td>';
    }

    // =============================================
    // ADMIN: Enhanced Add/Edit Form
    // =============================================
    function openAdminForm(entity, id = null) {
        let data = [];
        if (entity === 'trainings') data = trainings;
        else if (entity === 'testings') data = testings;
        else if (entity === 'notices') data = notices;
        else if (entity === 'officers') data = officers;
        else if (entity === 'trainees') data = trainees;
        else if (entity === 'equipment') data = equipment;
        else if (entity === 'gallery') data = galleryItems;
        else if (entity === 'videos') data = videoItems;
        else if (entity === 'facilities') data = facilities;
        else if (entity === 'sliders') data = sliders;
        else if (entity === 'employees') data = employees;

        const numericId = (id !== null && id !== 'null' && id !== 0) ? parseInt(id) : null;
        const item = numericId ? data.find(d => parseInt(d.id) === numericId) : null;
        const isEdit = !!item;

        const entityNames = { trainings: t('entity_training'), testings: t('entity_testing'), notices: t('entity_notice'), officers: t('entity_officer'), employees: t('entity_employee'), trainees: t('entity_trainee'), equipment: t('entity_equipment'), gallery: t('entity_gallery'), videos: t('entity_video'), facilities: t('entity_facility'), sliders: t('entity_slider') };
        const title = isEdit ? `${t('form_edit')} ${entityNames[entity] || entity}` : `${t('form_new')} ${entityNames[entity] || entity}`;
        const entityIcons = { trainings: 'fa-chalkboard-teacher', testings: 'fa-flask', notices: 'fa-bullhorn', officers: 'fa-user-tie', employees: 'fa-users', trainees: 'fa-user-graduate', equipment: 'fa-tools', gallery: 'fa-images', videos: 'fa-video', facilities: 'fa-building', sliders: 'fa-images' };

        const imgField = (val) => `<div class="form-group"><label>${t('form_image')}</label><div class="flex items-center gap-4"><div id="img-preview-box" class="w-24 h-24 rounded-xl overflow-hidden border-2 border-dashed flex items-center justify-center ${val ? '' : 'bg-gray-50'}" style="border-color:var(--border)"><img id="img-preview-tag" src="${val ? escAttr(val) : ''}" class="${val ? 'w-full h-full object-cover' : 'hidden'}"><span id="img-placeholder" class="text-gray-300 ${val ? 'hidden' : ''}"><i class="fas fa-image text-2xl"></i></span></div><div class="flex-1"><input type="file" id="af-img-file" accept="image/*" onchange="previewAdminImage(this)" class="text-sm"><p class="text-[10px] text-gray-400 mt-1">${t('form_img_hint')}</p></div></div><input type="hidden" id="af-img" value="${escAttr(val || '')}"></div>`;

        let fields = '';

        if (entity === 'trainings') {
            fields = `
    <div class="form-group">
        <label>${t('form_title_req')}</label>
        <input type="text" id="af-title" required value="${escAttr(isEdit ? (item.title || '') : '')}" placeholder="${t('form_training_title_ph')}">
    </div>
    <div class="form-group">
        <label>${t('form_description')}</label>
        <textarea id="af-desc" rows="3" placeholder="${t('form_detailed_desc_ph')}">${escAttr(isEdit ? (item.desc || '') : '')}</textarea>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_category')}</label>
            <select id="af-category">
                <option value="Short Course" ${isEdit && item.category === 'Short Course' ? 'selected' : ''}>Short Course</option>
                <option value="Workshop" ${isEdit && item.category === 'Workshop' ? 'selected' : ''}>Workshop</option>
                <option value="Seminar" ${isEdit && item.category === 'Seminar' ? 'selected' : ''}>Seminar</option>
                <option value="Long Course" ${isEdit && item.category === 'Long Course' ? 'selected' : ''}>Long Course</option>
            </select>
        </div>
        <div class="form-group">
            <label>${t('form_status')}</label>
            <select id="af-status">
                <option value="upcoming" ${isEdit && item.status === 'upcoming' ? 'selected' : ''}>Upcoming</option>
                <option value="ongoing" ${isEdit && item.status === 'ongoing' ? 'selected' : ''}>Ongoing</option>
                <option value="completed" ${isEdit && item.status === 'completed' ? 'selected' : ''}>Completed</option>
            </select>
        </div>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_start_date')}</label>
            <input type="date" id="af-start" value="${isEdit ? (item.start || '') : ''}">
        </div>
        <div class="form-group">
            <label>${t('form_end_date')}</label>
            <input type="date" id="af-end" value="${isEdit ? (item.end || '') : ''}">
        </div>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_fee')}</label>
            <input type="number" id="af-fee" value="${isEdit ? (item.fee || 0) : 0}" min="0" step="0.01">
        </div>
        <div class="form-group">
            <label>${t('form_duration')}</label>
            <input type="text" id="af-duration" value="${escAttr(isEdit ? (item.duration || '') : '')}" placeholder="e.g. 10 Days">
        </div>
    </div>
    <div class="form-row">
        <div class="form-group">
            <label>${t('form_capacity')}</label>
            <input type="number" id="af-capacity" value="${isEdit ? (item.capacity || 30) : 30}" min="0">
        </div>
        <div class="form-group">
            <label>${t('form_venue')}</label>
            <input type="text" id="af-venue" value="${escAttr(isEdit ? (item.venue || '') : '')}">
        </div>
    </div>
    ${imgField(isEdit ? (item.img || '') : '')}`;
            fields = `<div class="form-group"><label>${t('form_test_name_req')}</label><input type="text" id="af-title" required value="${escAttr(isEdit ? (item.title || '') : '')}"></div><div class="form-group"><label>${t('form_description')}</label><textarea id="af-desc" rows="3">${escAttr(isEdit ? (item.desc || '') : '')}</textarea></div><div class="form-row"><div class="form-group"><label>${t('form_test_type')}</label><select id="af-testType"><option value="Concrete" ${isEdit && item.testType === 'Concrete' ? 'selected' : ''}>Concrete</option><option value="Soil" ${isEdit && item.testType === 'Soil' ? 'selected' : ''}>Soil</option><option value="Steel" ${isEdit && item.testType === 'Steel' ? 'selected' : ''}>Steel</option><option value="Bitumen" ${isEdit && item.testType === 'Bitumen' ? 'selected' : ''}>Bitumen</option><option value="Brick" ${isEdit && item.testType === 'Brick' ? 'selected' : ''}>Brick</option><option value="Timber" ${isEdit && item.testType === 'Timber' ? 'selected' : ''}>Timber</option></select></div><div class="form-group"><label>${t('form_turnaround_days')}</label><input type="number" id="af-turnaround" value="${isEdit ? (item.turnaround || 3) : 3}" min="1"></div></div>${imgField(isEdit ? (item.img || '') : '')}`;
        } else if (entity === 'notices') {
            fields = `<div class="form-group"><label>${t('form_title_req')}</label><input type="text" id="af-title" required value="${escAttr(isEdit ? (item.title || '') : '')}"></div><div class="form-group"><label>${t('form_content_req')}</label><textarea id="af-content" rows="5" required>${escAttr(isEdit ? (item.content || '') : '')}</textarea></div><div class="form-row"><div class="form-group"><label>${t('form_date')}</label><input type="date" id="af-date" value="${isEdit ? (item.date || '') : new Date().toISOString().split('T')[0]}"></div><div class="form-group"><label>${t('form_type')}</label><select id="af-type"><option value="general" ${isEdit && item.type === 'general' ? 'selected' : ''}>General</option><option value="important" ${isEdit && item.type === 'important' ? 'selected' : ''}>Important</option><option value="new" ${isEdit && item.type === 'new' ? 'selected' : ''}>New</option></select></div></div><div class="form-group"><label>${t('form_category')}</label><select id="af-category"><option value="">Select</option><option value="Training" ${isEdit && item.category === 'Training' ? 'selected' : ''}>Training</option><option value="Holiday" ${isEdit && item.category === 'Holiday' ? 'selected' : ''}>Holiday</option><option value="Exam" ${isEdit && item.category === 'Exam' ? 'selected' : ''}>Exam</option><option value="Admission" ${isEdit && item.category === 'Admission' ? 'selected' : ''}>Admission</option></select></div>`;
        } else if (entity === 'officers') {
            fields = `<div class="form-row"><div class="form-group"><label>${t('form_full_name_req')}</label><input type="text" id="af-name" required value="${escAttr(isEdit ? (item.name || '') : '')}"></div><div class="form-group"><label>${t('form_designation_req')}</label><input type="text" id="af-designation" required value="${escAttr(isEdit ? (item.designation || '') : '')}"></div></div><div class="form-group"><label>${t('form_office')}</label><input type="text" id="af-office" value="${escAttr(isEdit ? (item.office || '') : '')}"></div><div class="form-row"><div class="form-group"><label>${t('form_email')}</label><input type="email" id="af-email" value="${escAttr(isEdit ? (item.email || '') : '')}"></div><div class="form-group"><label>${t('form_phone')}</label><input type="tel" id="af-phone" value="${escAttr(isEdit ? (item.phone || '') : '')}"></div></div><div class="form-row"><div class="form-group"><label>${t('form_mobile')}</label><input type="tel" id="af-mobile" value="${escAttr(isEdit ? (item.mobile || '') : '')}"></div><div class="form-group"><label>${t('form_display_order')}</label><input type="number" id="af-display_order" value="${isEdit ? (item.display_order || 0) : 0}" min="0"></div></div>${imgField(isEdit ? (item.img || '') : '')}`;
        } else if (entity === 'employees') {
            fields = `<div class="form-row"><div class="form-group"><label>${t('form_name_req')}</label><input type="text" id="af-name" required value="${escAttr(isEdit ? (item.name || '') : '')}"></div><div class="form-group"><label>${t('form_designation_req')}</label><input type="text" id="af-designation" required value="${escAttr(isEdit ? (item.designation || '') : '')}"></div></div><div class="form-group"><label>${t('form_department')}</label><select id="af-department"><option value="Civil Division" ${isEdit && item.department === 'Civil Division' ? 'selected' : ''}>Civil</option><option value="Architecture Division" ${isEdit && item.department === 'Architecture Division' ? 'selected' : ''}>Architecture</option><option value="Electrical & Mechanical" ${isEdit && item.department === 'Electrical & Mechanical' ? 'selected' : ''}>E/M</option><option value="Training Section" ${isEdit && item.department === 'Training Section' ? 'selected' : ''}>Training</option><option value="Administration" ${isEdit && item.department === 'Administration' ? 'selected' : ''}>Admin</option><option value="Testing Laboratory" ${isEdit && item.department === 'Testing Laboratory' ? 'selected' : ''}>Lab</option><option value="Other" ${isEdit && item.department === 'Other' ? 'selected' : ''}>Other</option></select></div><div class="form-row"><div class="form-group"><label>${t('form_email')}</label><input type="email" id="af-email" value="${escAttr(isEdit ? (item.email || '') : '')}"></div><div class="form-group"><label>${t('form_phone')}</label><input type="tel" id="af-phone" value="${escAttr(isEdit ? (item.phone || '') : '')}"></div></div><div class="form-row"><div class="form-group"><label>${t('form_join_date')}</label><input type="date" id="af-joinDate" value="${isEdit ? (item.joinDate || '') : ''}"></div><div class="form-group"><label>${t('form_active')}</label><select id="af-active"><option value="1" ${isEdit && item.active != 0 ? 'selected' : ''}>Yes</option><option value="0" ${isEdit && item.active === 0 ? 'selected' : ''}>No</option></select></div></div>${imgField(isEdit ? (item.img || '') : '')}`;
        } else if (entity === 'trainees') {
            fields = `<div class="form-row"><div class="form-group"><label>${t('form_name_req')}</label><input type="text" id="af-name" required value="${escAttr(isEdit ? (item.name || '') : '')}"></div><div class="form-group"><label>${t('form_email_req')}</label><input type="email" id="af-email" required value="${escAttr(isEdit ? (item.email || '') : '')}"></div></div><div class="form-row"><div class="form-group"><label>${t('form_phone')}</label><input type="tel" id="af-phone" value="${escAttr(isEdit ? (item.phone || '') : '')}"></div><div class="form-group"><label>${t('form_organization')}</label><input type="text" id="af-org" value="${escAttr(isEdit ? (item.org || '') : '')}"></div></div><div class="form-row"><div class="form-group"><label>${t('form_designation')}</label><input type="text" id="af-designation" value="${escAttr(isEdit ? (item.designation || '') : '')}"></div><div class="form-group"><label>${t('form_status')}</label><select id="af-status"><option value="enrolled" ${isEdit && item.status === 'enrolled' ? 'selected' : ''}>Enrolled</option><option value="completed" ${isEdit && item.status === 'completed' ? 'selected' : ''}>Completed</option><option value="dropped" ${isEdit && item.status === 'dropped' ? 'selected' : ''}>Dropped</option></select></div></div>`;
        } else if (entity === 'equipment') {
            fields = `<div class="form-group"><label>${t('form_name_req')}</label><input type="text" id="af-name" required value="${escAttr(isEdit ? (item.name || '') : '')}"></div><div class="form-group"><label>${t('form_description')}</label><textarea id="af-desc" rows="3">${escAttr(isEdit ? (item.desc || '') : '')}</textarea></div><div class="form-row"><div class="form-group"><label>${t('form_capacity')}</label><input type="text" id="af-capacity" value="${escAttr(isEdit ? (item.capacity || '') : '')}"></div><div class="form-group"><label>${t('form_standard')}</label><select id="af-standard"><option value="BDS" ${isEdit && item.standard === 'BDS' ? 'selected' : ''}>BDS</option><option value="ASTM" ${isEdit && item.standard === 'ASTM' ? 'selected' : ''}>ASTM</option><option value="BS" ${isEdit && item.standard === 'BS' ? 'selected' : ''}>BS</option><option value="IS" ${isEdit && item.standard === 'IS' ? 'selected' : ''}>IS</option></select></div></div>${imgField(isEdit ? (item.img || '') : '')}`;
        } else if (entity === 'gallery') {
            fields = `<div class="form-group"><label>${t('form_title')}</label><input type="text" id="af-title" value="${escAttr(isEdit ? (item.title || '') : '')}"></div><div class="form-row"><div class="form-group"><label>${t('form_category')}</label><select id="af-category"><option value="Event" ${isEdit && item.category === 'Event' ? 'selected' : ''}>Event</option><option value="Training" ${isEdit && item.category === 'Training' ? 'selected' : ''}>Training</option><option value="Campus" ${isEdit && item.category === 'Campus' ? 'selected' : ''}>Campus</option><option value="Lab" ${isEdit && item.category === 'Lab' ? 'selected' : ''}>Lab</option></select></div><div class="form-group"><label>${t('form_date')}</label><input type="date" id="af-date" value="${isEdit ? (item.date || '') : ''}"></div></div>${imgField(isEdit ? (item.img || '') : '')}`;
        } else if (entity === 'videos') {
            fields = `<div class="form-group"><label>${t('form_video_title_req')}</label><input type="text" id="af-title" required value="${escAttr(isEdit ? (item.title || '') : '')}"></div><div class="form-group"><label>${t('form_video_url_req')}</label><input type="url" id="af-url" required value="${escAttr(isEdit ? (item.url || '') : '')}" placeholder="https://youtube.com/watch?v=..."></div><div class="form-group"><label>${t('form_category')}</label><select id="af-category"><option value="Training" ${isEdit && item.category === 'Training' ? 'selected' : ''}>Training</option><option value="Event" ${isEdit && item.category === 'Event' ? 'selected' : ''}>Event</option><option value="Tutorial" ${isEdit && item.category === 'Tutorial' ? 'selected' : ''}>Tutorial</option></select></div>`;
        } else if (entity === 'facilities') {
            fields = `<div class="form-group"><label>${t('form_facility_type_req')}</label><select id="af-type" required><option value="">Select Type</option><option value="classroom" ${isEdit && item.type === 'classroom' ? 'selected' : ''}>Classroom</option><option value="computerlab" ${isEdit && item.type === 'computerlab' ? 'selected' : ''}>Computer Lab</option><option value="library" ${isEdit && item.type === 'library' ? 'selected' : ''}>Library</option><option value="residential" ${isEdit && item.type === 'residential' ? 'selected' : ''}>Residential</option><option value="playground" ${isEdit && item.type === 'playground' ? 'selected' : ''}>Playground</option><option value="gymnasium" ${isEdit && item.type === 'gymnasium' ? 'selected' : ''}>Gymnasium</option><option value="swimmingpool" ${isEdit && item.type === 'swimmingpool' ? 'selected' : ''}>Pool</option><option value="testinglab" ${isEdit && item.type === 'testinglab' ? 'selected' : ''}>Testing Lab</option></select></div><div class="form-group"><label>${t('form_title')}</label><input type="text" id="af-title" value="${escAttr(isEdit ? (item.title || '') : '')}"></div><div class="form-group"><label>${t('form_description')}</label><textarea id="af-desc" rows="4">${escAttr(isEdit ? (item.desc || '') : '')}</textarea></div><div class="form-row"><div class="form-group"><label>${t('form_capacity')}</label><input type="number" id="af-capacity" value="${isEdit ? (item.capacity || 0) : 0}" min="0"></div><div class="form-group"><label>${t('form_area_sqft')}</label><input type="number" id="af-area" value="${isEdit ? (item.area || 0) : 0}" min="0"></div></div><div class="form-group"><label>${t('form_features_hint')}</label><textarea id="af-features" rows="3">${escAttr(isEdit ? (item.features || '') : '')}</textarea></div>${imgField(isEdit ? (item.img || '') : '')}`;
        } else if (entity === 'sliders') {
            fields = `<div class="form-group"><label>${t('form_title')}</label><input type="text" id="af-title" value="${escAttr(isEdit ? (item.title || '') : '')}"></div><div class="form-group"><label>${t('form_subtitle')}</label><input type="text" id="af-subtitle" value="${escAttr(isEdit ? (item.subtitle || '') : '')}"></div><div class="form-row"><div class="form-group"><label>${t('form_button_text')}</label><input type="text" id="af-btnText" value="${escAttr(isEdit ? (item.btnText || '') : '')}"></div><div class="form-group"><label>${t('form_button_link')}</label><input type="text" id="af-btnLink" value="${escAttr(isEdit ? (item.btnLink || '') : '')}"></div></div><div class="form-row"><div class="form-group"><label>${t('form_order')}</label><input type="number" id="af-order" value="${isEdit ? (item.order || 0) : 0}" min="0"></div><div class="form-group"><label>${t('form_active')}</label><select id="af-active"><option value="1" ${isEdit && item.active != 0 ? 'selected' : ''}>Yes</option><option value="0" ${isEdit && item.active === 0 ? 'selected' : ''}>No</option></select></div></div>${imgField(isEdit ? (item.img || '') : '')}`;
        } else {
            fields = `<div class="form-group"><p style="color:var(--muted)">Form not available for this entity</p></div>`;
        }

        const submitId = numericId ? numericId : 0;
        openModal(`
        <div class="relative">
            <div class="h-2 rounded-t-xl" style="background:linear-gradient(90deg, var(--primary), var(--accent))"></div>
            <div class="p-5 border-b flex items-center justify-between" style="border-color:var(--border)">
                <div class="flex items-center gap-3">
                    <div class="w-9 h-9 rounded-lg flex items-center justify-center" style="background:var(--primary-glow)"><i class="fas ${entityIcons[entity] || 'fa-edit'} text-sm" style="color:var(--primary)"></i></div>
                    <h3 class="font-semibold">${escAttr(title)}</h3>
                </div>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer"><i class="fas fa-times"></i></button>
            </div>
        </div>
        <div class="p-5"><form onsubmit="submitAdminForm(event,'${entity}',${submitId})">${fields}<div class="flex gap-3 mt-6"><button type="submit" class="btn-primary flex-1"><i class="fas fa-${isEdit ? 'save' : 'plus'} mr-2"></i>${isEdit ? t('btn_update') : t('btn_save')}</button><button type="button" onclick="closeModal()" class="btn-outline flex-1">${t('admin_cancel')}</button></div></form></div>
    `);
    }

    // =============================================
    // ADMIN: View Program Enrollments
    // =============================================
    function viewProgramEnrollments(programId, type) {
        const item = type === 'training'
            ? trainings.find(t => t.id === programId)
            : testings.find(t => t.id === programId);
        if (!item) { showToast(t('err_program_not_found'), 'error'); return; }

        const enrolledList = getProgramEnrolledList(programId);
        const interestedList = getProgramInterestedList(programId);

        const profileCard = (entry, index, listType) => {
            const initial = (entry.name || 'U').charAt(0).toUpperCase();
            const colors = ['#059669', '#0d6efd', '#7c3aed', '#d97706', '#dc2626', '#0891b2'];
            const color = colors[index % colors.length];
            const borderColor = listType === 'enrolled' ? '#059669' : '#dc2626';
            const dateStr = entry.date ? new Date(entry.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : '-';
            const timeStr = entry.date ? new Date(entry.date).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : '';
            const safeEmail = escAttr(entry.email || '');
            const removeFn = listType === 'enrolled' ? 'removeProgramEnrollment' : 'removeProgramInterest';
            const statusBadge = listType === 'enrolled'
                ? `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[9px] font-bold bg-green-100 text-green-700"><i class="fas fa-user-check text-[8px]"></i>${t('status_enrolled')}</span>`
                : `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[9px] font-bold bg-red-100 text-red-600"><i class="far fa-heart text-[8px]"></i>${t('status_interested')}</span>`;

            return `<div class="flex items-start gap-3 p-3 rounded-xl border-l-4 transition-all hover:shadow-md cursor-pointer group" style="border-left-color:${borderColor}; background:var(--card); border-top:1px solid var(--border); border-right:1px solid var(--border); border-bottom:1px solid var(--border)" onclick="viewAdminTraineeDashboard('${safeEmail}')">
            <div class="w-11 h-11 rounded-full flex items-center justify-center shrink-0 text-sm font-bold text-white shadow-md" style="background:linear-gradient(135deg,${color},${color}cc)">${initial}</div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center justify-between gap-2 mb-1"><span class="font-semibold text-sm text-gray-800 truncate">${escAttr(entry.name || '-')}</span>${statusBadge}</div>
                ${entry.designation ? `<div class="text-xs text-gray-600 flex items-center gap-1.5 mb-0.5"><i class="fas fa-briefcase text-[9px] text-gray-400 w-3 text-center"></i><span class="truncate">${escAttr(entry.designation)}</span></div>` : ''}
                ${entry.org ? `<div class="text-xs text-gray-500 flex items-center gap-1.5 mb-1.5"><i class="fas fa-building text-[9px] text-gray-400 w-3 text-center"></i><span class="truncate">${escAttr(entry.org)}</span></div>` : ''}
                <div class="flex flex-wrap items-center gap-2 mt-1">
                    ${entry.email ? `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-medium text-blue-700 bg-blue-50"><i class="fas fa-envelope text-[8px]"></i><span class="truncate">${escAttr(entry.email)}</span></span>` : ''}
                    ${entry.phone ? `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-medium text-green-700 bg-green-50"><i class="fas fa-phone text-[8px]"></i>${escAttr(entry.phone)}</span>` : ''}
                </div>
            </div>
            <div class="flex flex-col items-end justify-between h-full shrink-0 py-1">
                <div class="text-[10px] text-gray-400 text-right leading-tight"><div>${dateStr}</div>${timeStr ? `<div class="text-[9px]">${timeStr}</div>` : ''}</div>
                <div class="flex gap-1.5 mt-2" onclick="event.stopPropagation()">
                    ${listType === 'interested' ? `<button class="btn-primary btn-sm" style="font-size:9px; padding:3px 6px;" onclick="moveInterestToEnrollment(${programId},'${safeEmail}');viewProgramEnrollments(${programId},'${type}')" title="${t('btn_move_to_enrolled')}"><i class="fas fa-user-plus"></i></button>` : ''}
                    <button class="btn-danger btn-sm" style="font-size:9px; padding:3px 6px;" onclick="if(confirm(t('confirm_remove_person'))){${removeFn}(${programId},'${safeEmail}');viewProgramEnrollments(${programId},'${type}')}" title="${t('btn_remove')}"><i class="fas fa-trash-alt"></i></button>
                </div>
            </div>
        </div>`;
        };

        const enrolledHTML = enrolledList.length > 0
            ? enrolledList.map((e, i) => profileCard(e, i, 'enrolled')).join('')
            : `<div class="text-center py-10"><div class="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center" style="background:#ecfdf5"><i class="fas fa-user-slash text-3xl text-green-300"></i></div><p class="text-sm font-medium text-gray-500">${t('no_enrolled_trainees')}</p></div>`;

        const interestedHTML = interestedList.length > 0
            ? interestedList.map((e, i) => profileCard(e, i, 'interested')).join('')
            : `<div class="text-center py-10"><div class="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center" style="background:#fef2f2"><i class="fas fa-heart text-3xl text-red-300"></i></div><p class="text-sm font-medium text-gray-500">${t('no_interested_trainees')}</p></div>`;

        openModal(`
        <div class="p-5 border-b" style="border-color:var(--border)">
            <div class="flex items-start justify-between">
                <div class="flex items-start gap-3">
                    <div class="w-11 h-11 rounded-lg flex items-center justify-center shrink-0" style="background:${type === 'training' ? 'var(--primary-glow)' : 'var(--accent-glow)'}"><i class="fas ${type === 'training' ? 'fa-chalkboard-teacher' : 'fa-flask'}" style="color:${type === 'training' ? 'var(--primary)' : 'var(--accent)'}"></i></div>
                    <div><h3 class="font-semibold text-base leading-tight">${escAttr(item.title)}</h3><div class="flex items-center gap-2 mt-1"><span class="badge ${type === 'training' ? 'badge-info' : 'badge-warning'}" style="font-size:9px">${type === 'training' ? t('type_training') : t('type_testing')}</span>${type === 'training' && item.status ? `<span class="badge ${item.status === 'ongoing' ? 'badge-success' : item.status === 'upcoming' ? 'badge-info' : 'badge-warning'}" style="font-size:9px">${escAttr(item.status)}</span>` : ''}</div></div>
                </div>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer shrink-0 ml-2"><i class="fas fa-times"></i></button>
            </div>
        </div>
        <div class="p-5">
            <div class="grid grid-cols-2 gap-3 mb-5">
                <div class="p-4 rounded-xl text-center cursor-pointer transition-all hover:scale-[1.02] active:scale-[0.98]" style="background:linear-gradient(135deg,#ecfdf5,#d1fae5);border:1.5px solid #6ee7b7" onclick="switchEnrollTab('enrolled')">
                    <div class="w-10 h-10 rounded-full mx-auto mb-2 flex items-center justify-center" style="background:#05966920"><i class="fas fa-user-check text-green-600"></i></div>
                    <div class="text-2xl font-bold text-green-700">${enrolledList.length}</div>
                    <div class="text-[10px] text-green-600 mt-0.5 font-semibold">${t('status_enrolled')}</div>
                </div>
                <div class="p-4 rounded-xl text-center cursor-pointer transition-all hover:scale-[1.02] active:scale-[0.98]" style="background:linear-gradient(135deg,#fef2f2,#fecaca);border:1.5px solid #fca5a5" onclick="switchEnrollTab('interested')">
                    <div class="w-10 h-10 rounded-full mx-auto mb-2 flex items-center justify-center" style="background:#dc262620"><i class="fas fa-heart text-red-500"></i></div>
                    <div class="text-2xl font-bold text-red-700">${interestedList.length}</div>
                    <div class="text-[10px] text-red-600 mt-0.5 font-semibold">${t('status_interested')}</div>
                </div>
            </div>
            <div class="mb-4 relative">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
                <input type="text" id="enroll-search-input" placeholder="${t('search_name_email')}" class="w-full pl-9 pr-4 py-2 rounded-lg border text-sm focus:ring-2 focus:ring-blue-400 focus:border-blue-400 transition" style="border-color:var(--border)" oninput="filterEnrollList(this.value)">
            </div>
            <div class="flex gap-1 mb-4" style="border-bottom:2px solid var(--border)">
                <button id="enroll-tab-btn-enrolled" class="tab-btn active" onclick="switchEnrollTab('enrolled',this)"><i class="fas fa-user-check mr-1 text-green-500"></i>${t('status_enrolled')} (${enrolledList.length})</button>
                <button id="enroll-tab-btn-interested" class="tab-btn" onclick="switchEnrollTab('interested',this)"><i class="fas fa-heart mr-1 text-red-400"></i>${t('status_interested')} (${interestedList.length})</button>
            </div>
            <div class="text-xs text-gray-400 mb-2 flex items-center gap-1"><i class="fas fa-mouse-pointer"></i> ${t('click_for_details')}</div>
            <div id="enroll-tab-enrolled" class="space-y-2 max-h-80 overflow-y-auto enroll-list-container">${enrolledHTML}</div>
            <div id="enroll-tab-interested" class="space-y-2 max-h-80 overflow-y-auto enroll-list-container" style="display:none">${interestedHTML}</div>
        </div>
    `);
    }

    function switchEnrollTab(tab, btn) {
        document.getElementById('enroll-tab-enrolled').style.display = tab === 'enrolled' ? '' : 'none';
        document.getElementById('enroll-tab-interested').style.display = tab === 'interested' ? '' : 'none';
        document.querySelectorAll('#enroll-tab-btn-enrolled, #enroll-tab-btn-interested').forEach(b => b.classList.remove('active'));
        if (btn) {
            btn.classList.add('active');
        } else {
            document.getElementById(`enroll-tab-btn-${tab}`)?.classList.add('active');
        }
    }

    function filterEnrollList(query) {
        const q = query.toLowerCase();
        document.querySelectorAll('.enroll-list-container > div').forEach(card => {
            card.style.display = card.textContent.toLowerCase().includes(q) ? '' : 'none';
        });
    }

    // =============================================
    // ADMIN: View Detailed Trainee Dashboard
    // =============================================
    function viewAdminTraineeDashboard(userEmail) {
        const safeEmail = escAttr(userEmail);

        let traineeData = null;
        const allEngagements = [];
        const tracking = getProgramTracking();

        Object.keys(tracking).forEach(pid => {
            const progId = parseInt(pid);
            const program = tracking[pid];
            const item = trainings.find(t => t.id === progId) || testings.find(t => t.id === progId);
            if (!item) return;
            const isTraining = !!trainings.find(t => t.id === progId);

            if (program.enrolled) {
                const entry = program.enrolled.find(e => e.email === userEmail);
                if (entry) {
                    if (!traineeData) traineeData = entry;
                    allEngagements.push({ ...entry, programId: progId, programTitle: item.title, programType: isTraining ? 'training' : 'testing', programStatus: item.status || '-', programStart: item.start || '-', engagementType: 'enrolled' });
                }
            }
            if (program.interested) {
                const entry = program.interested.find(e => e.email === userEmail);
                if (entry) {
                    if (!traineeData) traineeData = entry;
                    allEngagements.push({ ...entry, programId: progId, programTitle: item.title, programType: isTraining ? 'training' : 'testing', programStatus: item.status || '-', programStart: item.start || '-', engagementType: 'interested' });
                }
            }
        });

        if (!traineeData) { showToast(t('err_trainee_not_found'), 'error'); return; }

        const dbTrainee = trainees.find(t => t.email === userEmail);
        const initial = (traineeData.name || 'U').charAt(0).toUpperCase();
        const colors = ['#059669', '#0d6efd', '#7c3aed', '#d97706', '#dc2626', '#0891b2', '#be185d', '#15803d'];
        const color = colors[(traineeData.name || 'A').charCodeAt(0) % colors.length];

        const enrolledCount = allEngagements.filter(e => e.engagementType === 'enrolled').length;
        const interestedCount = allEngagements.filter(e => e.engagementType === 'interested').length;
        const activeCount = allEngagements.filter(e => e.engagementType === 'enrolled' && e.programStatus === 'ongoing').length;
        const completedCount = allEngagements.filter(e => e.engagementType === 'enrolled' && e.programStatus === 'completed').length;

        const notes = getTraineeNotes(userEmail);
        const notesHTML = notes.length > 0 ? notes.map(n => {
            const d = new Date(n.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
            return `<div class="flex items-start gap-2 p-2.5 rounded-lg group hover:bg-yellow-50 transition" style="border:1px solid var(--border); background:var(--bg)">
            <i class="fas fa-sticky-note text-yellow-500 mt-0.5 text-xs shrink-0"></i>
            <div class="flex-1 min-w-0"><p class="text-xs text-gray-700 leading-relaxed">${escAttr(n.text)}</p><div class="text-[9px] text-gray-400 mt-1">${d} • ${escAttr(n.admin)}</div></div>
            <button onclick="deleteTraineeNote('${safeEmail}', ${n.id})" class="text-red-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition text-[10px] cursor-pointer shrink-0"><i class="fas fa-times"></i></button>
        </div>`;
        }).join('') : `<p class="text-xs text-gray-400 text-center py-3">${t('no_notes_yet')}</p>`;

        const statusOrder = { ongoing: 1, upcoming: 2, completed: 3 };
        allEngagements.sort((a, b) => (statusOrder[a.programStatus] || 4) - (statusOrder[b.programStatus] || 4));

        const timelineHTML = allEngagements.map(prog => {
            const isEnrolled = prog.engagementType === 'enrolled';
            const lineColor = isEnrolled ? '#059669' : '#dc2626';
            const dotColor = isEnrolled ? 'bg-green-500' : 'bg-red-500';
            const statusBg = prog.programStatus === 'ongoing' ? 'bg-green-100 text-green-700' : prog.programStatus === 'upcoming' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600';
            const removeFn = isEnrolled ? 'removeProgramEnrollment' : 'removeProgramInterest';

            return `<div class="flex gap-4">
            <div class="flex flex-col items-center"><div class="w-3 h-3 rounded-full ${dotColor} border-2 border-white shadow-sm shrink-0 mt-1.5"></div><div class="w-0.5 flex-1 mt-1" style="background:${lineColor}30"></div></div>
            <div class="flex-1 mb-4 p-3 rounded-lg border transition-all hover:shadow-sm" style="border-color:var(--border); background:var(--card)">
                <div class="flex items-center justify-between gap-2 mb-1.5"><h4 class="text-sm font-semibold text-gray-800 truncate">${escAttr(prog.programTitle)}</h4><span class="px-2 py-0.5 rounded-full text-[9px] font-bold ${statusBg}">${escAttr(prog.programStatus)}</span></div>
                <div class="flex items-center gap-3 text-[10px] text-gray-500 mb-2">
                    <span class="badge ${prog.programType === 'training' ? 'badge-info' : 'badge-warning'}" style="font-size:8px; padding:2px 6px">${prog.programType === 'training' ? t('type_training') : t('type_testing')}</span>
                    <span><i class="far fa-calendar-alt mr-1"></i>${escAttr(prog.programStart)}</span>
                </div>
                <div class="flex items-center justify-between pt-2 border-t" style="border-color:var(--border)">
                    <span class="inline-flex items-center gap-1 text-[10px] font-semibold ${isEnrolled ? 'text-green-600' : 'text-red-500'}"><i class="${isEnrolled ? 'fas fa-user-check' : 'far fa-heart'} text-[9px]"></i> ${isEnrolled ? t('status_enrolled') : t('status_interested')}</span>
                    <div class="flex gap-1.5" onclick="event.stopPropagation()">
                        ${!isEnrolled ? `<button class="btn-primary btn-sm" style="font-size:9px; padding:2px 6px;" onclick="moveInterestToEnrollment(${prog.programId},'${safeEmail}');viewAdminTraineeDashboard('${safeEmail}')"><i class="fas fa-user-plus mr-1"></i>${t('btn_enroll')}</button>` : ''}
                        <button class="btn-danger btn-sm" style="font-size:9px; padding:2px 6px;" onclick="if(confirm(t('confirm_remove'))){${removeFn}(${prog.programId},'${safeEmail}');viewAdminTraineeDashboard('${safeEmail}')}"><i class="fas fa-trash-alt"></i></button>
                    </div>
                </div>
            </div>
        </div>`;
        }).join('');

        openModal(`
        <div class="relative">
            <div class="h-28 rounded-t-xl relative overflow-hidden" style="background: linear-gradient(135deg, ${color}, ${color}99)">
                <div class="absolute inset-0 opacity-10" style="background-image: radial-gradient(circle at 20% 50%, white 1px, transparent 1px), radial-gradient(circle at 80% 20%, white 1px, transparent 1px); background-size: 20px 20px"></div>
                <button onclick="closeModal()" class="absolute top-3 right-3 w-8 h-8 rounded-full bg-white/20 backdrop-blur-sm text-white flex items-center justify-center hover:bg-white/40 transition cursor-pointer"><i class="fas fa-times text-sm"></i></button>
            </div>
            <div class="px-5 pb-4 border-b relative" style="border-color:var(--border)">
                <div class="flex flex-col sm:flex-row items-center sm:items-end gap-4 -mt-10">
                    <div class="relative"><div class="w-20 h-20 rounded-xl flex items-center justify-center text-2xl font-bold text-white shadow-lg border-4 border-white" style="background:linear-gradient(135deg,${color},${color}cc)">${initial}</div><div class="absolute -bottom-1 -right-1 w-5 h-5 bg-green-500 rounded-full border-2 border-white flex items-center justify-center"><i class="fas fa-check text-white text-[7px]"></i></div></div>
                    <div class="flex-1 text-center sm:text-left mb-1"><h2 class="text-lg font-bold text-gray-800">${escAttr(traineeData.name || '-')}</h2><div class="flex flex-wrap justify-center sm:justify-start items-center gap-x-3 gap-y-1 text-xs text-gray-500 mt-1">${traineeData.designation ? `<span class="flex items-center gap-1"><i class="fas fa-briefcase text-[10px]"></i>${escAttr(traineeData.designation)}</span>` : ''}${traineeData.org ? `<span class="flex items-center gap-1"><i class="fas fa-building text-[10px]"></i>${escAttr(traineeData.org)}</span>` : ''}</div></div>
                    <div class="flex gap-2 mb-1">
                        ${traineeData.email ? `<a href="mailto:${safeEmail}" class="w-8 h-8 rounded-lg flex items-center justify-center bg-blue-100 text-blue-600 hover:bg-blue-200 transition" title="Email"><i class="fas fa-envelope text-xs"></i></a>` : ''}
                        ${traineeData.phone ? `<a href="tel:${escAttr(traineeData.phone)}" class="w-8 h-8 rounded-lg flex items-center justify-center bg-green-100 text-green-600 hover:bg-green-200 transition" title="Call"><i class="fas fa-phone text-xs"></i></a>` : ''}
                        ${dbTrainee ? `<button onclick="closeModal();setTimeout(()=>openAdminForm('trainees',${dbTrainee.id}),300)" class="w-8 h-8 rounded-lg flex items-center justify-center bg-purple-100 text-purple-600 hover:bg-purple-200 transition" title="${t('btn_edit')}"><i class="fas fa-user-edit text-xs"></i></button>` : ''}
                    </div>
                </div>
            </div>
        </div>
        <div class="p-5 space-y-6 max-h-[70vh] overflow-y-auto">
            <div class="grid grid-cols-4 gap-3">
                <div class="p-3 rounded-xl text-center shadow-sm border border-green-100" style="background:#f0fdf4"><div class="text-xl font-bold text-green-700">${enrolledCount}</div><div class="text-[9px] font-semibold text-green-600 mt-0.5">${t('status_enrolled')}</div></div>
                <div class="p-3 rounded-xl text-center shadow-sm border border-red-100" style="background:#fef2f2"><div class="text-xl font-bold text-red-700">${interestedCount}</div><div class="text-[9px] font-semibold text-red-500 mt-0.5">${t('status_interested')}</div></div>
                <div class="p-3 rounded-xl text-center shadow-sm border border-blue-100" style="background:#eff6ff"><div class="text-xl font-bold text-blue-700">${activeCount}</div><div class="text-[9px] font-semibold text-blue-600 mt-0.5">${t('status_active')}</div></div>
                <div class="p-3 rounded-xl text-center shadow-sm border border-gray-100" style="background:#f9fafb"><div class="text-xl font-bold text-gray-700">${completedCount}</div><div class="text-[9px] font-semibold text-gray-500 mt-0.5">${t('status_done')}</div></div>
            </div>
            <div>
                <h4 class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2"><i class="fas fa-sticky-note text-yellow-500"></i> ${t('admin_notes')}</h4>
                <div class="mb-3 flex gap-2"><input type="text" id="admin-note-input" placeholder="${t('ph_new_note')}" class="flex-1 px-3 py-2 rounded-lg border text-xs focus:ring-1 focus:ring-blue-400 focus:border-blue-400 transition" style="border-color:var(--border)" onkeydown="if(event.key==='Enter')addTraineeNote('${safeEmail}')"><button onclick="addTraineeNote('${safeEmail}')" class="btn-primary btn-sm" style="font-size:11px"><i class="fas fa-plus mr-1"></i>${t('btn_add')}</button></div>
                <div class="space-y-2 max-h-32 overflow-y-auto">${notesHTML}</div>
            </div>
            <div>
                <h4 class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2"><i class="fas fa-stream text-indigo-500"></i> ${t('program_timeline')}</h4>
                ${allEngagements.length > 0 ? `<div>${timelineHTML}</div>` : `<div class="text-center py-6"><i class="fas fa-stream text-3xl text-gray-200 mb-2"></i><p class="text-xs text-gray-400">${t('no_engagements')}</p></div>`}
            </div>
        </div>
    `);
    }

    // =============================================
    // ADMIN: Submit Form
    // =============================================
    // =============================================
    // ADMIN: Submit Form (FIXED)
    // =============================================
    async function submitAdminForm(e, entity, id) {
        e.preventDefault();
        const editId = (id && id !== 0) ? parseInt(id) : null;
        const formData = new FormData();

        // ===== ফাইল ইনপুট খুঁজুন =====
        const fileInput = e.target.querySelector('#af-img-file');
        const hasNewFile = fileInput && fileInput.files && fileInput.files.length > 0;

        if (hasNewFile) {
            formData.append('img', fileInput.files[0]);
            console.log('📎 File attached:', fileInput.files[0].name,
                '(' + (fileInput.files[0].size / 1024).toFixed(1) + ' KB)');
        } else {
            const hiddenImg = document.getElementById('af-img');
            if (hiddenImg && hiddenImg.value && hiddenImg.value.startsWith('data:')) {
                formData.append('img', hiddenImg.value);
                console.log('📎 Base64 image attached');
            } else {
                console.log('📎 No new image selected');
            }
        }

        // ===== সব ফর্ম ফিল্ড যোগ করুন =====
        e.target.querySelectorAll('input, textarea, select').forEach(input => {
            if (input.id && input.id.startsWith('af-') && input.type !== 'file' && input.id !== 'af-img') {
                const key = input.id.replace('af-', '');
                formData.append(key, input.value);
            }
        });

        if (editId) formData.append('id', editId);

        // ===== ডিবাগ: FormData কনটেন্ট লগ =====
        console.log('📤 Submitting form for:', entity, '| Edit ID:', editId);
        for (let [key, value] of formData.entries()) {
            if (value instanceof File) {
                console.log(`  ${key}: [File] ${value.name} (${value.size} bytes)`);
            } else {
                console.log(`  ${key}: ${value.substring(0, 80)}${value.length > 80 ? '...' : ''}`);
            }
        }

        const submitBtn = e.target.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = `<i class="fas fa-spinner fa-spin mr-2"></i>${t('saving')}`;
        }

        try {
            const res = await fetch(`${API}?entity=${entity}`, { method: 'POST', body: formData });

            if (!res.ok) {
                throw new Error(`HTTP ${res.status}: ${res.statusText}`);
            }

            const result = await res.json();
            console.log('📥 Server response:', result);

            if (result.success !== false && !result.error) {
                showToast(editId ? t('admin_updated') : t('admin_created'), 'success');
                closeModal();
                await refreshEntity(entity);
                renderAdminPage();

                if (entity === 'notices') {
                    try { updateTicker(); } catch (e) { }
                }
            } else {
                // সার্ভার থেকে আসা এরর মেসেজ দেখান
                const errMsg = result.error || t('admin_operation_failed');
                showToast(errMsg, 'error');
                console.error('❌ Server error:', errMsg);
            }
        } catch (err) {
            console.error('❌ Submit error:', err);
            showToast(t('admin_operation_failed') + ': ' + err.message, 'error');
        } finally {
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = `<i class="fas fa-${editId ? 'save' : 'plus'} mr-2"></i>${editId ? t('btn_update') : t('btn_save')}`;
            }
        }
    }

    // =============================================
    // ADMIN: Delete Record (FIXED)
    // =============================================
    async function adminDelete(entity, id) {
        if (!confirm(t('confirm_delete'))) return;
        try {
            const res = await api(entity, 'DELETE', { id });
            if (res.success !== false && !res.error) {
                showToast(t('admin_deleted'), 'success');
                logAdminActivity('delete', `${entity} #${id}`);
                await refreshEntity(entity);
                renderAdminPage();

                if (entity === 'notices') {
                    try { updateTicker(); } catch (e) { console.warn('Ticker update skipped:', e); }
                }
            } else {
                showToast(res.error || t('admin_operation_failed'), 'error');
            }
        } catch (err) {
            console.error('Admin delete error:', err);
            showToast(t('admin_operation_failed'), 'error');
        }
    }

    // =======================
    // ADMIN: Image Preview
    // =============================================
    function previewAdminImage(input) {
        const file = input.files[0];
        if (!file) return;
        if (!file.type.startsWith('image/')) { showToast(t('err_image_file'), 'error'); input.value = ''; return; }
        if (file.size > 5 * 1024 * 1024) { showToast(t('err_image_size'), 'error'); input.value = ''; return; }
        const reader = new FileReader();
        reader.onload = function (e) {
            const base64 = e.target.result;
            const previewBox = document.getElementById('img-preview-box');
            const previewTag = document.getElementById('img-preview-tag');
            const hiddenInput = document.getElementById('af-img');
            const placeholder = document.getElementById('img-placeholder');
            if (previewBox && previewTag && hiddenInput) {
                previewBox.classList.remove('bg-gray-50');
                previewTag.src = base64;
                previewTag.classList.remove('hidden');
                if (placeholder) placeholder.classList.add('hidden');
                hiddenInput.value = base64;
            }
        };
        reader.readAsDataURL(file);
    }

    // =============================================
    // ADMIN: Export Reports
    // =============================================
    function exportEnrollmentReport() {
        const allPrograms = [...trainings.map(tr => ({ ...tr, type: 'training' })), ...testings.map(ts => ({ ...ts, type: 'testing' }))];
        let csv = `${t('col_program')},${t('col_type')},${t('col_status')},${t('col_enrolled')},${t('col_interested')}\n`;
        allPrograms.forEach(p => {
            const s = getProgramStats(p.id);
            csv += `"${p.title}",${p.type},${p.status || '-'},${s.enrolledCount},${s.interestedCount}\n`;
        });
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `enrollment_report_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();
        URL.revokeObjectURL(link.href);
        showToast(t('toast_report_downloading'), 'success');
    }

    function exportFullReport() {
        let csv = '';

        csv += `\n--- ${t('report_trainings_header')} ---\n`;
        csv += 'Title,Category,Status,Start,End,Enrolled,Interested\n';
        trainings.forEach(t => { const s = getProgramStats(t.id); csv += `"${t.title}",${t.category || ''},${t.status || ''},${t.start || ''},${t.end || ''},${s.enrolledCount},${s.interestedCount}\n`; });

        csv += `\n--- ${t('report_trainees_header')} ---\n`;
        csv += 'Name,Email,Phone,Organization,Designation\n';
        trainees.forEach(t => { csv += `"${t.name || ''}","${t.email || ''}","${t.phone || ''}","${t.org || t.organization || ''}","${t.designation || ''}"\n`; });

        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `full_report_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();
        URL.revokeObjectURL(link.href);
        showToast(t('toast_full_report_downloading'), 'success');
    }

    // =============================================
    // ADMIN: Enhanced Settings Page
    // =============================================
    function adminSettings() {
        return `<div class="max-w-3xl space-y-6">
        <div class="admin-card">
            <h3 class="font-semibold mb-5 flex items-center gap-2"><i class="fas fa-school text-blue-500"></i> ${t('settings_academy_info')}</h3>
            <form onsubmit="saveSettings(event)" class="space-y-5">
                <div class="form-group"><label>${t('form_academy_name')}</label><input type="text" id="set-name" value="PWD Training Academy"></div>
                <div class="form-group"><label>${t('form_address')}</label><input type="text" id="set-address" value="Sher-e-Bangla Nagar, Dhaka"></div>
                <div class="form-row"><div class="form-group"><label>${t('form_phone')}</label><input type="tel" id="set-phone" value="+880-2-8181234"></div><div class="form-group"><label>${t('form_email')}</label><input type="email" id="set-email" value="info@pwd.training.gov.bd"></div></div>
                <button type="submit" class="btn-primary"><i class="fas fa-save mr-2"></i>${t('btn_save_settings')}</button>
            </form>
        </div>
        <div class="admin-card">
            <h3 class="font-semibold mb-5 flex items-center gap-2"><i class="fas fa-palette text-purple-500"></i> ${t('settings_customization')}</h3>
            <div class="space-y-4">
                <div class="flex items-center justify-between p-4 rounded-lg" style="border:1px solid var(--border)">
                    <div><div class="text-sm font-medium">${t('settings_dark_mode')}</div><div class="text-xs text-gray-400">${t('settings_toggle_theme_desc')}</div></div>
                    <button class="btn-outline btn-sm" onclick="toggleTheme()"><i class="fas fa-moon mr-1"></i>${t('btn_toggle')}</button>
                </div>
                <div class="flex items-center justify-between p-4 rounded-lg" style="border:1px solid var(--border)">
                    <div><div class="text-sm font-medium">${t('settings_language')}</div><div class="text-xs text-gray-400">${t('settings_switch_lang_desc')}</div></div>
                    <button class="btn-outline btn-sm" onclick="toggleLanguage()"><i class="fas fa-language mr-1"></i>${currentLang === 'bn' ? 'English' : 'বাংলা'}</button>
                </div>
            </div>
        </div>
        <div class="admin-card">
            <h3 class="font-semibold mb-5 flex items-center gap-2"><i class="fas fa-database text-orange-500"></i> ${t('settings_system')}</h3>
            <div class="space-y-3">
                <div class="flex items-center justify-between p-4 rounded-lg" style="border:1px solid var(--border)">
                    <div><div class="text-sm font-medium">${t('settings_clear_data')}</div><div class="text-xs text-gray-400">${t('settings_clear_data_desc')}</div></div>
                    <button class="btn-danger btn-sm" onclick="if(confirm(t('confirm_clear_data'))){localStorage.removeItem('pwdta_program_tracking');showToast(t('toast_data_cleared'),'success');renderAdminPage()}"><i class="fas fa-trash mr-1"></i>${t('btn_clear')}</button>
                </div>
                <div class="p-4 rounded-lg" style="border:1px solid var(--border)">
                    <div class="text-sm font-medium mb-2">${t('settings_data_summary')}</div>
                    <div class="grid grid-cols-3 gap-2 text-xs text-gray-500">
                        <div class="p-2 rounded text-center" style="background:var(--bg)"><div class="text-lg font-bold" style="color:var(--primary)">${trainings.length}</div>${t('admin_trainings')}</div>
                        <div class="p-2 rounded text-center" style="background:var(--bg)"><div class="text-lg font-bold" style="color:var(--accent)">${trainees.length}</div>${t('admin_trainees')}</div>
                        <div class="p-2 rounded text-center" style="background:var(--bg)"><div class="text-lg font-bold text-green-600">${Object.keys(getProgramTracking()).length}</div>${t('settings_tracked')}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>`;
    }

    async function saveSettings(e) {
        e.preventDefault();
        try {
            const formData = new FormData();
            formData.append('site_name', document.getElementById('set-name')?.value || '');
            formData.append('address', document.getElementById('set-address')?.value || '');
            formData.append('phone', document.getElementById('set-phone')?.value || '');
            formData.append('email', document.getElementById('set-email')?.value || '');
            const res = await fetch(`${API}?entity=settings`, { method: 'POST', body: formData });
            const result = await res.json();
            showToast(t('toast_settings_saved'), 'success');
        } catch (err) {
            showToast(t('toast_settings_saved'), 'success');
        }
    }

    // =============================================
    // ADMIN: Enhanced Reports Page
    // =============================================
    function adminReports() {
        let totalEnrolled = 0, totalInterested = 0;
        const allPrograms = [...trainings.map(tr => ({ ...tr, type: 'training' })), ...testings.map(ts => ({ ...ts, type: 'testing' }))];
        allPrograms.forEach(p => { const s = getProgramStats(p.id); totalEnrolled += s.enrolledCount; totalInterested += s.interestedCount; });

        const categoryBreakdown = {};
        trainings.forEach(tr => {
            const cat = tr.category || 'Other';
            if (!categoryBreakdown[cat]) categoryBreakdown[cat] = { enrolled: 0, interested: 0, count: 0 };
            categoryBreakdown[cat].count++;
            const s = getProgramStats(tr.id);
            categoryBreakdown[cat].enrolled += s.enrolledCount;
            categoryBreakdown[cat].interested += s.interestedCount;
        });

        const categoryHTML = Object.entries(categoryBreakdown).map(([cat, data]) => {
            const total = data.enrolled + data.interested;
            const enrolledPct = total > 0 ? Math.round((data.enrolled / total) * 100) : 0;
            return `<div class="flex items-center gap-3 p-3 rounded-lg" style="border:1px solid var(--border)">
            <div class="flex-1"><div class="text-sm font-medium">${escAttr(cat)}</div><div class="text-xs text-gray-400">${data.count} ${t('rep_programs_count')}</div></div>
            <div class="flex items-center gap-3 text-xs">
                <span class="text-green-600 font-bold">${data.enrolled} ${t('status_enrolled')}</span>
                <span class="text-red-500 font-bold">${data.interested} ${t('status_interested')}</span>
            </div>
            <div class="w-24 h-2 rounded-full overflow-hidden" style="background:#f1f5f9"><div class="h-full rounded-full" style="width:${enrolledPct}%;background:#059669"></div></div>
        </div>`;
        }).join('');

        const testingBreakdown = {};
        testings.forEach(ts => {
            const ttype = ts.testType || 'Other';
            if (!testingBreakdown[ttype]) testingBreakdown[ttype] = { enrolled: 0, interested: 0, count: 0 };
            testingBreakdown[ttype].count++;
            const s = getProgramStats(ts.id);
            testingBreakdown[ttype].enrolled += s.enrolledCount;
            testingBreakdown[ttype].interested += s.interestedCount;
        });

        const testingHTML = Object.entries(testingBreakdown).map(([ttype, data]) => {
            return `<div class="flex items-center gap-3 p-3 rounded-lg" style="border:1px solid var(--border)">
            <div class="flex-1"><div class="text-sm font-medium">${escAttr(ttype)}</div><div class="text-xs text-gray-400">${data.count} ${t('rep_services_count')}</div></div>
            <div class="flex items-center gap-3 text-xs">
                <span class="text-green-600 font-bold">${data.enrolled}</span>
                <span class="text-red-500 font-bold">${data.interested}</span>
            </div>
        </div>`;
        }).join('');

        const topPrograms = [...allPrograms].map(p => ({ ...p, stats: getProgramStats(p.id) })).sort((a, b) => (b.stats.enrolledCount + b.stats.interestedCount) - (a.stats.enrolledCount + a.stats.interestedCount)).slice(0, 5);
        const topProgramsHTML = topPrograms.map((p, i) => {
            const total = p.stats.enrolledCount + p.stats.interestedCount;
            return `<div class="flex items-center gap-3 p-3 rounded-lg" style="border:1px solid var(--border)">
            <div class="w-8 h-8 rounded-lg flex items-center justify-center font-bold text-sm text-white" style="background:${i < 3 ? ['#d97706', '#94a3b8', '#b45309'][i] : '#6b7280'}">${i + 1}</div>
            <div class="flex-1 min-w-0"><div class="text-sm font-medium truncate">${escAttr(p.title)}</div><div class="text-[10px] text-gray-400">${p.type === 'training' ? t('type_training') : t('type_testing')}</div></div>
            <div class="text-right"><div class="text-sm font-bold" style="color:var(--primary)">${total}</div><div class="text-[9px] text-gray-400">${t('rep_total')}</div></div>
        </div>`;
        }).join('');

        return `<div class="space-y-6">
        <div class="grid grid-cols-2 lg:grid-cols-5 gap-4">
            <div class="stat-card"><div class="text-xs text-gray-500">${t('rep_total_programs')}</div><div class="text-2xl font-bold" style="color:var(--primary)">${allPrograms.length}</div></div>
            <div class="stat-card"><div class="text-xs text-gray-500">${t('admin_trainings')}</div><div class="text-2xl font-bold text-blue-700">${trainings.length}</div></div>
            <div class="stat-card"><div class="text-xs text-gray-500">${t('admin_testings')}</div><div class="text-2xl font-bold" style="color:var(--accent)">${testings.length}</div></div>
            <div class="stat-card"><div class="text-xs text-gray-500">${t('dash_total_enrolled')}</div><div class="text-2xl font-bold text-green-700">${totalEnrolled}</div></div>
            <div class="stat-card"><div class="text-xs text-gray-500">${t('dash_total_interested')}</div><div class="text-2xl font-bold text-red-700">${totalInterested}</div></div>
        </div>

        <div class="grid lg:grid-cols-2 gap-6">
            <div class="admin-card">
                <h3 class="font-semibold mb-4 text-sm flex items-center gap-2"><i class="fas fa-chalkboard-teacher text-blue-500"></i> ${t('rep_training_by_category')}</h3>
                <div class="space-y-2">${categoryHTML || `<p class="text-xs text-gray-400">${t('rep_no_data')}</p>`}</div>
            </div>
            <div class="admin-card">
                <h3 class="font-semibold mb-4 text-sm flex items-center gap-2"><i class="fas fa-flask text-orange-500"></i> ${t('rep_testing_by_type')}</h3>
                <div class="space-y-2">${testingHTML || `<p class="text-xs text-gray-400">${t('rep_no_data')}</p>`}</div>
            </div>
        </div>

        <div class="admin-card">
            <h3 class="font-semibold mb-4 text-sm flex items-center gap-2"><i class="fas fa-trophy text-yellow-500"></i> ${t('rep_top_programs')}</h3>
            <div class="space-y-2">${topProgramsHTML || `<p class="text-xs text-gray-400">${t('rep_no_data')}</p>`}</div>
        </div>

        <div class="admin-card">
            <h3 class="font-semibold mb-4 text-sm flex items-center gap-2"><i class="fas fa-file-export text-green-500"></i> ${t('rep_export_reports')}</h3>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                <button class="p-4 rounded-lg text-center hover:shadow-md transition cursor-pointer" style="border:1px solid var(--border)" onclick="exportEnrollmentReport()">
                    <div class="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center bg-green-100"><i class="fas fa-file-csv text-green-600"></i></div>
                    <div class="text-xs font-medium">${t('rep_enrollment_csv')}</div>
                </button>
                <button class="p-4 rounded-lg text-center hover:shadow-md transition cursor-pointer" style="border:1px solid var(--border)" onclick="exportFullReport()">
                    <div class="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center bg-blue-100"><i class="fas fa-file-alt text-blue-600"></i></div>
                    <div class="text-xs font-medium">${t('rep_full_report')}</div>
                </button>
                <button class="p-4 rounded-lg text-center hover:shadow-md transition cursor-pointer" style="border:1px solid var(--border)" onclick="exportEntityCSV('trainees')">
                    <div class="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center bg-purple-100"><i class="fas fa-users text-purple-600"></i></div>
                    <div class="text-xs font-medium">${t('rep_trainees_csv')}</div>
                </button>
                <button class="p-4 rounded-lg text-center hover:shadow-md transition cursor-pointer" style="border:1px solid var(--border)" onclick="exportEntityCSV('trainings')">
                    <div class="w-10 h-10 rounded-lg mx-auto mb-2 flex items-center justify-center bg-orange-100"><i class="fas fa-chalkboard-teacher text-orange-600"></i></div>
                    <div class="text-xs font-medium">${t('rep_trainings_csv')}</div>
                </button>
            </div>
        </div>
    </div>`;
    }
    // =============================================
    // NOTICE TICKER SYSTEM (Must Have)
    // =============================================
    function updateTicker() {
        const ticker = document.getElementById('notice-ticker');
        const tickerWrap = document.getElementById('notice-ticker-wrap');
        if (!ticker || !tickerWrap) return;

        if (!notices || notices.length === 0) {
            ticker.style.display = 'none';
            return;
        }

        ticker.style.display = '';

        const importantNotices = notices.filter(n => n.type === 'important');
        const displayNotices = importantNotices.length > 0 ? importantNotices : notices;

        const itemsHTML = displayNotices.map(n =>
            `<span class="inline-flex items-center gap-2 mx-8 whitespace-nowrap">
            ${n.type === 'important' ? '<i class="fas fa-exclamation-triangle text-red-400 text-xs"></i>' : '<i class="fas fa-bell text-blue-400 text-xs"></i>'}
            <strong>${escAttr(n.title)}</strong>
            ${n.content ? `<span class="text-gray-300">— ${escAttr(n.content.substring(0, 80))}${n.content.length > 80 ? '...' : ''}</span>` : ''}
            <span class="text-gray-500 text-xs ml-2">(${n.date || ''})</span>
        </span>`
        ).join('');

        // ✅ tickerWrap এ লিখুন, ticker এ নয়
        // ✅ ডুপ্লিকেট করুন seamless scroll এর জন্য
        tickerWrap.innerHTML = itemsHTML + itemsHTML;
    }
    // =============================================
    // REFRESH ENTITY DATA (Must Have)
    // =============================================
    async function refreshEntity(entity) {
        try {
            const res = await api(entity);
            const data = Array.isArray(res) ? res : (res.data || []);

            // Update global variables
            if (entity === 'trainings') trainings = data;
            else if (entity === 'testings') testings = data;
            else if (entity === 'notices') notices = data;
            else if (entity === 'officers') officers = data;
            else if (entity === 'employees') employees = data;
            else if (entity === 'trainees') trainees = data;
            else if (entity === 'equipment') equipment = data;
            else if (entity === 'gallery') galleryItems = data;
            else if (entity === 'videos') videoItems = data;
            else if (entity === 'facilities') facilities = data;
            else if (entity === 'sliders') sliders = data;
        } catch (err) {
            console.error(`Refresh ${entity} failed:`, err);
        }
    }

    // =============================================
    // API HELPER (Check if exists, if not add)
    // =============================================
    async function api(endpoint, method = 'GET', body = null) {
        const opts = { method, headers: {} };
        if (body && method !== 'GET') {
            if (body instanceof FormData) {
                opts.body = body;
            } else {
                opts.headers['Content-Type'] = 'application/json';
                opts.body = JSON.stringify(body);
            }
        }
        const res = await fetch(`${API}?entity=${endpoint}`, opts);
        return await res.json();
    }

    // =============================================
    // GET PROGRAM STATS (Check if exists)
    // =============================================
    function getProgramStats(programId) {
        const tracking = getProgramTracking();
        const prog = tracking[programId] || {};
        const enrolled = prog.enrolled || [];
        const interested = prog.interested || [];
        return {
            enrolledCount: enrolled.length,
            interestedCount: interested.length,
            enrolled,
            interested
        };
    }

    // =============================================
    // GET PROGRAM TRACKING (Check if exists)
    // =============================================
    function getProgramTracking() {
        const data = localStorage.getItem('pwdta_program_tracking');
        return data ? JSON.parse(data) : {};
    }

    // =============================================
    // PROGRAM ENROLLMENT HELPERS (Check if exists)
    // =============================================
    function getProgramEnrolledList(programId) {
        const tracking = getProgramTracking();
        return tracking[programId]?.enrolled || [];
    }

    function getProgramInterestedList(programId) {
        const tracking = getProgramTracking();
        return tracking[programId]?.interested || [];
    }

    function removeProgramEnrollment(programId, email) {
        const tracking = getProgramTracking();
        if (tracking[programId]?.enrolled) {
            tracking[programId].enrolled = tracking[programId].enrolled.filter(e => e.email !== email);
            localStorage.setItem('pwdta_program_tracking', JSON.stringify(tracking));
        }
    }

    function removeProgramInterest(programId, email) {
        const tracking = getProgramTracking();
        if (tracking[programId]?.interested) {
            tracking[programId].interested = tracking[programId].interested.filter(e => e.email !== email);
            localStorage.setItem('pwdta_program_tracking', JSON.stringify(tracking));
        }
    }

    function moveInterestToEnrollment(programId, email) {
        const tracking = getProgramTracking();
        if (!tracking[programId]) return;
        const idx = tracking[programId].interested?.findIndex(e => e.email === email);
        if (idx > -1) {
            const [entry] = tracking[programId].interested.splice(idx, 1);
            if (!tracking[programId].enrolled) tracking[programId].enrolled = [];
            tracking[programId].enrolled.push(entry);
            localStorage.setItem('pwdta_program_tracking', JSON.stringify(tracking));
            showToast(t('status_enrolled') + '!', 'success');
        }
    }