$(document).ready( function(){

    // Get the id from the URL's query parameters
    var urlParams = new URLSearchParams(window.location.search);
    const lead_id = urlParams.get('id').trim();

    getLeadById(lead_id);


    // Use event delegation for dynamically added elements
    $('.lead_btn_group').on('click', '#btn_view_all_leads', function() {
        // Your code to redirect back
        window.location.href = 'all-leads.php';
    });


    $(document).on('change', '.lead_status_select', function(){

        // Get the selected option value
        const selected_status_id = $(this).val();

        if(selected_status_id == 6){
            $("#lead_email_label").append('<span class="required-mark lead_email_required_mark"> *</span>');
        }else{
            $(".lead_email_required_mark").css('display', 'none');   
        }
    });

    $('.lead_btn_group').on('click', '#btn_update_lead', function() {
        
        var selected_lead_status = $('.lead_status_select').val();
        var entered_lead_note = $('#text_lead_note').val().trim();
        var lead_email = $('#lead_email').val().trim();

        if(selected_lead_status == 6){ // 6 = completed

            // Check if the entered email is valid
            if (isValidEmail(lead_email)) {
                
                updateLeadRecord(lead_id, lead_email, selected_lead_status, entered_lead_note);
                
            }else{
                unsuccessPopup('Please Enter a Valid Email Address!');
                return;

            }
            
        }else if(selected_lead_status != 6 && lead_email.length > 0){
            
            // Check if the entered email is valid
            if (isValidEmail(lead_email)) {
                updateLeadRecord(lead_id, lead_email, selected_lead_status, entered_lead_note);

            }else{

                unsuccessPopup('Please Enter a Valid Email Address!');
                return;
                
            }
        
        }else if(selected_lead_status != 6 && lead_email == ''){
            updateLeadRecord(lead_id, lead_email, selected_lead_status, entered_lead_note);

        }

    });

    
});

function getLeadById(lead_id){

    $.ajax({
        type: 'GET',
        url: 'classes/LeadController.php', // Replace with the URL of your server-side script
        data: {'VIEW_LEAD':1, 'lead_id':lead_id},
        dataType: 'json', // Assuming the response is in JSON format
        success: function(data) {

            if(data.status == '1'){

                var resp = data.message[0];
                var lead_notes_arr = JSON.parse(data.message[0].all_notes);
                var note_arr_count = lead_notes_arr.length;
                var lead_status = '';

                if (resp.lead_status == 0) { // pending approval from center function
                    lead_status = '<span class="lead-pending">Pending</span>';
                }else if(resp.lead_status == 1){ // assigned to counselor
                    lead_status = '<span class="lead-assigned">Assigned</span>';
                }else if(resp.lead_status == 2){ // rejected by center function
                    lead_status = '<span class="lead-rejected">Rejected</span>';
                }else if(resp.lead_status == 3){ // not prefer to join.
                    lead_status = '<span class="lead-prospective">Not Prospective</span>';
                }else if(resp.lead_status == 4){ // convertible
                    lead_status = '<span class="lead-convertible">Convertible</span>';
                }else if(resp.lead_status == 5){ // future intakes
                    lead_status = '<span class="lead-future-intake">Future Intake</span>';
                }else if(resp.lead_status == 6){ // completed | pending list for register to system as a student
                    lead_status = '<span class="lead-completed">Completed</span>';
                }else if(resp.lead_status == 7){ // registered | register with the system as a student
                    lead_status = '<span class="lead-registered">Registered</span>';
                }


                //button permission based on lead status
                setButtonPermission(resp.lead_status);



                $('#lead_id').html(resp.lead_id);
                $('#lead_status').html(lead_status);
                $('#lead_first_name').html(resp.lead_first_name);
                $('#lead_last_name').html(resp.lead_last_name);
                $('#lead_pref_lang').html(resp.lead_pref_lang);
                $('#lead_source').html(resp.lead_source);
                $('#laad_phone_1').html(resp.lead_phone_1);
                $('#laad_phone_2').html(resp.lead_phone_2);
                $('#lead_email').val(resp.lead_email);
                $('#laad_campus').html(resp.campus_name);
                $('#laad_branch').html(resp.branch_name);
                $('#lead_address').html(resp.lead_address);
                $('#laad_created_date_time').html(resp.lead_created_date_time);
                $('#laad_updated_date_time').html(resp.lead_updated_date_time);

                if(note_arr_count > 0){
                    //show lead notes in table
                    lead_notes_arr.forEach((element, index) => {
                        
                        var note_row = 
                        '<tr>' +
                            '<td>' + ++index + '</td>' +
                            '<td><textarea class="lead_note_textarea" rows="3" readonly>'+ element.note_description +'</textarea></td>' +
                            '<td>'+ element.note_created_date_time +'</td>' +
                        '</tr>';

                        $('#lead_notes_body').append(note_row);
                    });
                    
                }else {
                    var note_row = 
                        '<tr><td colspan="3" class="text-center">Notes not available!</td></tr>';

                    $('#lead_notes_body').append(note_row);
                }

            }else {
                unsuccessPopup(data.message, 'all-leads.php');
            }

        },
        error: function() {
            unsuccessPopup('Failed Request!');
        }
    });

}

function successPopup(msg, customURL){
    Swal.fire({
        title: 'SUCCESS',
        text: msg,
        allowOutsideClick:false,
        allowEscapeKey:false,
        customClass: {
            popup: 'suc-pop',
            title: 'suc-pop-title',
            content: 'suc-pop-content',
            confirmButton: 'suc-pop-btn-ok'
        }
    }).then(okay => {
        if (okay) {
            if(customURL){
                window.location.href = customURL;
            }else{
                location.reload();
            }
        }
    });
}

function unsuccessPopup(msg, customURL){
    Swal.fire({
        title: 'UNSUCCESS',
        text: msg,
        allowOutsideClick:false,
        allowEscapeKey:false,
        customClass: {
            popup: 'unsuc-pop',
            title: 'unsuc-pop-title',
            confirmButton: 'unsuc-pop-btn-ok'
        }
    }).then(okay => {
        if (okay) {
            if(customURL){
                window.location.href = customURL;
            }
        }
    });
}

function hasNonEmptyId() {
    // Check if the 'id' parameter exists and is not empty
    return window.location.search.includes('id=') && window.location.search.split('id=')[1].length > 0;
}

function isValidEmail(email) {

    // Regular expression for basic email validation
    const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
    // const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function updateLeadRecord(lead_id, lead_email, selected_lead_status, entered_lead_note){

    if(lead_id != ''){

        if(entered_lead_note != ''){
            
            Swal.fire({
                title: 'ARE YOU SURE?',
                text: "Do you want to Update ?",
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, proceed it!',
                customClass: {
                    popup: 'confirm-pop',
                    title: 'confirm-pop-title'
                }
            }).then((result) => {
                if (result.isConfirmed) {

                    $.ajax({
                    type: 'POST',
                    url: 'classes/LeadController.php', // Replace with the URL of your server-side script
                    data: {'UPDATE_LEAD':1, 'lead_id':lead_id, 'lead_email':lead_email, 'selected_lead_status':selected_lead_status, 'entered_lead_note':entered_lead_note},
                    dataType: 'json', // Assuming the response is in JSON format
                    success: function(data) {
    
                        if(data.status == 1){
                            successPopup(data.message);
                        }else if(data.status == 0){
                            unsuccessPopup(data.message);
                        }
    
    
                    },
                    error: function() {
                        unsuccessPopup('Failed Request!');
                    }
                    });
                }
            });


            

        }else{
            unsuccessPopup('Please add a note!');
        }

    }else{
        unsuccessPopup('Invalid Request. Please Try Again!');
    }

}

function add_required_mark(lead_status){

    if(lead_status == 6){
        $("#lead_email_label").append('<span class="required-mark lead_email_required_mark"> *</span>');
    }else{
        $(".lead_email_required_mark").css('display', 'none');   
    }
    
}

function setButtonPermission(lead_status){

    var lead_btn_template = '';
    var lead_status_dropdown = '';
    var lead_note_textarea = '';


    if(lead_status == 6 || lead_status == 7) { // 6 = completed lead / 7 = registered lead
        
        lead_btn_template = 
        '<button class="btn btn-primary mt-md-0 mt-2" id="btn_view_all_leads"> <i class="fa fa-chevron-left"></i> Go back</button>';

    }else if(lead_status == 1 || lead_status == 3 || lead_status == 4 || lead_status == 5) { 
        // Lead Status: 1=Assigned / 3=NotProspective / 4=Convertible / 5=FutureIntakes
        lead_btn_template = 
        '<button class="btn btn-primary mt-md-0 mt-2" id="btn_view_all_leads"> <i class="fa fa-chevron-left"></i> Go back</button> ' +
        '<button class="btn btn-block btn-primary mt-md-0 mt-2" id="btn_update_lead">Update Lead</button>';
    
        // lead status dropdown
        lead_status_dropdown = 
        '<div class="col-md-12">' +
            '<strong><label>Lead Status </label></strong>' +
            '<select class="lead_status_select form-control" required="">' +

            '</select>' +
        '</div>';

        // lead note input
        lead_note_textarea = 
        '<div class="col-md-12">' +
            '<strong><label>Lead Note</label></strong>' +
            '<div class="col-md-12"><textarea class="form-control" id="text_lead_note" placeholder="Enter lead\'s note here..."></textarea></div>' +
        '</div>';


    }

    $('.lead_btn_group').html(lead_btn_template);
    $('.lead_status_group').html(lead_status_dropdown);
    $('.lead_note_group').html(lead_note_textarea);


    // load lead statuses to dropdown
    loadLeadStatusesToDropdown(lead_status);

    // add required by if lead status equal to 6 = completed
    add_required_mark(lead_status);

}

function loadLeadStatusesToDropdown(lead_status){

    // load leads statuses - start
    const leadStatuses = [
        { value: "1", label: "Assigned" },
        { value: "3", label: "Not Prospective" },
        { value: "4", label: "Convertible" },
        { value: "5", label: "Future Intake" },
        { value: "6", label: "Completed" }
    ];

    var lead_options = '';
    leadStatuses.forEach((status, index) => {
        if(lead_status == status.value){
            lead_options += '<option value='+ status.value +' selected>' + status.label + '</option>';
        }else{
            lead_options += '<option value='+ status.value +'>' + status.label + '</option>';
        }
    });

    $('.lead_status_select').html(lead_options);
    // load leads statuses - end

}