function formatCurrency(number) {
    // Chuyển đổi số thành chuỗi và ngăn cách hàng nghìn bằng dấu phẩy
    let formattedNumber = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    // Thêm ký hiệu tiền tệ "VNĐ" vào cuối chuỗi
    formattedNumber += " VNĐ";
    return formattedNumber;
}
/*
 * Search func
 */
function Search(task, params){
	this.task = task;
	this.params = params;
	
	switch(task){
            
		case 'searchAct':
            searchAct();
			break;
        case 'searchClear':
            searchClear();
            break;
        case 'loadMore':
            loadMore();
            break;
        
        case 'courseDetail':
            var idCourse = params;
            courseDetail();
            break;
        case 'courseRegister':
            var idCourse = params;
            courseRegister();
            break;
        case 'courseRegister_popup_selectEB':
            courseRegister_popup_selectEarlyBird();
            break;
        case 'courseRegister_popup_selectDC':
            courseRegister_popup_selectDiscountCode();
            break;
        case 'courseRegister_popup_applyDC':
            courseRegister_popup_applyDiscountCode();
            break;
        case 'courseRegister_popup_handleKeyUp':
            courseRegister_popup_handleKeyUp();
            break;
        case 'courseRegister_popup_submitRegister':
            courseRegister_popup_submitRegister();
            break;
        case 'courseRegister_popup_close':
            courseRegister_popup_close();
            break;
        case 'triggerClickUploadBtn':
            courseRegister_triggerClickUploadBtn();
            break;
        case 'doUploadAttachFile':
            courseRegister_doUploadAttachFile();
            break;
        case 'courseMentorRegister':
            courseMentorRegister();
            break;
        case 'courseDetail_gotoReviewsTab':
            $('#tab-check').click();
            $('html, body').animate({
                scrollTop: $("#tab-check").offset().top
            }, 150);
            break;
        case 'courseDetail_gotoMentorTab':
            $('#tab-mentor').click();
            $('html, body').animate({
                scrollTop: $("#tab-mentor").offset().top
            }, 150);
            break;
            
            
        case 'activityDetail':
            var idActivity = params;
            activityDetail();
            break;
        case 'activityRegister':
            var idActivity = params;
            activityRegister();
            break;
        case 'activityMentorRegister':
            activityMentorRegister();
            break;
        case 'goMenteeHome':
            //location.href = params;
            openLink( params );
            break;
            
        case 'loginCourse':
            var idCourse = params;
            loginCourse();
            break;
        case 'loginActivity':
            var idActivity = params;
            loginActivity();
            break;
        
        case 'goBack':
            window.history.back();
            break;
        case 'chatWithUserNotLogin':
             chatWithUserNotLogin();
             break;
        
            
        // ViewCount
        case 'viewcountCourse':
            var idCourse = params;
            viewCountCourse(idCourse);
            break;
        case 'viewcountActivity':
            var idActivity = params;
            viewCountActivity(idActivity);
            break;
            
	}
    
    function searchAct() {
        if ($("#txtKeyword").val() == "" ) {
            $("#txtKeyword").focus();
        }
        else {
            var url = path + "/index.php?p=homep&keyword=" + encodeURIComponent( $("#txtKeyword").val() );
            //location.href = url;
            openLink( url );
        }
    }
    
    function searchClear() {
        $("#txtKeyword").val("");
        $("#txtKeyword").focus();
    }
    
    function loadMore() {
        $("div.search__list:hidden").slice(0, 10).slideDown();
        if ($("div.search__list:hidden").length == 0) {
            $("#loadMore").fadeOut('slow');
        }
    }
    
    /** Course */
    function courseDetail() {
        viewCountCourse(idCourse);
        //location.href = path + "/detail.php?p=coursedetail&id=" + idCourse;
        openLink( path + "/detail.php?p=coursedetail&id=" + idCourse );
    }
    function courseRegister() {
        let courseFee = $('#hideCourseFee').val();
        if (courseFee == "" || courseFee == -1) {
            courseMenteeRegister();
        }
        else {
            $('#div_course_register_popup').show().css('display', 'flex');
        }
    }
    /** courseMenteeRegister - free */
    function courseMenteeRegister() {
        $('#regcourse-waiting-load').show();
        
        var pars = 'task=courseMenteeRegister';
        pars += '&idCourse=' + idCourse;
        var url = path + '/searchAjax.php';
        $.ajax({
            url: url,
            data: pars,
            type: 'GET',
            success: function(response) {
               var result = JSON.parse(response);
               if (result["status"] == "Success") {
                    Swal.fire({
                      icon: 'success',
                      html: result["dialogForm"],
                      allowOutsideClick: false,
                      didDestroy: function () {
                        //location.href = result["path"];
                        openLink( result["path"] );
                      }
                    });
               }
               else if (result["status"] == "ErrCoMentor") {
                   Swal.fire({
                     icon: 'error',
                     html: "Bạn không thể đăng ký khoá học này.
Bạn là giảng viên hoặc đồng giảng viên của khoá học này.",
                     allowOutsideClick: false,
                     didDestroy: function () {
                     }
                   });
               }
               else {
                    Swal.fire({
                      icon: 'error',
                      html: "Đăng ký không thành công.
Vui lòng đăng ký lại.",
                      allowOutsideClick: false,
                      didDestroy: function () {
                        location.reload();
                      }
                    });
               }
               $('#regcourse-waiting-load').hide();
            },
            error: function(zhr){
                //alert("Error!");
            }
        });
    }
    function courseMentorRegister() {
        /*Swal.fire({
          icon: 'warning',
          html: 'Bạn đang đăng nhập tài khoản Giáo viên.\nBạn cần Đăng Nhập/Đăng Ký tài khoản Học viên trên MentorLinks. Sau đó hãy đăng ký khoá học.'
        });
        return;*/
    }
    function courseRegister_popup_selectEarlyBird() {
        let discount_fee = $('#hide_discount_price_eb').val();
        $('#hide_discount_fee').val(discount_fee);
        courseRegister_popup_updateDiscountForm();
        $('#div_discount_code').hide();
        $('#error_apply_discount_code').hide();
    }
    function courseRegister_popup_selectDiscountCode() {
        $('#txt_discount_code').val('');
        $('#hide_discount_code_val').val('');
        $('#hide_discount_price_dc').val(0);
        let discount_fee = $('#hide_discount_price_dc').val();
        $('#hide_discount_fee').val(discount_fee);
        let fee_total = $('#hide_fee_total').val();
        let fee_paid = fee_total - discount_fee;
        
        courseRegister_popup_updateDiscountForm();
        $('#span_original_price').html( formatCurrency(fee_total) );
        $('#span_paid_price').html( formatCurrency(fee_paid) );
        $('#div_discount_code').show();
    }
    function courseRegister_popup_applyDiscountCode() {
        let discount_code = $('#txt_discount_code').val();
        if (discount_code == "") {
            $('#error_apply_discount_code').html("Vui lòng nhập mã giảm giá.");
            $('#error_apply_discount_code').show();
            return;
        }
        var pars = 'task=courseMenteePreRegister_CheckDiscountCode';
        pars += '&idCourse=' + $('#hideIdCourse').val();
        pars += '&discount_code=' + discount_code;
        pars += '&fee_total=' + $('#hide_fee_total').val();
        var url = path + '/searchAjax.php';
        $.ajax({
            url: url,
            data: pars,
            type: 'GET',
            success: function(response) {
                //console.log(response);
                var result = JSON.parse(response);
                if (result["status"] == "Error") {
                    if (result["status_type"] == "EmptyNumber") {
                        $('#error_apply_discount_code').html("Xin lỗi! Số lượng mã giảm giá này đã hết.");
                        $('#error_apply_discount_code').show();
                    }
                    else { //Invalid
                        $('#error_apply_discount_code').html("Rất tiếc! Không thể tìm thấy mã giảm giá này.");
                        $('#error_apply_discount_code').show();
                    }
                    return;
                }
                else {
                    $('#hide_discount_code_val').val(discount_code);
                    let discount_fee = result["discount_fee"];
                    $('#hide_discount_price_dc').val(discount_fee);
                    $('#hide_discount_fee').val(discount_fee);
                    let fee_total = $('#hide_fee_total').val();
                    let fee_paid = fee_total - discount_fee;
                    
                    courseRegister_popup_updateDiscountForm();
                    $('#span_original_price').html( formatCurrency(fee_total) );
                    $('#span_paid_price').html( formatCurrency(fee_paid) );
                    $('#error_apply_discount_code').html("Tiết kiệm: " + formatCurrency(discount_fee));
                    $('#error_apply_discount_code').show();
                    return;
                }
            },
            error: function(zhr){
                //alert("Error!");
            }
        });
    }
    function courseRegister_popup_handleKeyUp() {
        $('#hide_discount_code_val').val("");
        
        $('#hide_discount_price_dc').val(0)
        let discount_fee = $('#hide_discount_price_dc').val();
        $('#hide_discount_fee').val(discount_fee);
        let fee_total = $('#hide_fee_total').val();
        let fee_paid = fee_total - discount_fee;
        courseRegister_popup_updateDiscountForm();
        $('#span_original_price').html( formatCurrency(fee_total) );
        $('#span_paid_price').html( formatCurrency(fee_paid) );
        $('#error_apply_discount_code').hide();
    }
    function courseRegister_popup_updateDiscountForm() {
        let fee_total = $('#hide_fee_total').val();
        let discount_fee = $('#hide_discount_fee').val();
        let fee_paid = fee_total - discount_fee;
        $('#hide_fee_paid').val(fee_paid);
        $('#span_discount_fee').html( '-' + formatCurrency(discount_fee) );
        $('#span_fee_paid').html( formatCurrency(fee_paid) );
        $('#hide_discount_fee').val(discount_fee);
    }
    function courseRegister_popup_submitRegister() {
        let idCourse = $('#hideIdCourse').val();
        let fee_total = $('#hide_fee_total').val();
        let discount_fee = $('#hide_discount_fee').val();
        //
        var feeTypeRadio = document.getElementsByName('fee-type');
        var fee_type_selected;
        for (var i = 0; i < feeTypeRadio.length; i++) {
            if (feeTypeRadio[i].checked) {
                fee_type_selected = feeTypeRadio[i].value;
                break;
            }
        }
        //
        var discount_code = "";
        if (fee_type_selected == "DC") {
            discount_code = $('#hide_discount_code_val').val();
        }
        //
        var discount_data = {};
        discount_data["fee_type"] = fee_type_selected;
        discount_data["total_fee"] = fee_total;
        discount_data["discount_code"] = discount_code;
        discount_data["discount_fee"] = discount_fee;
        action_submitCourseMenteeRegister(discount_data, idCourse);
    }
    function action_submitCourseMenteeRegister(discount_data, idCourse) {
        $('#div_course_register_popup').hide();
        $('#regcourse-waiting-load').show();
        
        var pars = 'task=courseMenteeRegister_discount';
        pars += '&discount_data=' + JSON.stringify(discount_data);
        pars += '&idCourse=' + idCourse;
        var url = path + '/searchAjax.php';
        $.ajax({
            url: url,
            data: pars,
            type: 'GET',
            success: function(response) {
               // console.log(response);
               var result = JSON.parse(response);
               if (result["status"] == "Success") {
                    Swal.fire({
                      icon: 'success',
                      html: result["dialogForm"],
                      allowOutsideClick: false,
                      didDestroy: function () {
                        //location.href = result["path"];
                        openLink( result["path"] );
                      }
                    });
               }
               else if (result["status"] == "ErrCoMentor") {
                   Swal.fire({
                     icon: 'error',
                     html: "Bạn không thể đăng ký khoá học này.
Bạn là giảng viên hoặc đồng giảng viên của khoá học này.",
                     allowOutsideClick: false,
                     didDestroy: function () {
                     }
                   });
               }
               else {
                    Swal.fire({
                      icon: 'error',
                      html: "Đăng ký không thành công.
Vui lòng đăng ký lại.",
                      allowOutsideClick: false,
                      didDestroy: function () {
                        location.reload();
                      }
                    });
               }
               $('#regcourse-waiting-load').hide();
            },
            error: function(zhr){
                //alert("Error!");
            }
        });
    }
    function courseRegister_popup_close() {
        $('#div_course_register_popup').hide();
    }
    //
    function courseRegister_triggerClickUploadBtn() {
        $("#fee_upload_file").trigger("click");
    }
    //
    function courseRegister_doUploadAttachFile() {
        let idCourse = $('#hideIdCourse').val();
        var input = document.getElementById('fee_upload_file');
        if (!input.files) {
            Swal.fire(
                'Failure',
                'The browser does not support uploading this file.',
                'error'
            );
        } else if (!input.files[0]) {
            Swal.fire(
                'Failure',
                'Vui lòng chọn tập tin (image).',
                'error'
            );
        } else {
            $('#regcourse-waiting-load').show();
            var file = input.files[0];
            if (file.size > 10000000) {
                Swal.fire(
                    'Failure',
                    'Vui lòng chọn một tập tin có kích thước <= 10Mb.',
                    'error'
                );
                //Reset file choosen
                $(e).val(null);
                //
                $("#regcourse-waiting-load").hide();
            } else {
                //Upload
                var fd = new FormData();
                fd.append('file', file);
                fd.append('idCourse', idCourse);
                var url = path + '/feeUploadFileAjax.php';
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: fd,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        // console.log(response);
                        const response_json = JSON.parse(response);
                        if (parseInt(response_json.status) == 0) {
                            let img_url = response_json.img_url;
                            let html = `
`;
                            $('#div_payment_bill_img').html(html);
                        } else {
                            let html = `Lỗi upload file.`;
                            $('#div_payment_bill_img').html(html);
                        }
                        $('#regcourse-waiting-load').hide();
                    },
                    error: function(zhr){
                        //alert("Error!");
                    }
                });
            }
        }
    }
    
    
    /** Activity */
    function activityDetail() {
        viewCountActivity(idActivity);
        //location.href = path + "/detail.php?p=activitydetail&id=" + idActivity;
        openLink( path + "/detail.php?p=activitydetail&id=" + idActivity );
    }
    function activityRegister() {
        Booked('activityBooked', idActivity);
    }
    function activityMentorRegister() {
        /*Swal.fire({
          icon: 'warning',
          html: 'Bạn đang đăng nhập tài khoản Giáo viên.\nBạn cần Đăng Nhập/Đăng Ký tài khoản Học viên trên MentorLinks. Sau đó hãy đăng ký khoá học.'
        });
        return;*/
    }
    
    function loginCourse() {
        var pars = 'task=loginCourse';
        pars += '&idCourse=' + idCourse;
        var url = path + '/searchAjax.php';
        $.ajax({
            url: url,
            data: pars,
            type: 'GET',
            success: function(response) {
               Swal.fire({
                 icon: 'warning',
                 html: 'Vui lòng đăng nhập hệ thống
trước khi đăng ký khoá học.',
                 allowOutsideClick: false,
                 didDestroy: function () {
                    //location.href = response;
                    openLink( response );
                 }
               });
            },
            error: function(zhr){
                //alert("Error!");
            }
        });
    }
    function loginActivity() {
        var pars = 'task=loginActivity';
        pars += '&idActivity=' + idActivity;
        var url = path + '/searchAjax.php';
        $.ajax({
            url: url,
            data: pars,
            type: 'GET',
            success: function(response) {
               //location.href = response;
               openLink( response );
            },
            error: function(zhr){
                //alert("Error!");
            }
        });
    }
    
    
    function chatWithUserNotLogin() {
        Swal.fire({
          icon: 'warning',
          html: 'Vui lòng Đăng Nhập tài khoản trên MentorLinks.
Sau đó hãy nhắn tin với Giáo viên.'
        });
        return;
    }
    
    
    /** View Count */
    function viewCountCourse(idCourse) {
        var pars = 'task=viewCountCourse';
        pars += '&idCourse=' + idCourse;
        var url = path + '/searchAjax.php';
        $.ajax({
            url: url,
            data: pars,
            type: 'GET',
            success: function(response) {
               //
            },
            error: function(zhr){
                //alert("Error!");
            }
        });
    }
    
    function viewCountActivity(idActivity) {
        var pars = 'task=viewCountActivity';
        pars += '&idActivity=' + idActivity;
        var url = path + '/searchAjax.php';
        $.ajax({
            url: url,
            data: pars,
            type: 'GET',
            success: function(response) {
               //
            },
            error: function(zhr){
                //alert("Error!");
            }
        });
    }
    
} //Search