/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var rentproduct = function () {

    $caltotal = function () {
        $amount = $('#amount').val();
        $buyprice = $('#buyprice').val();

        $('#totalprice').val(Number($amount) * Number($buyprice));
    };

    $('#amount,#buyprice').keyup(function () {
        $caltotal();
    });

    /*$('input[type=radio][name=paytype]').change(function () {
     $sel = $(this).val();
     if ($sel == 1) {
     $('#suppliercontainter').show();
     } else {
     $('#suppliercontainter').hide();
     }
     });*/

};

var TableDatatablesButtons = function () {

    var e = function () {
        var e = $("#custom_tbl_dt");
        var lstone, belastone, thrdone;
        $i = 0;
        $('#custom_tbl_dt thead th').each(function () {
            $vl = $(this).html().length;
            var iColumns = $('#custom_tbl_dt thead th').length;

            if ($vl == 0 && $i == 2) {
                //do something
                thrdone = iColumns - 3;
                $i = 3;
            }

            if ($vl == 0 && $i == 1) {
                //do something
                belastone = iColumns - 2;
                $i = 2;
            }

            if ($vl == 0 && $i == 0) {
                //do something
                lstone = iColumns - 1;
                $i = 1;
            }



        });
        e.dataTable({
            "bStateSave": true,
            "language": {
                "aria": {
                    "sortAscending": ": Used to order Ascending",
                    "sortDescending": ": Used to order Descending"
                },
                "emptyTable": "لا يوجد بيانات",
                "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
                "infoEmpty": "لا يوجد بيانات",
                "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
                "lengthMenu": " _MENU_ عنصر",
                "search": "البحث:",
                "zeroRecords": "لا يوجد بيانات تشابه البحث"
            },
            buttons: [{
                    extend: "print",
                    className: "btn dark btn-outline",
                    text: "طباعه",
                    exportOptions: {
                        columns: '.show-print'
                    }

                }, {
                    extend: "copy",
                    className: "btn red btn-outline",
                    text: "نسخ",
                    exportOptions: {
                        columns: '.show-print'
                    }
                }, {
                    extend: "excel",
                    className: "btn yellow btn-outline ",
                    text: "اكسل",
                    exportOptions: {
                        columns: '.show-print'
                    }
                }, {
                    extend: "colvis",
                    className: "btn dark btn-outline",
                    text: "المكونات"
                }],
            responsive: !0,
            "columnDefs": [
                {// set default column settings
                    "orderable": false,
                    "searchable": false,
                    "targets": [lstone],
                    "className": 'hide-print'
                },
                {// set default column settings
                    "orderable": false,
                    "searchable": false,
                    "targets": [belastone],
                    "className": 'hide-print'
                },
                {// set default column settings
                    "orderable": false,
                    "searchable": false,
                    "targets": [thrdone],
                    "className": 'hide-print'
                },
                {targets: '_all', "className": 'show-print'}],
            order: [
                [0, "asc"]
            ],
            lengthMenu: [
                [5, 10, 15, 20, -1],
                [5, 10, 15, 20, "All"]
            ],
            pageLength: 10,
            dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
        });
    };
    return {
        init: function () {
            jQuery().dataTable && (e())
        }
    };
}();

var rentbill = function () {


    $('.adatepicker').datepicker({autoclose: true});
//type
    $('.renttype').live('change', function () {
        $type = $(this).val();
        $itr = $(this).attr('data-itr');
        //to change max with out and in
        $notmax = $('#amount' + $itr).attr('notmax');

        if ($type == 1) {
            $('.typeout' + $itr).css({"display": "block"});
            $('.maintypeout').css({"display": "block"});
            //to change max with out and in
            $('#amount' + $itr).removeAttr('max');
            $('#amountcount' + $itr).html('');
        } else {
            $('.typeout' + $itr).css({"display": "none"});
            $('.maintypeout').css({"display": "none"});
            //to change max with out and in
            $max = $('#amount' + $itr).attr('max', $notmax);
            $('#amountcount' + $itr).html($notmax);
        }

//check if there out
        $('.renttype').each(function () {
            $inval = $(this).val();
            if ($inval == 1) {
                $('.maintypeout').css({"display": "block"});
            }
        });
    });


    $('.fetchproduct').select2({
        width: "300px",
        placeholder: "اختر",
        minimumInputLength: 1,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "rentajax.php?do=getproducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    ids: $('#selectedIds').val(),
                    myid: $(this).val(),
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });

    var formatResult = function (data) {
        return  data.text;
    };

    var getselectedids = function ()
    {
        var ids = '';
        $('.fetchproduct').each(function (index, element) {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (tag == 'input' && type == "hidden")
            {
                if (this.value != "")
                {
                    ids += this.value + ',';
                }
            }
        });
        $('#selectedIds').val(ids);
    };





    /* add new item **/
    $('#addrent').click(function () {
        var rentitr = Number($('#hidden_itr').val()) + 1;
        $billtr = '<tr id="productraw' + rentitr + '">'
                + '<td>'
                + '<input type="hidden"  id="productid' + rentitr + '" name="productid' + rentitr + '" data-placeholder="اختر" required=""  data-itr="' + rentitr + '" class="fetchproduct wdt100"/>'
                + '</td>'
                + '<td>'
                + '<select class="select2 wdt100 renttype" name="renttype' + rentitr + '" id="renttype' + rentitr + '" data-itr="' + rentitr + '">'
                + '<option value="0">داخلى</option>'
                + '<option value="1">خارجي</option>'
                + '</select>'
                + '</td>'
                + '<td>'
                + '<table class="typeout typeout' + rentitr + '">'
                + '<tr>'
                + '<td>'
                + '<select class="select2 wdth150" name="supplierid' + rentitr + '" id="supplierid' + rentitr + '" placeholder="اختر مورد" required="" >'
                + '<option value=""></option>'
                + $('#supls').html()
                + '</select>'
                + '</td>'
                + '<td>'
                + '<input type="text" name="buyprice' + rentitr + '" id="buyprice' + rentitr + '" number="true" min="1"  class="form-control txt-nonraduis wdth50 calptotal" data-itr="' + rentitr + '" value="0" tabindex="7" />'
                + '</td>'
                + '<td>'
                + '<div id="buytotal' + rentitr + '" class="wdth50">'
                + '0'
                + '</div>'
                + '<input type="hidden" name="hbuytotal' + rentitr + '" id="hbuytotal' + rentitr + '" value="0"/>'
                + '</td>'
                + '<td>'
                + '<div id="bbuytotal' + rentitr + '" class="wdth50">'
                + '0'
                + '</div>'
                + '<input type="hidden" name="hbbuytotal' + rentitr + '" id="hbbuytotal' + rentitr + '" value="0"/>'
                + '</td>'
                + '</tr>'
                + '</table>'
                + '</td>'
                + '<td>'
                + '<input type="text" style="float: right;width: 50%;" min="1" name="amount' + rentitr + '" id="amount' + rentitr + '"  class="form-control txt-nonraduis calptotal" data-itr="' + rentitr + '" value="1" tabindex="7" />'
                + '<div id="amountcount' + rentitr + '" style="float: left;"></div>'
                + '</td>'
                + '<td>'
                + '<input type="text" name="rentprice' + rentitr + '" id="rentprice' + rentitr + '"  class="form-control txt-nonraduis calptotal" data-itr="' + rentitr + '" number="true" min="1" value="0" tabindex="7" />'
                + '</td>'
                + '<td>'
                + '<div id="renttotal' + rentitr + '">'
                + '0'
                + '</div>'
                + '<input type="hidden" name="hrenttotal' + rentitr + '" id="hrenttotal' + rentitr + '" class="prenttotal" value="0"/>'
                + '</td>'
                + '<td>'
                + '<input name="startdate' + rentitr + '" type="text" id="startdate' + rentitr + '" data-date-format="yyyy-mm-dd" value="' + $('#todaydate').val() + '" data-itr="' + rentitr + '" class="form-control adatepicker caldate" required=""/>'
                + '</td>'
                + '<td>'
                + '<input name="enddate' + rentitr + '" type="text" id="enddate' + rentitr + '" data-date-format="yyyy-mm-dd"  class="form-control adatepicker caldate" data-itr="' + rentitr + '" required=""/>'
                + '</td>'
                + '<td>'
                + '<div id="rentdays' + rentitr + '">'
                + '0'
                + '</div>'
                + '<input type="hidden" name="hrentdays' + rentitr + '" id="hrentdays' + rentitr + '" value="0"/>'
                + '</td>'
                + '<td>'
                + '<div id="rentdaystotal' + rentitr + '">'
                + '0'
                + '</div>'
                + '<input type="hidden" name="hrentdaystotal' + rentitr + '" id="hrentdaystotal' + rentitr + '" class="prentdaystotal" value="0"/>'
                + '</td>'
                + '<td>'
                + '<button id="remove' + rentitr + '" type="button"  data-itr="' + rentitr + '" class="close flt-none removeicon removeproduct" aria-hidden="true">&times;</button>'
                + '</td>'
                + '</tr>';
        $('#rentscontainer').append($billtr);
        //update plugins
        //$('#productid' + rentitr).select2();

        $('#productid' + rentitr).select2({
            width: "300px",
            placeholder: "اختر",
            minimumInputLength: 1,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "rentajax.php?do=getproducts",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                        ids: $('#selectedIds').val(),
                        myid: $(this).val()
                    };
                },
                results: function (data) {
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });


        $('#renttype' + rentitr).select2();
        $('#supplierid' + rentitr).select2();
        $('#startdate' + rentitr).datepicker({autoclose: true});
        $('#enddate' + rentitr).datepicker({autoclose: true});
        $('#hidden_itr').val(rentitr);
    });

    $('.removeproduct').live('click', function () {
        $itr = $(this).attr('data-itr');
        $(this).parent().parent().remove();
        cal_total_rent_single($itr);
        cal_days_total($itr);
        cal_big_total_buy_single($itr);
        cal_all_total();
        cal_reset();
    });

    $('.fetchproduct').live('change', function () {
        $selectpro = $(this).val();
        $itr = $(this).attr('data-itr');
        $.ajax({
            type: "POST",
            url: 'rentajax.php?do=fetchproduct',
            data: {productid: $selectpro},
            success: function (rslt) {
                console.log(rslt);
                $('#rentprice' + $itr).val(rslt.rentprice);

                $renttype = $('#renttype' + $itr).val();
                //get max
                $enddate = $('#enddate' + $itr).val();
                if ($enddate == "") {
                    $enddate = $('#todaydate').val();
                }
                $startdate = $('#startdate' + $itr).val();
                if ($startdate == "") {
                    $startdate = $('#todaydate').val();
                }
                $.post('rentajax.php?do=calmaxava', {productid: $selectpro, startdate: $startdate, enddate: $enddate}, function (max) {
                    $('#amount' + $itr).attr('notmax', max);
                    if ($renttype == 0) {
                        $('#amount' + $itr).attr('max', max);
                        $('#amountcount' + $itr).html(max);
                    } else {
                        $('#amount' + $itr).removeAttr('max');
                        $('#amountcount' + $itr).html('');
                    }
                });

                /*if (rslt.paytype == 1) {
                 $('#renttype' + $itr).select2('val', 1);
                 $('.typeout' + $itr).css({"display": "block"});
                 $('.maintypeout').css({"display": "block"});
                 $('#supplierid' + $itr).select2('val', rslt.supplierid);
                 $('#buyprice' + $itr).val(rslt.buyprice);
                 cal_total_buy_single($itr);
                 } else {
                 $('#renttype' + $itr).select2('val', 0);
                 $('.typeout' + $itr).css({"display": "none"});
                 $('#supplierid' + $itr).select2('val', "");
                 $('#buyprice' + $itr).val(0);
                 }*/
                cal_total_rent_single($itr);
                cal_days_total($itr);
                cal_big_total_buy_single($itr);
                cal_all_total();
                cal_reset();
            },
            dataType: 'json'
        });

        getselectedids();
    });
    //cal total of rent for product
    var cal_total_rent_single = function (itr) {
        $amount = Number($('#amount' + itr).val());
        $rentprice = Number($('#rentprice' + itr).val());
        $sumit = $amount * $rentprice;
        $("#renttotal" + itr).html($sumit);
        $("#hrenttotal" + itr).val($sumit);
    };
    //cal total of buy for product
    var cal_total_buy_single = function (itr) {
        $amount = Number($('#amount' + itr).val());
        $buyprice = Number($('#buyprice' + itr).val());
        $sumit = $amount * $buyprice;
        $("#buytotal" + itr).html($sumit);
        $("#hbuytotal" + itr).val($sumit);
    };
    //call total of buy price iwth days
    var cal_big_total_buy_single = function (itr) {
        $buytotal = Number($('#hbuytotal' + itr).val());
        $rentdays = Number($('#hrentdays' + itr).val());
        $sumit = $buytotal * $rentdays;
        $("#bbuytotal" + itr).html($sumit);
        $("#hbbuytotal" + itr).val($sumit);
    };
    //cal all total of rent
    var cal_all_total = function () {
        var alltotal = 0;
        $('.prentdaystotal').each(function () {
            alltotal = alltotal + Number($(this).val());
        });
        $('#rentbilltotal').html(alltotal);
        $('#hrentbilltotal').val(alltotal);
        $('#paperval').val(alltotal);
    };
    //the reset from payed
    var cal_reset = function () {

        $total = Number($('#hrentbilltotal').val());
        $genpay = Number($('#genpay').val());
        $discount = Number($('#discount').val());
        $distotal = Number($('#distotal').val());

        if ($genpay > 0){
            if ($distotal > 0){
                $total = $distotal;
            }
            else{
                $total = Number($('#hrentbilltotal').val());
            }
            $sumit = $total - $genpay;
            if ($genpay > $total) {
                $('#genpay').val($total);
                $sumit = 0;
            }
        } else if($discount > 0){
            $sumit = $total - $discount;
            if ($discount > $total) {
                $('#discount').val($total);
                $sumit = 0;
            }
            $("#discounttotal").html($sumit);
            $("#distotal").val($sumit);

        }else {
            $sumit = $total - $genpay;
            if ($genpay > $total) {
                $('#genpay').val($total);
                $sumit = 0;
            }
			
			 if ($discount <= 0){

                $("#distotal").val(0);
                $("#discounttotal").html(0);
            }
        }


            $("#gen3total").html($sumit);

    };

    $('#discount').keyup(function () {
        cal_reset();
    });

    
    //cal no of day for product
    var cal_days = function (itr) {

        $startdate = new Date($('#startdate' + itr).val());
        $enddate = new Date($('#enddate' + itr).val());
        var diff = new Date($enddate - $startdate);
        // get days
        var days = diff / 1000 / 60 / 60 / 24;
        if (days <= 0) {
            $('#enddate' + itr).val('');
            days = 0;
        }
        $('#rentdays' + itr).html(days);
        $('#hrentdays' + itr).val(days);
    };
    //cal days total
    var cal_days_total = function (itr) {
        $renttotal = Number($('#hrenttotal' + itr).val());
        // $rentdays = Number($('#hrentdays' + itr).val());
        // $sumit = $rentdays * $renttotal;
        $("#rentdaystotal" + itr).html($renttotal);
        $("#hrentdaystotal" + itr).val($renttotal);
    };


    $('.calptotal').live('keyup', function () {
        $itr = $(this).attr('data-itr');
        cal_total_rent_single($itr);
        cal_total_buy_single($itr);
        cal_days_total($itr);
        cal_big_total_buy_single($itr);
        cal_all_total();
        cal_reset();
    });
    $('.caldate').live('change', function () {
        $itr = $(this).attr('data-itr');
        cal_days($itr);
        cal_days_total($itr);
        cal_big_total_buy_single($itr);
        cal_all_total();
        cal_reset();

        $renttype = $('#renttype' + $itr).val();
        $selectpro = $('#productid' + $itr).val();
        //get max
        $enddate = $('#enddate' + $itr).val();
        if ($enddate == "") {
            $enddate = $('#todaydate').val();
        }
        $startdate = $('#startdate' + $itr).val();
        if ($startdate == "") {
            $startdate = $('#todaydate').val();
        }
        $.post('rentajax.php?do=calmaxava', {productid: $selectpro, startdate: $startdate, enddate: $enddate}, function (max) {
            $('#amount' + $itr).attr('notmax', max);
            if ($renttype == 0) {
                $('#amount' + $itr).attr('max', max);
                $('#amountcount' + $itr).html(max);
            } else {
                $('#amount' + $itr).removeAttr('max');
                $('#amountcount' + $itr).html('');
            }
        });



    });
    $('.payit').keyup(function () {
        cal_reset();
    });


    //to bank or not
    $('input[name=payistype]').change(function () {
        $isno = $(this).val();
        if ($isno == 1) {
            $('#bankinfocontianter').css({"display": "block"});
            $('.forcash').css({"display": "none"});
        } else {
            $('#bankinfocontianter').css({"display": "none"});
            $('.forcash').css({"display": "block"});
        }
    });

    //get accounts in bank
    $('#bankid').change(function () {
        $isno = $(this).val();
        $.post('rentajax.php?do=fetchaccounts', {bankid: $isno}, function (rslt) {
            $('#accountcontainer').html(rslt);
            $('#accountid').select2();
        });
    });




};

var billdetails = function () {

    //check if there direct print
    $isprint = $('#isprint').val();
    if ($isprint == 1) {
        print_Custom('mycustomheader');
    }

    $('#printit').click(function () {
        print_Custom('mycustomheader');
    });

    $('.openreceived').click(function () {
        $billproid = $(this).attr('data-id');

        window.location = "rentbill.php?do=receive&id=" + $billproid;

    });

};
$(document).ready(function (e) {

    $(".rentform").validate();
    //rent products
    /*================================================*/



    rentproduct();
    TableDatatablesButtons.init();
    rentbill();
    billdetails();


    $('#rentform').submit(function (e) {
        $('.fetchproduct').each(function () {
            $proval = $(this).val();
            $protype = $(this).attr('type');
            $proname = $(this).attr('name');
            if ($protype == 'hidden') {
                if ($proval == "") {
                    $(this).parent().append('<label id="' + $proname + '-error" class="error" for="' + $proname + '">هذا الحقل إلزامي</label>');
                } else {
                    $("#" + $proname + "-error").remove();
                }
            }
        });
    });





});





