
<script src="<?php echo THEME_PATH; ?>/plugins/moment/moment.min.js"></script>

<script>
    function AddCommas(val){
        val = parseFloat(val.toString()).toString();
        while (/(\d+)(\d{3})/.test(val.toString())){
            val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
        }
        return val.replace(/\.0$|\.00$/,"") || "0";
    }
    function FixNumber(val){
        return AddCommas(parseFloat(val+"").toFixed(2));
    }
    // to remove many digits after the period
    $(function(){$(".ValSpan").each(function(){$(this).html(AddCommas(parseFloat($.trim($(this).text())).toFixed(3))).animate({opacity:1})})})
</script>
<style>
    #tableWithSearch tbody >tr>td >div.Arrow{
        cursor:pointer;   
    }
    #tableWithSearch tbody >tr>td >div.Arrow:before{
        content: "\f054";
        display: inline-block;
        margin-right: 8px;
        font-family: 'FontAwesome';
        -webkit-transition: all 0.12s linear;
        transition: all 0.12s linear;
    }
    #tableWithSearch tbody >tr.shown>td >div.Arrow:before {
        -webkit-transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        transform: rotate(90deg);
    }
    .table thead tr >th{
        background-color: #4c0870;
        color:#fff;
    }
    .table thead tr th[class*='sorting_'] {
        color: #FFFFFF;
    }
    .bg-master-lighter {
        border:none;
        background-color:#fff;
/*        border-top:1px solid #ddd; */

    }
        .StatementTable{
        width: 80%;
        margin: 0 auto;
        border: 1px solid rgb(200, 200, 200);

    }
    .StatementTable th{
        border: 1px solid rgb(200, 200, 200) !important;
    }
    .StatementTable tbody tr:last-child > td{
        border-bottom: 1px solid rgb(200, 200, 200) !important;
    }
    .StatementTable td,.StatementTable th{
        font-size:11px !important;
    }
    .datepicker thead tr .dow {
        color:#4c0870  !important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870  !important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870  !important;
    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870   !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870  !important;
    }
    .datepicker table tr td span:hover {
        background-color: #4c0870  !important;
        color:#fff;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870  !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870  !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .select2-container .select2-choice {
        color:#000 !important;
        opacity: 1;
    }
 .daterangepicker {
    position: absolute;
    background: #fff;
     top: 5px; 
     left: 850px; 
    padding: 4px;
    margin-top: 1px;
    border-radius: 4px;
    width:25%;
    
}
 .NameCenter{
        margin-left: 120px;
</style>
<script src="<?php echo JS_PATH;?>scripts.js"></script>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"> <?php print CommonLanguage::getMessage('item_cost_change');?></div>


            <div class="col-md-12"> 
<!--
                <div id="reportrange" class="col-md-2 form-group  daterangepicker" >
                    <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>&nbsp;
                    <span></span> <b class="caret"></b>
                </div>
-->
                
                <div class="col-md-2">
                    <select required id="Material_Code" name="Material_Code" class="full-width" data-init-plugin="select2" style="width:420px;">
                     <?php foreach ($all_products as $prod): ?>
                        <option value="<?php echo $prod['Product_ID']; ?>"><?php echo $prod['Product_Name']; ?></option>
                    <?php endforeach; ?>
                
                    </select>
                </div>

                
                
<div class="input-datarange input-group col-md-5 pull-right" style="width: 348px;">

<input id="FromDate"type="text" class="form-control input-sm" name="start" data-date-format="yyyy-mm" value="<?php echo($year.'/'.$monthName); ?>" aria-required="true" aria-invalid="false">
<span class="input-group-addon bg-primary"><i class="fa fa-calendar"></i></span>
<input id="ToDate"type="text" class="form-control input-sm" name="end" data-date-format="yyyy-mm" value="<?php echo($year.'/'.$monthName); ?>" aria-required="true" aria-invalid="false">

</div>
                

            </div>

<!--
<div class="col-md-3" style="margin-top: 15px;">
<input type="text" id="search-table" class="form-control pull-right" placeholder="Search">
</div>
-->
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <h2><?php print CommonLanguage::getMessage('cost_change_hint');?></h2>
            <table class="table  table-hover demo-table-search" id="tableWithSearch" >
                <thead>
                    <tr>
                       
                        <th class="text-center" style="width:50%" ><?php print CommonLanguage::getMessage('month');?></th>
                        <th class="text-center" style="width:50%" ><?php print CommonLanguage::getMessage('percent_of_change');?></th>



                    </tr>
                </thead>
                <tbody>
                    <?php
    for($x=0;$x<count($productList);$x++){
    $Curproduct = $productList[$x];
                    ?>
                    <tr data-month='<?php echo $Curproduct["MonthDate"]; ?>'>
                        
                        <td class=' v-align-middle text-center bold'><div class=" Arrow"><?php echo date("F", mktime(0, 0, 0, $Curproduct["MonthDate"], 10)); ?></td>
                        <td class=' v-align-middle text-center'><span class="ValSpan"><?php echo $Curproduct["percentage"]; ?></span> %</td>

                    </tr>
                    <?php }?>

                </tbody>
            </table>
        </div>
    </div>
</div>
<nav class="hidden navbar navbar-default bg-master-lighter sm-padding-10" role="navigation">
    <div class="container-fluid">
        <div class="collapse navbar-collapse" id="sub-nav">
            <div class="row"> 
                <div class="col-sm-4">
                    <ul class="nav navbar-nav navbar-center">
                        <li><a href="#" data-toggle="tooltip" title="Print" class="PrintThisTableButton" data-table="#tableWithSearch" data-date="" data-title="PRODUCT LIST"><i class="fa fa-print"></i></a></li>
                        <li><a href="#" data-toggle="tooltip" data-placement="bottom" title="Download"><i class="fa fa-download"></i></a></li>
                    </ul>
                </div>
                <div class="col-sm-4 pull-right">
                    <ul class="nav navbar-nav navbar-right">
                        <li>
                            <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-pdf" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png"></a>
                        </li>
                        <li>
                            <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-image" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/image2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/image2x.png" src="<?php echo SITE_LINK; ?>img/invoice/image2x.png"></a>
                        </li>
                        <li>
                            <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-doc" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png"></a>
                        </li>
                        <li><a href="#" class="p-r-10" onclick="$.Pages.setFullScreen(document.querySelector('html'));return false"><i class="fa fa-expand"></i></a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</nav>
<script>

    var Month_Name = [<?php echo json_encode([
                  CommonLanguage::getMessage('January'),
                  CommonLanguage::getMessage('February'),
                  CommonLanguage::getMessage('March'),
                  CommonLanguage::getMessage('April'),
                  CommonLanguage::getMessage('May'),
                  CommonLanguage::getMessage('June'),
                  CommonLanguage::getMessage('July'),
                  CommonLanguage::getMessage('August'),
                  CommonLanguage::getMessage('September'),
                  CommonLanguage::getMessage('October'),
                  CommonLanguage::getMessage('November'),
                  CommonLanguage::getMessage('December')]);?>];
    var DateLang = <?php echo json_encode(CommonLanguage::getMessage('Date'));?>,
        CostLang = <?php echo json_encode(CommonLanguage::getMessage('Cost'));?>;
    $(function(){
        $("#Material_Category_ID").on("change",function(){
            var Type = $(this).data("TypeListTarget"),
                Catolder = $("#s2id_"+$(this).attr("id"));
            $("#s2id_Material_Code").append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'><img style='height:25px;margin-top:5px;' src='img/demo/progress.svg' /></div>")
            Catolder.append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'></div>")
            $.ajax({
                url:"StockAjax/StockDashboardAjax",
                dataType:"json",
                data:{Material_Category_ID:$(this).val()},
                complete:function(v,vv){
                    $("#Material_Code").select2("destroy").empty()
                    if(vv == "success"){
                        var ToBeAdded = "";
                        for(var x=0;x<v.responseJSON.length;x++){
                            ToBeAdded += "<option value='"+v.responseJSON[x]["ID"]+"'>"+v.responseJSON[x]["Code"]+"-"+v.responseJSON[x]["Name"]+"</option>"
                        }
                        $("#Material_Code").html(ToBeAdded);
                    }
                    $("#Material_Code").select2();
                    $(">.LoadingCities",Catolder).remove()
                }
            })
        }).data("MyModuleListTarget","#Module_ID").trigger("change")
//
//        function cb(start, end) {
//            $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
//        }
//        cb(moment().subtract(29, 'days'), moment());
//
//        $('#reportrange').daterangepicker({
//            ranges: {
//                'Today': [moment(), moment()],
//                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
//                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
//                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
//                'This Month': [moment().startOf('month'), moment().endOf('month')],
//                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
//            }
//        }, cb);

                $("#FromDate").datepicker({autoclose:true,
                                          viewMode:"months",
									   minViewMode:"months"})
                $("#ToDate").datepicker({autoclose:true,
                                        viewMode:"months",
									   minViewMode:"months"})
        $("#FromDate,#ToDate").on("changeDate",function(e){
            getProductList();
        })
        $("#Material_Category_ID,#Material_Code").on('change',function(){
            
             setTimeout(function(){
				getProductList();
			},400)

        })
        
          var table = $('#tableWithSearch');

        table.dataTable();

        $('#search-table').on("keyup",function() {
            table.fnFilter($(this).val());
        });
                var StatementTableTemplate = '<table class="table table-hover StatementTable">'+
            '<thead>'+
            '    <tr>'+
            '        <th>'+DateLang+'</th>'+
            '        <th>'+CostLang+'</th>'+
            '    </tr>'+
            '</thead>'+
            '<tbody>'+
            '</tbody>'+
            '</table>';
        var LoadingTableTemplate = '<div class="TableLoader"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress"/></div>';


        $('tbody',table).on('click', '>tr', function() {
            if ($(this).hasClass('shown') && $(this).next().hasClass('row-details')) {
                $(this).removeClass('shown');
                $(this).next().remove();
                return;
            }
            var tr = $(this).closest('tr');
            var row = table.DataTable().row(tr);
            $(this).parents('tbody').find('.shown').removeClass('shown');
            $(this).parents('tbody').find('.row-details').remove();
            row.child(LoadingTableTemplate).show();
            tr.addClass('shown');
            tr.next().addClass('row-details');

            var code = {
                month:tr.attr("data-month"),
                Month_Item_ID:$("#Material_Code").val(),
            }
            console.log(code);

            $.ajax({
                url: 'InventoryAjax/ItemCostChangeAjax',
                data:code,
                dataType: 'json',
                complete: function(data,vv){

                    var TheTable = $(StatementTableTemplate),results = (data.responseJSON);
                    for (var i = 0; i < (results.length); i++) {

                        // console.log(results.length);


                        var locations =  "<tr>" +
                            "<td>" + results[i]["Pricing_Date"] + "</td>" +
                            "<td>" + results[i]["Product_Cost"] +' '+results[i]["Currency_Symbol"] +"</td>";


                        $("tbody",TheTable).append(locations);
                    }

                    $(".TableLoader",tr.next()).replaceWith(TheTable);
                    //row.child(TheTable);
                    console.log(data.responseJSON);


                }
            })







        });
    })
    function getProductList(){

        var CurrentDate =  {
            FromDate:[moment($("#FromDate").val()).format("YYYY"),moment($("#FromDate").val()).format("MM"),moment($("#FromDate").val()).format("DD")],
            
            ToDate:[moment($("#ToDate").val()).format("YYYY"),moment($("#ToDate").val()).format("MM"),moment($("#ToDate").val()).format("DD")],
           Item_ID:$("#Material_Code").val(),
        };
       console.log(CurrentDate)

        $('#tableWithSearch').DataTable().destroy();
        $("#tableWithSearch tbody").empty();
        $.ajax({
            url:"InventoryAjax/ItemCostChangeAjax",
            data:CurrentDate,
            dataType: 'json',
            complete:function(v1,v2){
                if(v2 == "success"){
                    var Data  = (v1.responseJSON);
                    for(var i=0;i<Data.length;i++){

                        console.log(Data);

                        var TR  = "<tr data-month='"+Data[i]["MonthDate"]+"'>"
                        TR += "<td class=' v-align-middle text-center bold'><div class=' Arrow'>"+Month_Name[0][Data[i]["MonthDate"]-1]+"</td>"
                        TR += "<td class=' v-align-middle text-center'>"+FixNumber(Data[i]["percentage"])+" %</td>"
                        TR += "</tr>"


                        TR = $(TR)
                        $("#tableWithSearch").append(TR)


                    }
                }
                RebuildTable()
            }
        })

    }
    function RebuildTable(){
        $('#tableWithSearch').dataTable();

    }

</script>