<section class="w-full py-12 md:py-24 lg:py-32">
    <div class="container mx-auto px-4 md:px-6">
        <div class="mx-auto max-w-3xl">
            <div class="mb-8 space-y-2 text-center">
                <h1 class="font-headline text-3xl font-bold tracking-tight sm:text-4xl">
                    Update Profile
                </h1>
                <p class="text-gray-500">
                    Update your personal and academic information below.
                </p>
            </div>
            <% if (error) { %>
                <div class="mb-6 text-red-600 text-sm text-center"><%= error %></div>
                <% } %>
                <form id="update-profile-form" action="/student/update-profile" method="POST" class="space-y-8">
                    <div class="bg-white shadow-lg rounded-lg">
                        <div class="p-6">
                            <h2 class="text-xl font-headline font-bold">Personal Information</h2>
                        </div>
                        <div class="p-6 pt-0 grid grid-cols-1 gap-6 md:grid-cols-2">
                            <div class="space-y-2">
                                <label for="fullName" class="text-sm font-medium">Full Name</label>
                                <input
                                id="fullName"
                                name="fullName"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                />
                            </div>
                            <div class="space-y-2">
                                <label for="email" class="text-sm font-medium">Email Address</label>
                                <input
                                id="email"
                                name="email"
                                type="email"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                />
                            </div>
                            <div class="space-y-2">
                                <label for="phone" class="text-sm font-medium">Phone Number</label>
                                <input
                                id="phone"
                                name="phone"
                                type="tel"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                />
                            </div>
                            <div class="space-y-2">
                                <label for="gender" class="text-sm font-medium">Gender</label>
                                <select
                                id="gender"
                                name="gender"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                required
                                >
                                <option value="" disabled selected>Select</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                                <option value="Other">Other</option>
                                <option value="Prefer not to say">Prefer not to say</option>
                            </select>
                        </div>
                        <div class="space-y-2">
                            <label for="race" class="text-sm font-medium">Race</label>
                            <select
                            id="race"
                            name="race"
                            required
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                            >
                            <option value="" disabled selected>Select your race</option>
                            <option value="Black African">Black African</option>
                            <option value="Coloured">Coloured</option>
                            <option value="Indian or Asian">Indian or Asian</option>
                            <option value="White">White</option>
                            <option value="Other">Other</option>
                            <option value="Prefer not to say">Prefer not to say</option>
                        </select>
                    </div>
                    <div class="space-y-2">
                        <label for="idNumber" class="text-sm font-medium">ID Number</label>
                        <input
                        id="idNumber"
                        name="idNumber"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                        />
                    </div>
                    <div class="space-y-2 md:col-span-2">
                        <label for="address" class="text-sm font-medium">Residential Address</label>
                    </div>
                    <div class="space-y-2">
                        <label for="dateOfBirth" class="text-sm font-medium">Date of Birth</label>
                        <input
                        id="dateOfBirth"
                        name="dateOfBirth"
                        type="date"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                        />
                    </div>
                </div>
            </div>
            <div class="bg-white shadow-lg rounded-lg">
                <div class="p-6">
                    <h2 class="text-xl font-headline font-bold">Academic Information</h2>
                </div>
                <div class="p-6 pt-0 grid grid-cols-1 gap-6 md:grid-cols-2">
                    <div class="space-y-2">
                        <label for="institution" class="text-sm font-medium">Tertiary Institution</label>
                        <select
                        id="institution"
                        name="institution"
                        required
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                        >
                        <option value="" disabled selected>Select your institution</option>

                        <!-- Public Universities -->
                        <optgroup label="Public Universities">
                            <option value="University of Cape Town">University of Cape Town (UCT)</option>
                            <option value="University of the Witwatersrand">University of the Witwatersrand (Wits)</option>
                            <option value="University of Pretoria">University of Pretoria (UP)</option>
                            <option value="Stellenbosch University">Stellenbosch University (SU)</option>
                            <option value="University of Johannesburg">University of Johannesburg (UJ)</option>
                            <option value="University of KwaZulu-Natal">University of KwaZulu-Natal (UKZN)</option>
                            <option value="University of the Western Cape">University of the Western Cape (UWC)</option>
                            <option value="University of South Africa">University of South Africa (UNISA)</option>
                            <option value="University of Fort Hare">University of Fort Hare (UFH)</option>
                            <option value="North-West University">North-West University (NWU)</option>
                            <option value="Rhodes University">Rhodes University</option>
                            <option value="University of Limpopo">University of Limpopo</option>
                            <option value="University of Venda">University of Venda (UNIVEN)</option>
                            <option value="Walter Sisulu University">Walter Sisulu University (WSU)</option>
                            <option value="University of Zululand">University of Zululand (UZ)</option>
                            <option value="Central University of Technology">Central University of Technology (CUT)</option>
                            <option value="Cape Peninsula University of Technology">Cape Peninsula University of Technology (CPUT)</option>
                            <option value="Durban University of Technology">Durban University of Technology (DUT)</option>
                            <option value="Mangosuthu University of Technology">Mangosuthu University of Technology (MUT)</option>
                            <option value="Nelson Mandela University">Nelson Mandela University (NMU)</option>
                            <option value="Tshwane University of Technology">Tshwane University of Technology (TUT)</option>
                            <option value="Vaal University of Technology">Vaal University of Technology (VUT)</option>
                        </optgroup>

                        <!-- TVET Colleges -->
                        <optgroup label="TVET Colleges">
                            <option value="Ekurhuleni East TVET College">Ekurhuleni East TVET College</option>
                            <option value="Ekurhuleni West TVET College">Ekurhuleni West TVET College</option>
                            <option value="South West Gauteng TVET College">South West Gauteng TVET College</option>
                            <option value="Tshwane South TVET College">Tshwane South TVET College</option>
                            <option value="Tshwane North TVET College">Tshwane North TVET College</option>
                            <option value="Sedibeng TVET College">Sedibeng TVET College</option>
                            <option value="Western TVET College">Western TVET College</option>
                            <option value="False Bay TVET College">False Bay TVET College</option>
                            <option value="Northlink TVET College">Northlink TVET College</option>
                            <option value="Boland TVET College">Boland TVET College</option>
                            <option value="Port Elizabeth TVET College">Port Elizabeth TVET College</option>
                            <option value="Buffalo City TVET College">Buffalo City TVET College</option>
                            <option value="Eastcape Midlands TVET College">Eastcape Midlands TVET College</option>
                            <option value="Central Johannesburg TVET College">Central Johannesburg TVET College</option>
                            <option value="Gert Sibande TVET College">Gert Sibande TVET College</option>
                            <!-- You can add more from DHET as needed -->
                        </optgroup>
                    </select>
                </div>

                <div class="space-y-2">
                    <label for="qualification" class="text-sm font-medium">Qualification</label>
                    <input
                    id="qualification"
                    name="qualification"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                    />
                </div>
            </div>
        </div>
        <div class="bg-white shadow-lg rounded-lg">
            <div class="p-6">
                <h2 class="text-xl font-headline font-bold">Guardian Information</h2>
            </div>
            <div class="p-6 pt-0 grid grid-cols-1 gap-6 md:grid-cols-2">
                <div class="space-y-2">
                    <label for="guardianName" class="text-sm font-medium">Guardian Name</label>
                    <input
                    id="guardianName"
                    name="guardianName"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                    />
                </div>
                <div class="space-y-2">
                    <label for="guardianContact" class="text-sm font-medium">Guardian Contact</label>
                    <input
                    id="guardianContact"
                    name="guardianContact"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                    />
                </div>
            </div>
        </div>
        <div class="bg-white shadow-lg rounded-lg">
            <div class="p-6">
                <h2 class="text-xl font-headline font-bold">Additional Information</h2>
            </div>
            <div class="p-6 pt-0">
                <div class="flex items-center space-x-2">
                    <input
                    id="disabilityStatus"
                    name="disabilityStatus"
                    type="checkbox"
                    class="h-4 w-4 text-blue-600 focus:ring-blue-600 border-gray-300 rounded"
                    />
                    <label for="disabilityStatus" class="text-sm font-medium">
                        I have a disability
                    </label>
                </div>
            </div>
        </div>
        <div class="flex justify-between items-center">
            <a
            href="/student/dashboard"
            class="inline-flex items-center bg-gray-200 text-gray-700 px-6 py-3 rounded-md hover:bg-gray-300 transition"
            >
            <i data-lucide="arrow-left" class="h-4 w-4 mr-2"></i> Back
        </a>

        <button
        type="submit"
        class="bg-blue-600 text-white px-6 py-3 rounded-md hover:bg-blue-700 transition flex items-center"
        >
        <i data-lucide="save" class="h-4 w-4 mr-2"></i> Save Changes
    </button>
</div>

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

<script nonce="<%= nonce %>">
    document.getElementById('update-profile-form').addEventListener('submit', async function(e) {
        e.preventDefault();

        const fullName         = document.getElementById('fullName').value.trim();
        const email            = document.getElementById('email').value.trim();
        const phone            = document.getElementById('phone').value.trim();
        const gender           = document.getElementById('gender').value;
        const race             = document.getElementById('race').value.trim();
        const idNumber         = document.getElementById('idNumber').value.trim();
        const address          = document.getElementById('address')?.value?.trim() || '';
        const dateOfBirth      = document.getElementById('dateOfBirth').value;
        const institution      = document.getElementById('institution').value.trim();
        const qualification    = document.getElementById('qualification').value.trim();
        const guardianName     = document.getElementById('guardianName').value.trim();
        const guardianContact  = document.getElementById('guardianContact').value.trim();
        const disabilityStatus = document.getElementById('disabilityStatus').checked;

        // 🔍 Validation
        if (!fullName || !email) {
            return Swal.fire({ icon: 'warning', title: 'Missing Info', text: 'Full name and email are required.' });
        }

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return Swal.fire({ icon: 'error', title: 'Invalid Email', text: 'Enter a valid email address.' });
        }

        if (phone && !/^\+?\d{10,15}$/.test(phone.replace(/\s/g, ''))) {
            return Swal.fire({ icon: 'error', title: 'Invalid Phone', text: 'Phone number must be 10–15 digits.' });
        }

        if (idNumber && !/^\d{13}$/.test(idNumber)) {
            return Swal.fire({ icon: 'error', title: 'Invalid ID', text: 'ID Number must be 13 digits.' });
        }

        if (dateOfBirth && new Date(dateOfBirth) > new Date()) {
            return Swal.fire({ icon: 'error', title: 'Invalid DOB', text: 'Date of Birth cannot be in the future.' });
        }

        // 🔐 Retrieve token
        const token = localStorage.getItem('jwtToken');
        if (!token) {
            return Swal.fire({ icon: 'error', title: 'Not Authenticated', text: 'Please log in to update your profile.' });
        }

        try {
            const response = await api.put('/api/v1/users/profile', {
                fullName,
                email,
                phone,
                gender,
                race,
                idNumber,
                address,
                dateOfBirth,
                institution,
                qualification,
                guardianName,
                guardianContact,
                disabilityStatus
            });

            Swal.fire({
                icon: 'success',
                title: 'Profile Updated',
                text: response.data.message || 'Your profile has been updated successfully!',
                timer: 2500,
                showConfirmButton: false
            });

        } catch (err) {
            console.error('Profile update error:', err);
            const msg = err.response?.data?.message || 'Failed to update profile.';
            Swal.fire({ icon: 'error', title: 'Update Failed', text: msg });
        }
    });

    lucide.createIcons();
</script>
