<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Faculty Profile Admin</title>
    <script src="https://cdn.tailwindcss.com/3.4.17"></script>
</head>
<body class="bg-gray-100 p-6">
    <div class="max-w-6xl mx-auto bg-white p-6 rounded-lg shadow">
        <div class="flex items-center justify-between mb-6">
            <h1 class="text-2xl font-bold">Faculty Profiles</h1>
            <button id="add-new" type="button" class="bg-green-500 text-white px-4 py-2 rounded">Add New</button>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
            <aside class="lg:col-span-1">
                <h2 class="font-semibold mb-3">Faculty List</h2>
                <div id="faculty-list" class="space-y-2"></div>
            </aside>

            <section class="lg:col-span-3">
                <h2 id="form-title" class="text-xl font-semibold mb-4">Add Faculty</h2>
                <form id="faculty-form" action="save.php" method="post">
                    <input type="hidden" name="index" id="faculty-index" value="-1">

                    <div class="mb-4">
                        <label class="block text-sm font-medium">Name</label>
                        <input type="text" name="name" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Initials</label>
                        <input type="text" name="initials" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Designation</label>
                        <input type="text" name="designation" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Institution</label>
                        <input type="text" name="institution" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Phone</label>
                        <input type="text" name="phone" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Email</label>
                        <input type="email" name="email" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">LinkedIn</label>
                        <input type="url" name="linkedin" class="w-full p-2 border rounded">
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div class="mb-4">
                            <label class="block text-sm font-medium">Experience (Years)</label>
                            <input type="text" name="stats[experience]" class="w-full p-2 border rounded" required>
                        </div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium">Publications</label>
                            <input type="text" name="stats[publications]" class="w-full p-2 border rounded" required>
                        </div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium">Research (Years)</label>
                            <input type="text" name="stats[research]" class="w-full p-2 border rounded" required>
                        </div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium">Admin (Years)</label>
                            <input type="text" name="stats[admin]" class="w-full p-2 border rounded" required>
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Professional Profile</label>
                        <textarea name="professionalProfile" class="w-full p-2 border rounded" rows="4" required></textarea>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Area of Interest</label>
                        <input type="text" name="areaOfInterest" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div class="mb-4">
                            <label class="block text-sm font-medium">UG Subjects (comma separated)</label>
                            <input type="text" name="subjectsTaught[ug]" class="w-full p-2 border rounded" required>
                        </div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium">PG Subjects (comma separated)</label>
                            <input type="text" name="subjectsTaught[pg]" class="w-full p-2 border rounded" required>
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Key Skills (comma separated)</label>
                        <input type="text" name="keySkills" class="w-full p-2 border rounded" required>
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div class="mb-4">
                            <label class="block text-sm font-medium">Total Experience</label>
                            <input type="text" name="experienceSummary[total]" class="w-full p-2 border rounded" required>
                        </div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium">Research Experience</label>
                            <input type="text" name="experienceSummary[research]" class="w-full p-2 border rounded" required>
                        </div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium">Admin Experience</label>
                            <input type="text" name="experienceSummary[admin]" class="w-full p-2 border rounded" required>
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium mb-2">Academic Background</label>
                        <div id="academic-container" class="space-y-3"></div>
                        <button type="button" id="add-academic" class="mt-2 bg-gray-500 text-white px-3 py-1 rounded text-sm">Add Academic Entry</button>
                    </div>
                    <input type="hidden" name="academicBackground" id="academic-json">
                    <div class="mb-4">
                        <label class="block text-sm font-medium mb-2">Work Experience</label>
                        <div id="work-container" class="space-y-3"></div>
                        <button type="button" id="add-work" class="mt-2 bg-gray-500 text-white px-3 py-1 rounded text-sm">Add Work Entry</button>
                    </div>
                    <input type="hidden" name="workExperience" id="work-json">
                    <div class="mb-4">
                        <label class="block text-sm font-medium mb-2">Publications</label>
                        <div id="publications-container" class="space-y-3"></div>
                        <button type="button" id="add-publication" class="mt-2 bg-gray-500 text-white px-3 py-1 rounded text-sm">Add Publication</button>
                    </div>
                    <input type="hidden" name="publications" id="publications-json">
                    <button id="save-btn" type="submit" class="bg-blue-500 text-white px-4 py-2 rounded">Save</button>
                </form>
            </section>
        </div>
    </div>

    <script>
        const facultyListEl = document.getElementById('faculty-list');
        const addNewBtn = document.getElementById('add-new');
        const formTitle = document.getElementById('form-title');
        const indexInput = document.getElementById('faculty-index');
        const facultyForm = document.getElementById('faculty-form');

        let faculties = [];

        const formField = key => document.querySelector(`[name="${key}"]`);

        function createAcademicEntry(data = {}) {
            const div = document.createElement('div');
            div.className = 'border rounded p-3 bg-gray-50';
            div.innerHTML = `
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2">
                    <input type="text" placeholder="Degree" class="p-1 border rounded" value="${data.degree || ''}">
                    <input type="text" placeholder="Specialization" class="p-1 border rounded" value="${data.specialization || ''}">
                    <input type="text" placeholder="University" class="p-1 border rounded" value="${data.university || ''}">
                    <input type="text" placeholder="Class" class="p-1 border rounded" value="${data.class || ''}">
                    <input type="text" placeholder="Year" class="p-1 border rounded" value="${data.year || ''}">
                </div>
                <button type="button" class="remove-btn bg-red-500 text-white px-2 py-1 rounded text-xs">Remove</button>
            `;
            div.querySelector('.remove-btn').onclick = () => div.remove();
            return div;
        }

        function createWorkEntry(data = {}) {
            const div = document.createElement('div');
            div.className = 'border rounded p-3 bg-gray-50';
            div.innerHTML = `
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2">
                    <input type="text" placeholder="Position" class="p-1 border rounded" value="${data.position || ''}">
                    <input type="text" placeholder="Institution" class="p-1 border rounded" value="${data.institution || ''}">
                    <input type="text" placeholder="Period" class="p-1 border rounded" value="${data.period || ''}">
                    <label class="flex items-center">
                        <input type="checkbox" ${data.current ? 'checked' : ''} class="mr-1"> Current
                    </label>
                </div>
                <button type="button" class="remove-btn bg-red-500 text-white px-2 py-1 rounded text-xs">Remove</button>
            `;
            div.querySelector('.remove-btn').onclick = () => div.remove();
            return div;
        }

        function createPublicationEntry(data = {}) {
            const div = document.createElement('div');
            div.className = 'border rounded p-3 bg-gray-50';
            div.innerHTML = `
                <div class="grid grid-cols-1 gap-2 mb-2">
                    <input type="number" placeholder="ID" class="p-1 border rounded" value="${data.id || ''}">
                    <input type="text" placeholder="Title" class="p-1 border rounded" value="${data.title || ''}">
                    <input type="text" placeholder="Journal" class="p-1 border rounded" value="${data.journal || ''}">
                    <input type="text" placeholder="Role" class="p-1 border rounded" value="${data.role || ''}">
                    <input type="text" placeholder="Indexing" class="p-1 border rounded" value="${data.indexing || ''}">
                </div>
                <button type="button" class="remove-btn bg-red-500 text-white px-2 py-1 rounded text-xs">Remove</button>
            `;
            div.querySelector('.remove-btn').onclick = () => div.remove();
            return div;
        }

        function clearForm() {
            facultyForm.reset();
            indexInput.value = -1;
            formTitle.textContent = 'Add Faculty';
            document.getElementById('academic-container').innerHTML = '';
            document.getElementById('work-container').innerHTML = '';
            document.getElementById('publications-container').innerHTML = '';
        }

        function setFormData(data, index) {
            formTitle.textContent = 'Edit Faculty';
            indexInput.value = index;
            formField('name').value = data.name || '';
            formField('initials').value = data.initials || '';
            formField('designation').value = data.designation || '';
            formField('institution').value = data.institution || '';
            formField('phone').value = data.phone || '';
            formField('email').value = data.email || '';
            formField('linkedin').value = data.linkedin || '';
            formField('stats[experience]').value = data.stats?.experience || '';
            formField('stats[publications]').value = data.stats?.publications || '';
            formField('stats[research]').value = data.stats?.research || '';
            formField('stats[admin]').value = data.stats?.admin || '';
            formField('professionalProfile').value = data.professionalProfile || '';
            formField('areaOfInterest').value = data.areaOfInterest || '';
            formField('subjectsTaught[ug]').value = (data.subjectsTaught?.ug || []).join(', ');
            formField('subjectsTaught[pg]').value = (data.subjectsTaught?.pg || []).join(', ');
            formField('keySkills').value = (data.keySkills || []).join(', ');
            formField('experienceSummary[total]').value = data.experienceSummary?.total || '';
            formField('experienceSummary[research]').value = data.experienceSummary?.research || '';
            formField('experienceSummary[admin]').value = data.experienceSummary?.admin || '';

            // Populate dynamic sections
            const academicContainer = document.getElementById('academic-container');
            academicContainer.innerHTML = '';
            (data.academicBackground || []).forEach(item => {
                academicContainer.appendChild(createAcademicEntry(item));
            });

            const workContainer = document.getElementById('work-container');
            workContainer.innerHTML = '';
            (data.workExperience || []).forEach(item => {
                workContainer.appendChild(createWorkEntry(item));
            });

            const pubContainer = document.getElementById('publications-container');
            pubContainer.innerHTML = '';
            (data.publications || []).forEach(item => {
                pubContainer.appendChild(createPublicationEntry(item));
            });
        }

        function renderFacultyList() {
            facultyListEl.innerHTML = '';

            faculties.forEach((faculty, idx) => {
                const row = document.createElement('div');
                row.className = 'border rounded p-2 flex justify-between items-center';

                const text = document.createElement('span');
                text.textContent = `${faculty.name || 'Unnamed'} (${faculty.designation || 'No designation'})`;

                const editBtn = document.createElement('button');
                editBtn.type = 'button';
                editBtn.textContent = 'Edit';
                editBtn.className = 'bg-blue-600 text-white px-3 py-1 rounded text-xs';
                editBtn.onclick = () => setFormData(faculty, idx);

                row.appendChild(text);
                row.appendChild(editBtn);
                facultyListEl.appendChild(row);
            });

            if (!faculties.length) {
                const empty = document.createElement('p');
                empty.className = 'text-sm text-slate-500';
                empty.textContent = 'No faculty records found. Click Add New to create one.';
                facultyListEl.appendChild(empty);
            }
        }

        function loadFacultyData() {
            fetch('../faculty.json')
                .then(res => res.ok ? res.json() : Promise.reject('load fail'))
                .then(data => {
                    if (!Array.isArray(data)) {
                        faculties = [data];
                    } else {
                        faculties = data;
                    }

                    renderFacultyList();
                    if (faculties.length > 0) {
                        setFormData(faculties[0], 0);
                    } else {
                        clearForm();
                    }
                })
                .catch(err => {
                    faculties = [];
                    renderFacultyList();
                    clearForm();
                    console.error('Cannot load faculty.json', err);
                });
        }

        function collectDynamicData() {
            // Academic Background
            const academicEntries = document.querySelectorAll('#academic-container > div');
            const academicData = Array.from(academicEntries).map(div => {
                const inputs = div.querySelectorAll('input');
                return {
                    degree: inputs[0].value,
                    specialization: inputs[1].value,
                    university: inputs[2].value,
                    class: inputs[3].value,
                    year: inputs[4].value
                };
            });
            document.getElementById('academic-json').value = JSON.stringify(academicData);

            // Work Experience
            const workEntries = document.querySelectorAll('#work-container > div');
            const workData = Array.from(workEntries).map(div => {
                const inputs = div.querySelectorAll('input');
                return {
                    position: inputs[0].value,
                    institution: inputs[1].value,
                    period: inputs[2].value,
                    current: inputs[3].checked
                };
            });
            document.getElementById('work-json').value = JSON.stringify(workData);

            // Publications
            const pubEntries = document.querySelectorAll('#publications-container > div');
            const pubData = Array.from(pubEntries).map(div => {
                const inputs = div.querySelectorAll('input');
                return {
                    id: parseInt(inputs[0].value) || 0,
                    title: inputs[1].value,
                    journal: inputs[2].value,
                    role: inputs[3].value,
                    indexing: inputs[4].value
                };
            });
            document.getElementById('publications-json').value = JSON.stringify(pubData);
        }

        addNewBtn.addEventListener('click', () => {
            clearForm();
        });

        document.getElementById('add-academic').addEventListener('click', () => {
            document.getElementById('academic-container').appendChild(createAcademicEntry());
        });

        document.getElementById('add-work').addEventListener('click', () => {
            document.getElementById('work-container').appendChild(createWorkEntry());
        });

        document.getElementById('add-publication').addEventListener('click', () => {
            document.getElementById('publications-container').appendChild(createPublicationEntry());
        });

        facultyForm.addEventListener('submit', (e) => {
            collectDynamicData();
        });

        loadFacultyData();
    </script>
</body>
</html>