$(function () {

    // ============================================================
    // Input Masking
    // ============================================================
    $('#stdNic, #guirdianNic, #formB').mask('00000-0000000-0', { placeholder: "_____-_______-_" });
    $('#cellNo, #gurdianCellNo').mask('0000-0000000', { placeholder: "____-_______" });

    // ============================================================
    // Search Form Handler
    // ============================================================
    $('#searchForm').on('submit', function (e) {
        e.preventDefault();
        const regNo = $('#registrationNoSearch').val().trim();
        const darja = $('#darjaS').val();

        if (!regNo || !darja) {
            Swal.fire('توجہ', 'رجسٹریشن نمبر اور درجہ دونوں درج کریں', 'warning');
            return;
        }

        $.ajax({
            url: 'APIs/registrationUpdateForm.php',
            method: 'GET',
            data: { registrationNo: regNo, darja: darja },
            success: function (res) {
                if (res.success) {
                    populateForm(res.data);
                    $('#updateFormSection').removeClass('d-none');
                    // Scroll to form
                    $('html, body').animate({ scrollTop: $('#updateFormSection').offset().top - 20 }, 500);
                } else {
                    Swal.fire('ریکارڈ نہیں ملا', res.message, 'error');
                    $('#updateFormSection').addClass('d-none');
                }
            },
            error: function () {
                Swal.fire('خرابی', 'ڈیٹا حاصل کرنے میں کوئی مسئلہ پیش آیا', 'error');
            }
        });
    });

    function populateForm(d) {
        $('#sno').val(d.sno);
        $('#photoBase64').val(''); // Reset: empty means no change to photo
        $('#currentDarja').val(d.currentDarja);
        $('#stdName').val(d.stdName);
        $('#fatherName').val(d.fatherName);
        $('#nationality').val(d.nationality);
        $('#dob').val(d.dob);
        $('#qualification').val(d.qualification);
        $('#guirdianName').val(d.guirdianName);
        $('#cellNo').val(d.cellNo);
        $('#fatherProfession').val(d.fatherProfession);
        $('#gurdianCellNo').val(d.gurdianCellNo);
        $('#contact_email').val(d.contact_email);
        $('#permanentAddress').val(d.permanentAddress);
        $('#presentAddress').val(d.presentAddress);
        $('#guirdianNameAuth').val(d.guirdianNameAuth);
        $('#guirdianFNameAuth').val(d.guirdianFNameAuth);
        $('#guirdianSign').val(d.guirdianSign);
        $('#signNazim').val(d.signNazim);
        $('#relationShipWithGuirdian').val(d.relationShipWithGuirdian);
        $('#admissionDate').val(d.admissionDate);
        $('#dateEnd').val(d.dateEnd);
        $('#registrationNo').val(d.registrationNo);
        $('#darja').val(d.currentDarja);

        // Radio: isLocal
        if (d.isLocal == '1') $('#isLocal1').prop('checked', true);
        else $('#isLocal2').prop('checked', true);

        // NIC logic
        $('#stdNic, #guirdianNic, #formB').val('0').prop('required', false);
        $('#stdNicWrap, #guirdianNicWrap, #formBWrap').addClass('d-none');

        if (d.stdNic && d.stdNic != '0') {
            $('#nicOpt1').prop('checked', true);
            $('#stdNic').val(d.stdNic).prop('required', true);
            $('#stdNicWrap').removeClass('d-none');
        } else if (d.guirdianNic && d.guirdianNic != '0') {
            $('#nicOpt2').prop('checked', true);
            $('#guirdianNic').val(d.guirdianNic).prop('required', true);
            $('#guirdianNicWrap').removeClass('d-none');
        } else {
            $('#nicOpt3').prop('checked', true);
            $('#formB').val(d.formB).prop('required', true);
            $('#formBWrap').removeClass('d-none');
        }

        // Photo Preview
        if (d.stdPhoto) {
            setPhotoPreview('uploaded/' + d.stdPhoto);
        } else {
            clearPhotoPreview();
        }
    }

    // ============================================================
    // Update Form Handler
    // ============================================================
    $('#registrationForm').on('submit', function (e) {
        e.preventDefault();

        if (!this.checkValidity()) {
            this.classList.add('was-validated');
            return;
        }

        const btn = $('#btnSave');
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>محفوظ ہو رہا ہے...');

        const payload = {
            sno: $('#sno').val(),
            currentDarja: $('#currentDarja').val(),
            stdName: $('#stdName').val(),
            fatherName: $('#fatherName').val(),
            nationality: $('#nationality').val(),
            dob: $('#dob').val(),
            qualification: $('#qualification').val(),
            guirdianName: $('#guirdianName').val(),
            darja: $('#darja').val(),
            cellNo: $('#cellNo').val(),
            fatherProfession: $('#fatherProfession').val(),
            gurdianCellNo: $('#gurdianCellNo').val(),
            contact_email: $('#contact_email').val(),
            permanentAddress: $('#permanentAddress').val(),
            presentAddress: $('#presentAddress').val(),
            guirdianNameAuth: $('#guirdianNameAuth').val(),
            guirdianFNameAuth: $('#guirdianFNameAuth').val(),
            guirdianSign: $('#guirdianSign').val(),
            signNazim: $('#signNazim').val(),
            relationShipWithGuirdian: $('#relationShipWithGuirdian').val(),
            admissionDate: $('#admissionDate').val(),
            dateEnd: $('#dateEnd').val(),
            registrationNo: $('#registrationNo').val(),
            isLocal: $('input[name="isLocal"]:checked').val(),
            nicOpt: $('input[name="nicOpt"]:checked').val(),
            stdNic: $('#stdNic').val(),
            guirdianNic: $('#guirdianNic').val(),
            formB: $('#formB').val(),
            photoBase64: $('#photoBase64').val(),
        };

        $.ajax({
            url: 'APIs/registrationUpdateForm.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(payload),
            success: function (res) {
                btn.prop('disabled', false).html('<i class="bi bi-save me-2"></i>محفوظ کیجئے');
                if (res.success) {
                    Swal.fire('کامیابی', res.message, 'success');
                } else {
                    Swal.fire('خرابی', res.message, 'error');
                }
            },
            error: function () {
                btn.prop('disabled', false).html('<i class="bi bi-save me-2"></i>محفوظ کیجئے');
                Swal.fire('خرابی', 'سرور پر کوئی مسئلہ پیش آیا', 'error');
            }
        });
    });

    // ============================================================
    // UI Helpers (Synced with registration_form.js)
    // ============================================================

    $('#copyAddressBtn').on('click', function (e) {
        e.preventDefault();
        $('#presentAddress').val($('#permanentAddress').val());
    });

    $('input[name="nicOpt"]').on('change', function () {
        $('#stdNicWrap, #guirdianNicWrap, #formBWrap').addClass('d-none');
        $('#stdNic, #guirdianNic, #formB').prop('required', false);
        const v = this.value;
        if (v === '1') { $('#stdNicWrap').removeClass('d-none'); $('#stdNic').prop('required', true); }
        else if (v === '2') { $('#guirdianNicWrap').removeClass('d-none'); $('#guirdianNic').prop('required', true); }
        else if (v === '3') { $('#formBWrap').removeClass('d-none'); $('#formB').prop('required', true); }
    });

    // -------- PHOTO HANDLING (Robust Camera) ---------
    let stream = null;
    let currentCameraId = null;

    async function populateCameraList() {
        try {
            const devices = await navigator.mediaDevices.enumerateDevices();
            const videos = devices.filter(d => d.kind === 'videoinput');
            const sel = $('#cameraSource').empty();
            if (videos.length > 1) {
                sel.removeClass('d-none');
                videos.forEach((d, i) => {
                    sel.append($('<option>').val(d.deviceId).text(d.label || `Camera ${i + 1}`));
                });
                if (currentCameraId) sel.val(currentCameraId);
            } else {
                sel.addClass('d-none');
            }
        } catch (e) { /* ignore */ }
    }

    async function startCamera(deviceId) {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            $('#photoUpload').attr('capture', 'environment').trigger('click');
            return;
        }

        if (stream) { stream.getTracks().forEach(t => t.stop()); }
        
        currentCameraId = deviceId;
        const constraints = {
            video: deviceId ? { deviceId: { exact: deviceId } } : { facingMode: 'user' }
        };

        $('#cameraContainer').removeClass('d-none');
        $('#photoActionBtns .btn:first').addClass('d-none');

        try {
            stream = await navigator.mediaDevices.getUserMedia(constraints);
            const video = $('#videoFeed')[0];
            video.srcObject = stream;
            
            // Mirroring
            const isFront = !deviceId || (constraints.video.facingMode === 'user');
            if (isFront) $(video).css('transform', 'scaleX(-1)');
            else $(video).css('transform', 'scaleX(1)');

            video.play();
            await populateCameraList();
        } catch (err) {
            console.error("Camera error:", err);
            Swal.fire({
                icon: 'error',
                title: 'خرابی',
                html: `کیمرہ تک رسائی نہیں ہو سکی: ${err.message} <button type="button" class="btn btn-link p-0 ms-2" onclick="showCameraHelp()" title="مدد کے لیے یہاں کلک کریں"><i class="bi bi-question-circle-fill fs-5"></i></button>`,
                confirmButtonText: 'ٹھیک ہے'
            });
        }
    }

    $('#openCameraBtn').on('click', () => startCamera(null));

    $('#cameraSource').on('change', function () {
        startCamera(this.value);
    });

    $('#snapBtn').on('click', function () {
        const video = $('#videoFeed')[0];
        if (video.readyState < 2) return;

        const canvas = $('#captureCanvas')[0];
        const width = video.videoWidth || 640;
        const height = video.videoHeight || 480;
        
        canvas.width = width;
        canvas.height = height;
        const context = canvas.getContext('2d');
        
        // Mirroring in capture
        const isMirrored = $(video).css('transform').includes('matrix(-1');
        if (isMirrored) {
            context.translate(width, 0);
            context.scale(-1, 1);
        }

        context.drawImage(video, 0, 0, width, height);
        const dataUrl = canvas.toDataURL('image/jpeg', 0.9);
        setPhotoPreview(dataUrl, true);
        closeCamera();
    });

    $('#closeCameraBtn').on('click', closeCamera);

    function closeCamera() {
        if (stream) { stream.getTracks().forEach(t => t.stop()); stream = null; }
        $('#cameraContainer').addClass('d-none');
        $('#photoActionBtns .btn:first').removeClass('d-none');
    }

    $('#photoUpload').on('change', function () {
        const file = this.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = function (e) { setPhotoPreview(e.target.result, true); };
        reader.readAsDataURL(file);
    });

    function setPhotoPreview(src, isBase64 = false) {
        if (isBase64) $('#photoBase64').val(src);
        $('#photoPreview').html(`<img src="${src}" class="photo-preview-img" alt="طالب علم">`);
        $('#clearPhotoBtn').removeClass('d-none');
    }

    function clearPhotoPreview() {
        $('#photoBase64').val('CLEAR');
        $('#photoPreview').html('<i class="bi bi-person-fill photo-placeholder-icon"></i>');
        $('#photoUpload').val('');
        $('#clearPhotoBtn').addClass('d-none');
    }

    $('#clearPhotoBtn').on('click', clearPhotoPreview);

    // ============================================================
    // Delete & Struck Off Logic
    // ============================================================
    $('#btnDel').on('click', function () {
        const sno = $('#sno').val();
        Swal.fire({
            title: 'کیا آپ یقینی طور پر مٹانا چاہتے ہیں؟',
            text: "یہ عمل واپس نہیں لیا جا سکے گا!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'ہاں، مٹائیں!',
            cancelButtonText: 'کینسل'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('AjaxPhp/delStd.php', { stdSno: sno }, function () {
                    Swal.fire('مٹا دیا گیا!', 'طالب علم کا ریکارڈ مٹا دیا گیا ہے۔', 'success').then(() => {
                        location.reload();
                    });
                });
            }
        });
    });

    $('#btnKharij').on('click', function () {
        const sno = $('#sno').val();
        Swal.fire({
            title: 'کیا آپ خارج کرنا چاہتے ہیں؟',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'ہاں، خارج کریں',
            cancelButtonText: 'کینسل'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('AjaxPhp/stuctOff.php', { stdSno: sno }, function () {
                    Swal.fire('خارج کر دیا گیا', '', 'success').then(() => {
                        location.reload();
                    });
                });
            }
        });
    });

});
