<%- include("partials/header-sidebar")%>
    <style>
        .ts-control {
            min-height: 38px;
            border-radius: 4px;
        }


        .image-uploads {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 20px;
            width: 220px;
            height: 150px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            background-color: #fafafa;
            overflow: hidden;
            /* Ensures image doesn't overflow */
        }

        .image-uploads img.preview-thumb {
            width: auto;
            height: 100px;
            max-width: 100%;
            max-height: 100%;
            border-radius: 6px;
            object-fit: contain;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }


        @media (max-width: 576px) {
            .image-uploads {
                width: 100%;
                height: 130px;
            }

            .image-uploads img.preview-thumb {
                height: 80px;
            }
        }
    </style>
    <!-- Tom Select CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.css" rel="stylesheet">



    <div class="page-wrapper" id="toTop">
        <div class="content">
            <div class="page-header">
                <div class="page-title">
                    <h4>Manage Programs</h4>
                    <h6>Add/Update/Delete Programs</h6>
                </div>
            </div>

            <form id="programForm" enctype="multipart/form-data">
                <div class="card">
                    <div class="card-body">

                        <div class="row">

                            <!-- Program Name -->
                            <div class="col-lg-12">
                                <div class="form-group">
                                    <label for="name">Program Name</label>
                                    <input type="text" id="name" name="name" class="form-control"
                                        placeholder="Enter program name" required>
                                </div>
                            </div>


                            <div class="col-lg-12">
                                <div class="form-group">
                                    <label for="faculty">School</label>
                                    <select id="faculty" name="faculty" class="form-select" required>
                                        <option value="" selected disabled>Select a School</option>
                                        <!-- Dynamically populated with faculty ObjectId values -->
                                    </select>
                                </div>
                            </div>



                            <!-- Department (multi-select, dynamic) -->
                            <div class="col-lg-12">
                                <div class="form-group">
                                    <label for="department">Department</label>
                                    <select id="department" name="department" class="form-select" multiple required>
                                        <!-- Dynamically populated with department ObjectId values -->
                                    </select>
                                </div>
                            </div>

                            <!-- Level -->
                            <div class="col-lg-12">
                                <div class="form-group">
                                    <label for="level">Level</label>
                                    <select id="level" name="level" class="form-select" required>
                                        <option value="" selected disabled>Select Level</option>
                                        <option value="ND">ND</option>
                                        <option value="HND">HND</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Program Type (ObjectIds, dynamically populated) -->
                            <div class="col-lg-12">
                                <div class="form-group">
                                    <label for="programType">Program Type</label>
                                    <select id="programType" name="programType" class="form-select" multiple required>
                                        <!-- Dynamically populated with programType ObjectId values -->
                                    </select>
                                </div>
                            </div>

                            <!-- Required Credit -->
                            <div class="col-sm-12 col-lg-6">
                                <div class="form-group">
                                    <label for="requiredCredit">Min Required Credit</label>
                                    <input type="number" id="requiredCredit" name="requiredCredit" class="form-control"
                                        placeholder="Enter minimum credit" min="0" required>
                                </div>
                            </div>

                            <!-- Duration -->
                            <div class="col-sm-12 col-lg-6">
                                <div class="form-group">
                                    <label for="duration">Program Duration</label>
                                    <input type="text" id="duration" name="duration" class="form-control"
                                        placeholder="e.g. 2 Years" required>
                                </div>
                            </div>



                            <!-- Description -->
                            <div class="col-lg-12">
                                <div class="form-group">
                                    <label for="description">Program Description</label>
                                    <textarea id="description" name="description" class="form-control" rows="4"
                                        placeholder="Short description" required></textarea>
                                </div>
                            </div>

                            <!-- Image Upload -->
                            <div class="col-lg-12">
                                <div class="form-group">
                                    <label for="programImage">Upload Program Image</label>
                                    <div class="image-upload">
                                        <input type="file" name="programImage" id="programImage" accept="image/*"
                                            required />
                                        <div class="image-uploads">
                                            <img src="assets/img/icons/upload.svg" alt="upload icon"
                                                class="upload-icon" />
                                            <h4>Drag and drop program image here</h4>
                                        </div>
                                    </div>
                                </div>
                            </div>


                            <!-- Submit Buttons -->
                            <div class="col-lg-12 mt-5">
                                <button type="button" id="createProgramBtn" class="btn btn-submit me-2">Create
                                    Program</button>
                                <button type="button" id="updateProgramBtn" class="btn btn-submit me-2">Update
                                    Program</button>
                                <button type="button" id="cancelUpdateBtn" onclick="cancelUpdate()"
                                    class="btn btn-cancel me-2">Cancel</button>
                            </div>



                        </div>
                    </div>
                </div>
            </form>



            <!-- table to contain list of schools -->
            <div class="row">
                <div class="col-sm-12">
                    <div class="card">
                        <div class="card-header pb-0">
                            <h4 class="card-title mb-0">All Programs</h4>

                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table datanew">
                                    <thead>
                                        <tr>
                                            <th>S/N</th>
                                            <th>School</th>
                                            <th>Department</th>
                                            <th>Prog Type</th>
                                            <th>Prog Name</th>
                                            <th>Level</th>
                                            <th>Credits</th>
                                            <th>Duration</th>
                                            <th>Actions</th>



                                        </tr>
                                    </thead>
                                    <tbody id="programList">
                                        <!-- inserted from js -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>



    <!-- Tom Select JS -->
    <script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>


    <%- include("partials/footer")%>

        <!-- For the image and its preview -->
        <script>
            const input = document.getElementById('programImage');
            const previewContainer = document.querySelector('.image-uploads');

            input.addEventListener('change', function () {
                const file = this.files[0]; // Only handle the first file

                // If more than one file is selected, ignore the rest
                if (this.files.length > 1) {
                    this.value = ''; // Reset the input
                    return; // Do nothing further
                }

                if (file) {
                    // Clear the previous content
                    previewContainer.innerHTML = '';

                    // Create the new thumbnail preview
                    const img = document.createElement('img');
                    img.src = URL.createObjectURL(file);
                    img.classList.add('preview-thumb'); // Style class
                    previewContainer.appendChild(img);

                    // Release memory when done
                    img.onload = () => URL.revokeObjectURL(img.src);
                }
            });

        </script>



        <!-- populating and initializing TOM SELECT -->
        <script>
            document.addEventListener("DOMContentLoaded", () => {


                document.getElementById("updateProgramBtn").style.display = "none";
                document.getElementById("cancelUpdateBtn").style.display = "none";


                populateDepartments();
                populateProgramTypes();
                populateSchools();

                loadPrograms()

                // Initialize TomSelect for static #level
                new TomSelect('#level', {
                    plugins: ['remove_button'],
                    maxItems: null,
                    placeholder: 'Select Level(s)',
                    create: false,
                    persist: false
                });


            });

            async function populateDepartments() {
                try {
                    const response = await fetch('/api/departments', {
                        headers: {
                            Authorization: `Bearer ${token}`,
                        }
                    });
                    const { data: departments } = await response.json();

                    const departmentSelect = document.getElementById('department');
                    if (!departmentSelect) return;

                    departmentSelect.innerHTML = ''; // Clear existing options

                    departments.forEach(dept => {
                        const option = document.createElement('option');
                        option.value = dept._id;
                        option.textContent = dept.name;
                        departmentSelect.appendChild(option);
                    });

                    // Initialize TomSelect AFTER populating
                    if (!departmentSelect.tomselect) {
                        new TomSelect("#department", {
                            plugins: ['remove_button'],
                            maxItems: null,
                            placeholder: 'Select Department(s)',
                            create: false,
                            persist: false
                        });
                    }
                } catch (error) {
                    console.error("Failed to load departments:", error);
                }
            }

            async function populateProgramTypes() {
                try {
                    const response = await fetch('/api/program-types', {
                        headers: {
                            Authorization: `Bearer ${token}`,
                        }
                    });
                    const { data: types } = await response.json();

                    const programTypeSelect = document.getElementById('programType');
                    if (!programTypeSelect) return;

                    programTypeSelect.innerHTML = ''; // Clear existing options

                    types.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type._id;
                        option.textContent = type.programTypeName;
                        programTypeSelect.appendChild(option);
                    });

                    if (!programTypeSelect.tomselect) {
                        new TomSelect("#programType", {
                            plugins: ['remove_button'],
                            maxItems: null,
                            placeholder: 'Select Program Type',
                            create: false,
                            persist: false
                        });
                    }
                } catch (error) {
                    console.error("Failed to load program types:", error);
                }
            }

            async function populateSchools() {
                try {
                    const response = await fetch('/api/schools', {
                        headers: {
                            Authorization: `Bearer ${token}`,
                        }
                    });
                    const { data: faculties } = await response.json();

                    const facultySelect = document.getElementById('faculty');
                    if (!facultySelect) return;

                    // Reset the select options, keeping the default placeholder
                    facultySelect.innerHTML = '<option value="" selected>Select a School</option>';

                    faculties.forEach(faculty => {
                        const option = document.createElement('option');
                        option.value = faculty._id;
                        option.textContent = faculty.name;
                        facultySelect.appendChild(option);
                    });

                } catch (error) {
                    console.error("Failed to load faculties:", error);
                }
            }

        </script>



        <script>
            function getFormData() {
                const form = document.getElementById('programForm');
                const formData = new FormData();

                formData.append('faculty', form.faculty.value);

                const departmentSelect = document.getElementById('department');
                const selectedDepartments = Array.from(departmentSelect.selectedOptions).map(opt => opt.value);

                const levelSelect = document.getElementById('level');
                const selectedLevels = Array.from(levelSelect.selectedOptions).map(opt => opt.value);

                const programTypeSelect = document.getElementById('programType');
                const selectedProgramTypes = Array.from(programTypeSelect.selectedOptions).map(opt => opt.value);

                selectedDepartments.forEach(dep => formData.append('department', dep));
                selectedLevels.forEach(level => formData.append('level', level));
                selectedProgramTypes.forEach(type => formData.append('programType', type));

                formData.append('requiredCredit', form.requiredCredit.value);
                formData.append('duration', form.duration.value);
                formData.append('name', form.name.value);
                formData.append('description', form.description.value);

                const imageFile = form.programImage.files[0];
                if (imageFile) {
                    formData.append('programImage', imageFile);
                }

                return formData;
            }





            document.getElementById('createProgramBtn').addEventListener('click', async (e) => {
                e.preventDefault();
                const formData = getFormData();

                try {
                    const response = await fetch('/api/programs', {
                        method: 'POST',
                        headers: {
                            Authorization: `Bearer ${token}`
                        },
                        body: formData,
                    });

                    const result = await response.json();

                    if (response.ok) {
                        await swal.fire({
                            icon: 'success',
                            title: 'Program created successfully!',
                            timer: 2000,
                            showConfirmButton: false,
                        });
                        const form = document.getElementById('programForm');
                        form.reset();

                        document.getElementById('department').tomselect.clear();
                        document.getElementById('level').tomselect.clear();
                        document.getElementById('programType').tomselect.clear();

                        // Clear image preview and reset upload UI
                        const imageContainer = document.querySelector('.image-uploads');
                        imageContainer.innerHTML = `
                                < img src="assets/img/icons/upload.svg" alt="upload icon" class= "upload-icon" />
                                    <h4>Drag and drop program image here</h4>
    `;


                        document.querySelector(".table-responsive").scrollIntoView({ behavior: "smooth" });
                    } else {
                        await swal.fire({
                            icon: 'error',
                            title: 'Failed to create program',
                            text: result.message || 'Unknown error',
                        });
                    }
                } catch (error) {
                    console.error('Error creating program:', error);
                    await swal.fire({
                        icon: 'error',
                        title: 'Error creating program',
                        text: 'Check the console for details.',
                    });
                }
            });




            document.getElementById('updateProgramBtn').addEventListener('click', async (e) => {
                e.preventDefault();

                const formData = getFormData();
                const programId = document.getElementById('programForm').dataset.editId;

                if (!programId) {
                    return swal.fire({
                        icon: 'error',
                        title: 'No program selected for update',
                    });
                }

                try {
                    const response = await fetch(`/api/programs/${programId}`, {

                        method: 'PUT', // assuming your API uses PUT for updates
                        headers: {
                            Authorization: `Bearer ${token}`
                        },
                        body: formData,
                    });

                    const result = await response.json();

                    if (response.ok) {
                        await swal.fire({
                            icon: 'success',
                            title: 'Program updated successfully!',
                            timer: 2000,
                            showConfirmButton: false,
                        });

                        // Optionally reset form and buttons, or refresh data on the page
                        resetProgramForm()

                        await loadPrograms()

                        document.getElementById("toTop").scrollIntoView({ behavior: "smooth" });
                    } else {
                        await swal.fire({
                            icon: 'error',
                            title: 'Failed to update program',
                            text: result.message || 'Unknown error',
                        });
                    }
                } catch (error) {
                    console.error('Error updating program:', error);
                    await swal.fire({
                        icon: 'error',
                        title: 'Error updating program',
                        text: 'Check the console for details.',
                    });
                }
            });



            // Reseting the form
            function resetProgramForm() {
                const form = document.getElementById('programForm');
                form.reset(); // Resets native inputs

                // Reset TomSelect fields
                ['faculty', 'department', 'level', 'programType'].forEach(id => {
                    const select = document.getElementById(id);
                    if (select?.tomselect) {
                        select.tomselect.clear(); // Clear selection
                    }
                });

                // Clear image preview and reset upload UI
                const imageContainer = document.querySelector('.image-uploads');
                imageContainer.innerHTML = `
                    < img src = "assets/img/icons/upload.svg" alt = "upload icon" class= "upload-icon" />
                    <h4>Drag and drop program image here</h4>
    `;

                // Reset buttons
                document.getElementById("createProgramBtn").style.display = "inline-block";
                document.getElementById("updateProgramBtn").style.display = "none";
                document.getElementById("cancelUpdateBtn").style.display = "none";

                // Remove stored edit ID
                form.removeAttribute('data-edit-id');


            }



        </script>

        <!-- populating the table using fetch -->

        <script>
            async function loadPrograms() {
                try {
                    const response = await fetch('/api/programs', {
                        headers: { Authorization: `Bearer ${token}` }
                    });
                    const bdata = await response.json();
                    const data = bdata.programs;

                    if ($.fn.DataTable.isDataTable('.datanew')) {
                        $('.datanew').DataTable().destroy();
                    }

                    const tbody = document.getElementById('programList');
                    tbody.innerHTML = '';

                    if (!Array.isArray(data) || data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="9" class="text-center">No programs found.</td></tr>';
                        return;
                    }

                    data.forEach((program, index) => {
                        const row = document.createElement('tr');

                        // Safely encode the program object
                        const programData = encodeURIComponent(JSON.stringify(program));

                        row.innerHTML = `
                        <td> ${index + 1}</td>
                <td>${program?.faculty?.name || "N/A"}</td>
                <td>${Array.isArray(program.department) ? program.department.map(d => d.name).join(', ') : program.department?.name || 'N/A'}</td>
                <td>${Array.isArray(program.programType) ? program.programType.map(p => p.programTypeName).join(', ') : program?.programType?.programTypeName || 'N/A'}</td>
                <td>${program.name}</td>
                <td>${Array.isArray(program.level) ? program.level.join(', ') : program.level}</td>
                <td>${program.requiredCredit}</td>
                <td>${program.duration}</td>
                <td>
                    <span class="me-2 text-primary action-btns" onclick="editProgram(this)" data-program="${programData}">
                        <i class="fas fa-pen me-1"></i>Edit
                    </span>
                    <span class="text-danger action-btns" onclick="deleteProgram('${program._id}')">
                        <i class="fas fa-trash me-1"></i>Delete
                    </span>
                </td>
            `;

                        tbody.appendChild(row);
                    });

                    $('.datanew').DataTable();

                } catch (err) {
                    console.error('Failed to load programs:', err);
                    document.getElementById('programList').innerHTML =
                        '<tr><td colspan="9" class="text-danger text-center">Error loading programs</td></tr>';
                }
            }

        </script>



        <!-- BIG POPULATE -->

        <script>
            async function editProgram(elem) {
                try {
                    // Parse the program JSON from data attribute
                    const program = JSON.parse(decodeURIComponent(elem.getAttribute('data-program')));

                    // Populate all selects once
                    await populateSchools();
                    await populateDepartments();
                    await populateProgramTypes();

                    // Faculty (single select)
                    const facultySelect = document.getElementById('faculty');
                    if (facultySelect.tomselect) {
                        facultySelect.tomselect.setValue(program.faculty._id);
                    } else {
                        facultySelect.value = program.faculty._id;
                    }

                    // Departments (multi-select)
                    const departmentSelect = document.getElementById('department');
                    const departmentTom = departmentSelect.tomselect;
                    // Do NOT clear options here, just set selected values
                    departmentTom.setValue(program.department.map(d => d._id));

                    // Program Types (multi-select)
                    const programTypeSelect = document.getElementById('programType');
                    const programTypeTom = programTypeSelect.tomselect;
                    // Do NOT clear options here, just set selected values
                    programTypeTom.setValue(program.programType.map(pt => pt._id));

                    // Level (single select or multi-select)
                    const levelSelect = document.getElementById('level');
                    if (levelSelect.tomselect) {
                        levelSelect.tomselect.setValue(program.level);
                    } else {
                        levelSelect.value = program.level.length === 1 ? program.level[0] : null;
                    }

                    // Fill text, number, textarea inputs
                    document.getElementById('name').value = program.name || '';
                    document.getElementById('description').value = program.description || '';
                    document.getElementById('requiredCredit').value = program.requiredCredit || '';
                    document.getElementById('duration').value = program.duration || '';

                    // Image preview & clear required attribute on file input (image already exists)
                    const imageInput = document.getElementById('programImage');
                    imageInput.required = false; // remove required when editing

                    const imageContainer = document.querySelector('.image-uploads');
                    imageContainer.innerHTML = ''; // Clear previous preview

                    if (program.programImage?.url) {
                        const imgPreview = document.createElement('img');
                        imgPreview.src = program.programImage.url;
                        imgPreview.alt = 'Program Image';
                        imgPreview.style.maxWidth = '150px';
                        imageContainer.appendChild(imgPreview);
                    } else {
                        // fallback placeholder
                        imageContainer.innerHTML = `
                    < img src = "assets/img/icons/upload.svg" alt = "upload icon" class="upload-icon" />
                        <h4>Drag and drop program image here</h4>
                `;
                    }

                    // Show Update / Cancel buttons, hide Create button
                    document.getElementById("createProgramBtn").style.display = "none";
                    document.getElementById("updateProgramBtn").style.display = "inline-block";
                    document.getElementById("cancelUpdateBtn").style.display = "inline-block";

                    await loadPrograms()

                    // Store program ID for update reference
                    document.getElementById('programForm').dataset.editId = program._id;

                } catch (error) {
                    console.error('Error populating edit form:', error);
                    swal.fire({
                        icon: 'error',
                        title: 'Failed to load program data',
                        text: 'Please try again.'
                    });
                }
            }
        </script>




        <script>
            // DELETE
            function deleteProgram(id) {
                Swal.fire({
                    title: "Are you sure?",
                    text: "This will permanently delete the Program.",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Yes, delete it!",
                    cancelButtonText: "Cancel"
                }).then(async (result) => {
                    if (result.isConfirmed) {
                        try {
                            const res = await fetch(`/ api / programs / ${id} `, {
                                method: "DELETE",
                                headers: {
                                    Authorization: `Bearer ${localStorage.getItem("token")}`
                                }
                            });

                            const data = await res.json();
                            if (!res.ok || !data.success) {
                                throw new Error(data.message || "Failed to delete");
                            }

                            Swal.fire("Deleted!", "Program has been deleted.", "success");
                            loadPrograms();
                        } catch (err) {
                            console.error(err);
                            Swal.fire("Error", err.message, "error");
                        }
                    }
                });
            }



            // RESETING THE FORM WHEN CANCELLED
            document.getElementById("cancelUpdateBtn").addEventListener('click', () => {
                resetProgramForm()
                document.querySelector(".table-responsive").scrollIntoView({ behavior: "smooth" });
            })

        </script>


        </body>

        </html>