var purpose;
var vehicleType;
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();

$(document).ready(function() {

    $('#addExamDate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    });

    $('#addExamTime').timepicker({
        showMeridian: false,
        showSeconds: true,
        minuteStep: 1,
        secondStep: 1,
        icons: {
            up: 'fa fa-angle-up',
            down: 'fa fa-angle-down'
        }
    });

    $('#addExamDateModal').on('hidden.bs.modal', function() {
        $('#addExamFrm').trigger("reset");
    });

    $('#examDate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    });

    $('#examTime').timepicker({
        showMeridian: false,
        showSeconds: true,
        minuteStep: 1,
        secondStep: 1,
        icons: {
            up: 'fa fa-angle-up',
            down: 'fa fa-angle-down'
        }
    });

    $('#pay').on('change', function() {
        if (parseInt($('#pay').val()) > parseInt($('#remain').val())) {
            $('#pay').val('');
        }
    });
    $("#payFrm").submit(function() {
        if (parseInt($('#pay').val()) > parseInt($('#remain').val())) {
            $('#pay').val('');
            return false;
        }
    });

    $('.pay-date').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
    }).datepicker("setDate", 'now');

    $('#payTime').timepicker({
        showMeridian: false,
        showSeconds: true,
        minuteStep: 1,
        secondStep: 1,
        icons: {
            up: 'fa fa-angle-up',
            down: 'fa fa-angle-down'
        }
    });
    //$('#paymenyModal').modal({ show: true });

    $('#paymenyModal').on('hidden.bs.modal', function() {
        //$('#payFrm')[0].reset();
        $('#payFrm').trigger("reset");
        $('#paymentMethod').selectpicker('refresh');
    });

    $('#courseModal').on('hidden.bs.modal', function() {
        $('#courseFrm').trigger("reset");
        $('#course').selectpicker('refresh');
        $('#courseMethod').selectpicker('refresh');
        $('#newCourse').hide();
    });

    $('.purpose').on('change', function() {
        let purpose = $("input[name='purpose']:checked").val();
        if (purpose == 'เพิ่มประสบการณ์') {
            $('#examDiv').hide();
        } else {
            $('#examDiv').show();
        }
    });

    $('#course').on('change', function() {
        let curCourse = $('#currentCourse').val();
        var cost = $('#course').val().split('-');
        let newCourse = cost[0];
        let cal = cost[1];
        let price = new Intl.NumberFormat().format(cal);
        $('#newCoursePrice').html(price);
        //let paid = $('#paid').val();
        // if (parseInt(paid) > parseInt(cal)) {
        //     let x = parseInt(paid) - parseInt(cal);
        //     $('#cost').html('มียอดชำระเกินไว้ ' + new Intl.NumberFormat().format(x) + ' บาท');
        // } else if (parseInt(paid) < parseInt(cal)) {
        //     let x = parseInt(cal) - parseInt(paid);
        //     $('#cost').html('ต้องชำระเพิ่ม ' + new Intl.NumberFormat().format(x) + ' บาท');
        // } else {
        //     $('#cost').html('ไม่มียอดชำระเพิ่ม');
        // }
        // $('#totalCost').val() = cal;

        let purpose = $("input[name='purpose']:checked").val();
        if (purpose == 'เพิ่มประสบการณ์') {
            $('#examDiv').hide();
        } else {
            $('#examDiv').show();
        }
        $('#coursePay').val("");
        if ($('#discountAmount').val() != "") {
            cal = (parseInt(cal) - parseInt($('#discountAmount').val())).toString();
        }
        $('#totalCost').val(cal);
        $('#courseRemain').val(cal);

        if (newCourse != curCourse) {
            $('#changeBtn').show();
            $('#newCourse').show(300);
        } else {
            $('#changeBtn').hide();
            $('#newCourse').hide(300);
        }
    });

    $('#discountAmount').on('change', function() {
        if ($('#course').val() != "") {
            var t = $('#course').val().split('-');
            var cost = t[1];
            cost = (parseInt(cost) - parseInt($('#discountAmount').val())).toString();
            $('#totalCost').val(cost);
            $('#courseRemain').val(cost);
        }
        if ($('#coursePay').val() != "") {
            $('#courseRemain').val((parseInt($('#totalCost').val()) - parseInt($('#coursePay').val())).toString());
        }
    });
    $('#coursePay').on('change', function() {
        if ($('#course').val() != "") {
            if (parseInt($('#coursePay').val()) > parseInt($('#totalCost').val())) {
                $('#coursePay').val("");
                $('#remcourseRemainain').val($('#totalCost').val());
            } else {
                var remain = parseInt($('#totalCost').val()) - parseInt($('#coursePay').val());
                $('#courseRemain').val(remain);
            }
        }
    });

    $('#courseExamDate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    });

    $('#courseExamTime').timepicker({
        showMeridian: false,
        showSeconds: true,
        minuteStep: 1,
        secondStep: 1,
        icons: {
            up: 'fa fa-angle-up',
            down: 'fa fa-angle-down'
        }
    });

    $('#courseMethod').on('change', function() {
        $('#coursePayDate').datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true,
            language: 'th',
            orientation: 'top'
        }).datepicker("setDate", 'now');

        $('#coursePayTime').timepicker({
            showMeridian: false,
            showSeconds: true,
            minuteStep: 1,
            secondStep: 1,
            icons: {
                up: 'fa fa-angle-up',
                down: 'fa fa-angle-down'
            }
        });
    });

    $('#editBookingModal0').on('hidden.bs.modal', function() {
        $('#modalEditBookingFrm0')[0].reset();
        $('#gear0').selectpicker('refresh');
        $('#starttime0').selectpicker('refresh');
        $('#hour0').selectpicker('refresh');
        $('#vehicle0').selectpicker('refresh');
    });
    $('#editBookingModal0').on('show.bs.modal', function() {
        bookingVehicle('vehicle0', 'gear0', 'date0', 'starttime0', 'endtime0', 'hour0', 'vehicleType0', 'vbid0');
    });

    $('#editBookingModal1').on('hidden.bs.modal', function() {
        $('#modalEditBookingFrm1')[0].reset();
        $('#gear1').selectpicker('refresh');
        $('#starttime1').selectpicker('refresh');
        $('#hour1').selectpicker('refresh');
        $('#vehicle1').selectpicker('refresh');
    });
    $('#editBookingModal1').on('show.bs.modal', function() {
        bookingVehicle('vehicle1', 'gear1', 'date1', 'starttime1', 'endtime1', 'hour1', 'vehicleType1', 'vbid1');
    });

    $('#editBookingModal2').on('hidden.bs.modal', function() {
        $('#modalEditBookingFrm2')[0].reset();
        $('#gear2').selectpicker('refresh');
        $('#starttime2').selectpicker('refresh');
        $('#hour2').selectpicker('refresh');
        $('#vehicle2').selectpicker('refresh');
    });
    $('#editBookingModal2').on('show.bs.modal', function() {
        bookingVehicle('vehicle2', 'gear2', 'date2', 'starttime2', 'endtime2', 'hour2', 'vehicleType2', 'vbid2');
    });

    $('#editBookingModal3').on('hidden.bs.modal', function() {
        $('#modalEditBookingFrm3')[0].reset();
        $('#gear3').selectpicker('refresh');
        $('#starttime3').selectpicker('refresh');
        $('#hour3').selectpicker('refresh');
        $('#vehicle3').selectpicker('refresh');
    });
    $('#editBookingModal3').on('show.bs.modal', function() {
        bookingVehicle('vehicle3', 'gear3', 'date3', 'starttime3', 'endtime3', 'hour3', 'vehicleType3', 'vbid3');
    });

    $('#addBookingModal').on('hidden.bs.modal', function() {
        $('#modalAddBookingFrm')[0].reset();
        $('#gear').selectpicker('refresh');
        $('#starttime').selectpicker('refresh');
        $('#hour').selectpicker('refresh');
        $('#vehicle').selectpicker('refresh');
    });

    $('#addBookingModal').on('show.bs.modal', function() {
        getModule('hour', $('#enroll').val());
        bookingVehicle('vehicle', 'gear', 'date', 'starttime', 'endtime', 'hour', 'vehicleType', 'vbid');
    });

    $('#examDateModal').on('hidden.bs.modal', function() {
        $('#examFrm')[0].reset();
    });

    $('.selectpicker').selectpicker();

});

function getStopTime(startID, endID, hourID) {
    var start = $('#' + startID).val();
    start = start.split(":");
    var hour = $('#' + hourID).val().split('-');
    var stop = parseInt(start[0]) + parseInt(hour[1]);
    stop = stop.toString() + ":00";
    $('#' + endID).val(stop);
}

function bookingVehicle(vehicleID, gearID, dateID, startTimeID, endTimeID, hourID, driveType, vbid) {
    $('#' + gearID).on('change', function() {
        if ($('#' + startTimeID).val() != "") {
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), $('#' + driveType).val(), $('#' + vbid).val(), $('#' + hourID).val());
        }
    });
    $('#' + dateID).datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    });
    $('#' + dateID).on('change', function() {
        if ($('#' + startTimeID).val() != "" || $('#' + hourID).val() != "") {
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), $('#' + driveType).val(), $('#' + vbid).val(), $('#' + hourID).val());
        }
    });
    $('#' + hourID).on('change', function() {
        getStopTime(startTimeID, endTimeID, hourID);
        if ($('#' + startTimeID).val() != "") {
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), $('#' + driveType).val(), $('#' + vbid).val(), $('#' + hourID).val());
        }
    });
    $('#' + startTimeID).on('change', function() {
        if ($('#' + hourID).val() != "") {
            getStopTime(startTimeID, endTimeID, hourID);
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), $('#' + driveType).val(), $('#' + vbid).val(), $('#' + hourID).val());
        }
    });
}

function fetchRecords(selectID, gear, date, starttime, endtime, driveType, vbid, hourID) {
    var dateParts = date.split("/");
    dateParts = dateParts[2] + "-" + dateParts[1] + "-" + dateParts[0];
    var purpose = $('#purpose').val();
    var d = hourID.split("-");
    var drive = d[2];
    $.ajax({
        url: '/getVehicles/' + driveType + '/' + gear + '/' + dateParts + '/' + starttime + '/' + endtime + '/' + drive + '/' + purpose + '/' + vbid,
        type: 'get',
        dataType: 'json',
        success: function(response) {
            // console.log('/getVehicles/' + driveType + '/' + gear + '/' + dateParts + '/' + starttime + '/' + endtime + '/' + drive + '/' + purpose + '/' + vbid);
            var len = 0;
            if (response['data'] != null) {
                len = response['data'].length;
            }
            select = document.getElementById(selectID);
            var length = select.options.length;
            for (i = length - 1; i >= 0; i--) {
                select.options[i] = null;
            }
            if (len > 0) {

                for (var i = 0; i < len; i++) {
                    var id = response['data'][i].id;
                    var number = response['data'][i].number;
                    var brand = response['data'][i].brand;
                    var model = response['data'][i].model;
                    var registration = response['data'][i].registration_class + " " + response['data'][i].registration_number;
                    var vehicle = "คันที่ : " + number + " , " + brand + " " + model + " (" + registration + ")";

                    var opt = document.createElement('option');
                    opt.value = id;
                    opt.innerHTML = vehicle;
                    select.appendChild(opt);
                    $('.selectpicker').selectpicker('refresh');
                }
            }
        }
    });
}

function getCourseModule(selectID, courseID) {
    $.ajax({
        url: '/getModule/' + courseID,
        type: 'get',
        dataType: 'json',
        success: function(response) {
            var len = 0;
            if (response['data'] != null) {
                len = response['data'].length;
            }
            select = document.getElementById(selectID);
            var length = select.options.length;
            for (i = length - 1; i >= 0; i--) {
                select.options[i] = null;
            }
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var hour = response['data'][i].id + "-" + response['data'][i].module_hour + "-" + response['data'][i].drive;
                    var name = "[" + response['data'][i].module_hour + "] " + response['data'][i].module;
                    var opt = document.createElement('option');
                    opt.value = hour;
                    opt.innerHTML = name;
                    select.appendChild(opt);
                    $('.selectpicker').selectpicker('refresh');
                }
            }
        }
    });
}

function getModule(selectID, eid) {
    $.ajax({
        url: '/getModuleForBooking/' + eid,
        type: 'get',
        dataType: 'json',
        success: function(response) {
            // console.log('/getModuleForBooking/' + eid);
            var len = 0;
            if (response['data'] != null) {
                len = response['data'].length;
            }
            var select = document.getElementById(selectID);
            var length = select.options.length;
            for (i = length - 1; i >= 0; i--) {
                select.options[i] = null;
            }
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var hour = response['data'][i].id + "-" + response['data'][i].module_hour + "-" + response['data'][i].drive;
                    var name = "[" + response['data'][i].module_hour + "] " + response['data'][i].module;
                    var opt = document.createElement('option');
                    opt.value = hour;
                    opt.innerHTML = name;
                    select.appendChild(opt);
                    $('.selectpicker').selectpicker('refresh');
                }
            }
        }
    });
}