$(function () {

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

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


    // ============================================================
    // NIC option toggle
    // ============================================================
    $('input[name="nicOpt"]').on('change', function () {
        $('#nicOptFeedback').addClass('d-none');
        $('#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); }
    });

    // ============================================================
    // Get Next Reg No for Darja
    // ============================================================
    window.countRegNum = function (darjaSno) {
        if (!darjaSno) return;
        const url = 'AjaxPhp/getRegNumber.php';
        const prefix = $('#registrationNo').data('hijri-prefix') || '';
        $.post(url, { darja_sno: darjaSno }, function (result) {
            if (result) {
                const num = result.trim();
                $('#registrationNo').val(prefix + num);
            }
        });
    };

    // ============================================================
    // Check registration number
    // ============================================================
    $('#checkRegNoBtn').on('click', function (e) {
        e.preventDefault();
        const num = $('#registrationNo').val().trim();
        if (!num) return;
        const url = 'AjaxPhp/isExistsRegNum.php';
        $.post(url, { num: num }, function (result) {
            $('#regNoMsg').html(result);
        });
    });

    // ============================================================
    // -------- PHOTO: Webcam capture (MediaDevices API) ---------
    // ============================================================
    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) {
            Swal.fire({
                icon: 'warning',
                title: 'کیمرہ دستیاب نہیں',
                text: 'سیکیورٹی وجوہات کی بنا پر براہ راست کیمرہ کھڑکی یہاں نہیں کھل سکتی، لیکن آپ تصویر لے سکتے ہیں۔ ڈیوائس کا اپنا کیمرہ کھل جائے گا۔',
                confirmButtonText: 'ٹھیک ہے'
            }).then(() => {
                $('#photoUpload').trigger('click');
            });
            return;
        }

        if (stream) { stream.getTracks().forEach(t => t.stop()); }
        
        currentCameraId = deviceId;
        const constraints = {
            video: deviceId ? { deviceId: { exact: deviceId } } : { facingMode: 'user' }
        };
        
        try {
            stream = await navigator.mediaDevices.getUserMedia(constraints);
            const video = $('#videoFeed')[0];
            video.srcObject = stream;
            
            // Mirror effect if it's the front camera
            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', function () {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            $('#photoUpload').attr('capture', 'environment').trigger('click');
            return;
        }
        $('#cameraContainer').removeClass('d-none');
        $('#photoActionBtns .btn:first').addClass('d-none');
        startCamera(null);
    });

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

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

    $('#snapBtn').on('click', function () {
        const video = $('#videoFeed')[0];
        if (video.readyState < 2) {
            Swal.fire('انتظار کریں', 'کیمرہ لوڈ ہو رہا ہے...', 'info');
            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');
        
        // Apply mirror if necessary
        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);
        $('#closeCameraBtn').trigger('click');
    });

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

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

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

    // Reset button also clears photo
    $('#btnReset').on('click', function () {
        $('#captureCanvas').addClass('d-none');
        $('#regNoMsg').html('');
        $('#stdNicWrap, #guirdianNicWrap, #formBWrap').addClass('d-none');
        $('#formAlert').html('');
    });

    // ============================================================
    // AJAX Submit
    // ============================================================
    $('#registrationForm').on('submit', function (e) {
        e.preventDefault();

        // Custom check for NIC selection
        if (!$('input[name="nicOpt"]:checked').length) {
            $('#nicOptFeedback').removeClass('d-none');
        }

        // Bootstrap validation
        if (!this.checkValidity()) {
            this.classList.add('was-validated');
            $('html, body').animate({ scrollTop: $('.is-invalid, :invalid').first().offset().top - 80 }, 400);
            return;
        }

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

        // Build payload
        const payload = {
            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(),
            admissionNo: $('#admissionNo').val(),
            registrationNo: $('#registrationNo').val(),
            isLocal: $('input[name="isLocal"]:checked').val() || '0',
            nicOpt: $('input[name="nicOpt"]:checked').val() || '0',
            stdNic: $('#stdNic').val(),
            guirdianNic: $('#guirdianNic').val(),
            formB: $('#formB').val(),
            photoBase64: $('#photoBase64').val(),
        };

        $.ajax({
            url: 'APIs/saveRegistration.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({
                        icon: 'success',
                        title: 'کامیابی',
                        text: res.message,
                        confirmButtonText: 'ٹھیک ہے'
                    }).then(() => {
                        $('#registrationForm')[0].reset();
                        $('#clearPhotoBtn').trigger('click');
                        $('#formAlert').html('');
                        // Update counter
                        const cur = parseInt($('#tStds').text()) || 0;
                        $('#tStds').text(cur + 1);
                        // Update registration number
                        const prefix = $('#registrationNo').data('hijri-prefix') || '';
                        $.get('APIs/getNextRegNo.php', function (d) {
                            if (d.nextRegNo) $('#registrationNo').val(prefix + d.nextRegNo);
                        });
                    });
                } else {
                    $('#formAlert').html(
                        `<div class="alert alert-danger alert-dismissible fade show" role="alert">
							<i class="bi bi-exclamation-triangle-fill me-2"></i>${res.message}
							<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
						 </div>`
                    );
                    $('html, body').animate({ scrollTop: 0 }, 300);
                }
            },
            error: function (xhr) {
                btn.prop('disabled', false).html('<i class="bi bi-save me-2"></i>محفوظ کیجئے');
                let msg = 'سرور پر خرابی آئی۔ دوبارہ کوشش کریں۔';
                try { msg = JSON.parse(xhr.responseText).message || msg; } catch (e) { }
                $('#formAlert').html(
                    `<div class="alert alert-danger alert-dismissible fade show" role="alert">
						<i class="bi bi-exclamation-triangle-fill me-2"></i>${msg}
						<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
					 </div>`
                );
                $('html, body').animate({ scrollTop: 0 }, 300);
            }
        });
    });

}); // end ready