var silent_post_test_url="https://thisisud.com/dashboard/ubCheckOutCallBack.php";
// var ub_checkout_url="https://ubfoundation.buffalo.edu/test/checkout/index.php";
var ub_checkout_url="https://ubfoundation.buffalo.edu/checkout/index.php";
var return_url = "https://thisisud.com/dashboard/myProjects.php";
var service_type_code="7700";
var ubf_account="9316204381";
var site_code="1290";

var currentMemberShip = localStorage.getItem("currentMemberShip");
var myData = localStorage.getItem("memberShipCat");
var parsedData = JSON.parse(myData);
var user_data = localStorage.getItem("user_data");
var parsedUserData = JSON.parse(user_data);

var bilingDate = localStorage.getItem("billingInfo");
bilingDate = JSON.parse(bilingDate);

var years = localStorage.getItem("years");
var amountDue = localStorage.getItem("total_amount_due");

var dateIfUpgradedTodayOrYears = localStorage.getItem("dateIfUpgradedTodayOrYears");
console.log(dateIfUpgradedTodayOrYears);

supporter = {
    'memberShipType':'Supporter',
    'benefits':['Access all solutions, drawings & figures','Access all design resources',
                'Create 1 project/year & access printable scorecard', '1 user/project', 'Submit projects for pre-certification, & isUD Certification with on-site audit',
                '20% discount on re-certification if subscription is active for all 5 years'],
    'noofProjects':'1',
    'userAccounts':'1', 
    'costPerYear':'$500/year',
    'totalCost':'500/year',
    'years':'1',
};

innovator = {
    'memberShipType':'Innovator',
    'benefits':['Access all solutions, drawings & figures','Access all design resources',
                'Create 2 projects/year & access printable scorecard', 'Up to 3 users/project', 'Submit projects for pre-certification,& isUD Certification with on-site audit',
                '20% discount on re-certification if subscription is active for all 5 years',
                'Access to free and discounted online course'],
    'noofProjects':'2',
    'userAccounts':'3', 
    'costPerYear':'$1000/year',
    'totalCost':'1000/year',
    'years':'1',
};


$(document).ready(function () {
    
    if(currentMemberShip == "free"){
        $('#membership-level').html(parsedData.memberShipType.split(" ")[0]);

        // if(parsedData.years>1){
        //     $('#years').html(parsedData.years+' '+'years');
        // }else{
        //     $('#years').html(parsedData.years+' '+'year');
        // }

        var startDate = GetStartDate();
        var endDate = GetEndDate(parsedData.years);
        timediff = dateDiff(new Date(startDate.year, startDate.month, startDate.day+2), new Date(endDate.year, endDate.month, endDate.day));
        var time ='';

        if(timediff.years > 0){
            time+= '  ' + timediff.years;
            time+='  Years';
        }
        if(timediff.months > 0){
            time+= '  ' + timediff.months;
            time+='  Months';
        }
        if(timediff.days > 0){
            time+= '  ' + timediff.days;
            time+='  Days';
        }
        startDate = startDate.month + "/" + startDate.day + "/" + startDate.year + "</b>";
        endDate = endDate.month + "/" + endDate.day + "/" + endDate.year + "</b>";

        $('#start-date').html(startDate);
        $('#end-date').html(endDate);
        $('#years').html(time);
        $('#amount-due').html('(Total:$'+parsedData.totalCost+')');
        $('#benefit-type').text(parsedData.memberShipType+" "+"Benefits");
        UpdateMemberShipBenefitsList(parsedData);
    }else{
        $('#membership-level').html(bilingDate["item_name"].split(" ")[1]);

        if(years > 1){
            $('#years').html(years+' '+'years');
        }else{
            $('#years').html(years+' '+'year');
        }

        var startDate = GetStartDate();
        var endDate = dateIfUpgradedTodayOrYears;
        startDate = "0"+startDate.month + "/" + startDate.day + "/" + startDate.year + "</b>";
        //endDate = endDate.month + "/" + endDate.day + "/" + endDate.year + "</b>";

        $('#start-date').html(startDate);
        $('#end-date').html(endDate);
        $('#amount-due').html('(Total:$'+amountDue+')');
        $('#benefit-type').text(bilingDate["item_name"]+" "+"Benefits");

        if(bilingDate["item_name"] == "isUD Supporter Membership"){
            UpdateMemberShipBenefitsList(supporter);
        }else{
            UpdateMemberShipBenefitsList(innovator);
        }
        
    }
    attachOverviewBtnEventListener();
});

function attachOverviewBtnEventListener(){
    $('#payNow').prop("disabled", true);
    $("#payNow").css("color","black");

    $(".go-back").click(function(ev){
        if(currentMemberShip == "free"){
            window.location.replace("profileMemberShip.php");
        }else{
            window.location.replace("profileMemberShipAfterReg.php");
        }
    });

    $(".pay-now").click(function(ev){
        if(currentMemberShip == "free"){
            var ub_checkout_form = $('<form></form>');
            var attributes_map = new Object;
            attributes_map["add"] = "1";
            attributes_map["item_name"] = "isUD"+" "+parsedData.memberShipType+" "+"Membership";
            attributes_map["service_type_code"] = service_type_code;
            attributes_map["site_code"] = site_code;
            attributes_map["ubf_account"] = ubf_account;
            attributes_map["return_url"] = return_url;
            attributes_map["quantity"] = "1";
            attributes_map["silent_post_test"] = silent_post_test_url;
            attributes_map["amount"] = parsedData.totalCost;
            attributes_map["custom[email_id_in_db]"] = parsedUserData.email_id;
            // For pre populating billing information in UBF checkout page - Start
            attributes_map["billing_first_name"] = "";
            attributes_map["billing_last_name"] = "";
            attributes_map["billing_address"] = "";
            attributes_map["billing_city"] = "";
            attributes_map["billing_state"] = "";
            attributes_map["billing_zip"] = "";
            attributes_map["billing_country"] = "";
            attributes_map["billing_email"] = "";
            attributes_map["billing_phone"] = "";
            attributes_map["custom[plan_type]"] = "free";
            // // For pre populating billing information in UBF checkout page - End
            ub_checkout_form.attr("method", "post");
            ub_checkout_form.attr("action", ub_checkout_url);

            $.each(attributes_map, function(key, value) {
            var field = $('<input></input>');
            field.attr("type", "hidden");
            field.attr("name", key);
            field.attr("value", value);

            ub_checkout_form.append(field);
            });
            $(document.body).append(ub_checkout_form);
            ub_checkout_form.submit();
            return;
        }else{
            var ub_checkout_form = $('<form></form>');
            ub_checkout_form.attr("method", "post");
            ub_checkout_form.attr("action", ub_checkout_url);
            $.each(bilingDate, function(key, value) {
            var field = $('<input></input>');
            console.log("Adding : "+key);
            field.attr("type", "hidden");
            field.attr("name", key);
            field.attr("value", value);
            ub_checkout_form.append(field);
            });
            $(document.body).append(ub_checkout_form);
            ub_checkout_form.submit();
        }
    });

    $('#terms-and-conditions-check').mousedown(function() {
        if (!$(this).is(':checked')) {
            $('#payNow').prop("disabled", false);
            $("#payNow").css("color","white");
        }else{
            $('#payNow').prop("disabled", true);
            $("#payNow").css("color","black");
        }
    });
}

var UpdateMemberShipDetailsList = function (elem)
{
    var todayDate = GetTodayDate();

    var cost = "Cost: "+elem.Cost
    var start_date = "Start Date: "+"<b>" + todayDate.month + "/" + todayDate.day + "/" + todayDate.year + "</b>";
    var end_date = "End Date: "+elem.cost;

    append_to_list(list_control,cost,elem.cost);
    append_to_list(list_control,start_date,GetTodayDate());
    append_to_list(list_control,end_date,elem.cost);
}

var UpdateMemberShipBenefitsList = function(elem) 
{ 

    var benefits_list_control = $('#id-ul-membership-benefits');

    benefits_list_control.empty();

    elem.benefits.map(item => {
        append_to_list(benefits_list_control,item,item);
    })

}

var append_to_list = function(list_control,display_str,check_str)
{
    if (check_str == "")
    {
        list_control.append('<li style="color:red">'+display_str+'</li>');
    }
    else
    {
        list_control.append('<li>'+display_str+'</li>');
    }
}

var GetStartDate = function () 
{
    var currentDate = new Date()
    var day = currentDate.getDate()
    var month = currentDate.getMonth() + 1
    var year = currentDate.getFullYear()
    // alert('startDate' + year+month+day);
    return {
        month,
        day,
        year
    }
}

var GetEndDate = function (years) 
{
    var expiryDate = new Date()
    expiryDate.setFullYear(parseInt(expiryDate.getFullYear()) + parseInt(years))
    if(leapYear(expiryDate.getFullYear())){
        expiryDate.setDate(expiryDate.getDate() + 1)
    }else{
        expiryDate.setDate(expiryDate.getDate()-1 + 1)
    }
    var day = expiryDate.getDate()
    var month = expiryDate.getMonth() + 1
    var year = expiryDate.getFullYear()
    // alert('EndDate' + year+month+day);
    return {
        month,
        day,
        year
    }
}

// var duration = function(startDate, endDate){
//     console.log('Hi');
//     dt1 = new Date(startDate);
//     dt2 = new Date(endDate);
//     var time =(dt2.getTime() - dt1.getTime()) / 1000;
//     var year  = Math.abs(Math.round((time/(60 * 60 * 24))/365.25));
//     var month = Math.abs(Math.round(time/(60 * 60 * 24 * 7 * 4)));
//     var days = Math.abs(Math.round(time/(3600 * 24)));
//     console.log("Year :- " + year + " Month :- " + month + " Days :-" + days);
//     return "Year :- " + year + " Month :- " + month + " Days :-" + days;
// }

var leapYear = function(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

function dateDiff(startdate, enddate) {
    alert('Moment');
    alert('startdate' +  startdate);
    alert('enddate' +  enddate);
    
    //define moments for the startdate and enddate
    var startdateMoment = moment(startdate);
    var enddateMoment = moment(enddate);

    if (startdateMoment.isValid() === true && enddateMoment.isValid() === true) {
      //getting the difference in years
      var years = enddateMoment.diff(startdateMoment, 'years');

      //moment returns the total months between the two dates, subtracting the years
      var months = enddateMoment.diff(startdateMoment, 'months') - (years * 12);

      //to calculate the days, first get the previous month and then subtract it
      startdateMoment.add(years, 'years').add(months, 'months');
      var days = enddateMoment.diff(startdateMoment, 'days')

    //   alert('typeof years' + typeof(years));
    //   alert('typeof months' + typeof(months));
    //   alert('typeof days' + typeof(days));

      return {
        years,
        months,
        days
    }

    }
    else {
      return undefined;
    }

  }

;