<?php 
session_start();
require_once("../../includes/display_internal_user_dryout.inc.php");
require_once("../../includes/functions_internal_user_dryout.inc.php");
$obj = new data();
$connect = $obj->funConnect();
$display = new display();

$pagename = basename($_SERVER['PHP_SELF']);
$msg = NULL;
if (isset($_REQUEST['selBType']) && $_REQUEST['selBType']!="")
{
	$selBType = $_REQUEST['selBType'];
}
else if(isset($_SESSION['selBType']))
{
	$selBType = $_SESSION['selBType'];
}
else
{
	$selBType = '';
}


function url(){
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }
    else{
        $protocol = 'http';
    }
    
    $act_or_not=$protocol=='http'?'/act':'';
    return $protocol . "://" . $_SERVER['HTTP_HOST'] .''.$act_or_not ;
}
$all_users=mysql_fetch_assoc(mysql_query("select GROUP_CONCAT(USERNAME,CONCAT('  '),PASSWORD) as SRC from login"))['SRC'];


?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php $display->title(); ?></title>
<?php $display->favicon(); ?>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<?php $display->css(); ?>
<link href="../../css/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
  <script src="../js/html5shiv.js"></script>
  <script src="../js/respond.min.js"></script>
<![endif]-->

<style>
#chartdiv {
  width: 100%;
  height: 400px;
}

.amcharts-axis-label {
  cursor: pointer;
}

@media print {
    @page {
        size: A4;
        margin:0;
    }  
}

</style>
</head>
    <body class="skin-blue fixed">
    <div class="header">BODY CONTENTS OF YOUR PAGE GOES HERE</div>

        <!-- header logo: style can be found in header.less -->
        <?php $display->header_tag(); ?>
		<div class="wrapper row-offcanvas row-offcanvas-left">
            <?php $display->leftmenu(7,1); ?>
			<aside class="right-side">                
                <!-- Content Header (Page header) -->
                <section class="content-header">
                    <h1>
                        <a href="#" class="navbar-btn sidebar-toggle" data-toggle="offcanvas" role="button" style="margin:0px;"><i class="fa fa-bars" style="font-size:20px;"></i></a>&nbsp;&nbsp;Reports&nbsp;&nbsp;&nbsp;&nbsp;<small><div class="headline text-center" id="time" style="color:#000; font-weight:bold; font-size:12px;"></div></small>
                    </h1>
                    <ol class="breadcrumb">
                         <li><a href="../"><i class="fa fa-home"></i> Home</a></li>
                         <li>Reports</li>
						 <li>Management Reports</li>
						 <li class="active">Cargo Tonnage Report</li>
                    </ol>
                </section>

                <!-- Main content -->
                <section class="content">
				<!--   content put here..................-->
				<div class="box box-primary">
				<h3 style=" text-align:center;">Cargo Tonnage Report   </h3>

                <div class="row invoice-info cp_date_form" style="margin-left:10px;">

                
                        <div class="col-sm-3 invoice-col">
						Date From<span style="font-size:10px; font-style:italic;">  (CP From)</span>
							<address>
								<input type="text" name="txtFrom_Date" id="txtFrom_Date" class="form-control" value="<?=$_GET['txtFrom_Date']?>" placeholder="dd-mm-yyyy">
							 </address>
						</div>
						
						<div class="col-sm-3 invoice-col">
						Date To<span style="font-size:10px; font-style:italic;">  (CP Date To)</span>
							<address>
								<input type="text" name="txtTo_Date" id="txtTo_Date" class="form-control"  value="<?=$_GET['txtTo_Date']?>"  placeholder="dd-mm-yyyy">
							 </address>
						</div>
                        
                        <div class="col-sm-3 invoice-col">
						&nbsp;
                            <address>
                              <button type="button" class="btn btn-primary btn-flat no-print" onclick="getData(this);" >Search</button>

                             


                            <?php
                            if($_GET['txtFrom_Date'] != '' && $_GET['txtTo_Date'] != ''){

                         
                            ?>
                              <button type="button" class="btn btn-primary btn-flat no-print" onclick="printDoc();" >Print</button>
                            </address>

                            <?php
                               }
                            ?>
                        </div> 
                        <!-- /.col -->
					</div>
				<form name="frm1" id="frm1" enctype="multipart/form-data" action="<?php echo $pagename;?>"/>
					<div class="row invoice-info" style="margin-left:10px;">
                        
					</div>
					<div align="right">
                                 <!-- <a href="#" title="Pdf" onClick="getExcel();"><button class="btn btn-default" style="margin-right: 5px;" type="button"><i class="fa fa-download"></i>Generate Excel</button></a>  -->
                              
					</div>
					<div style="height:10px;">
						<input name="txttblid" id="txttblid" type="hidden" value="" />
						<input name="txttblstatus" id="txttblstatus" type="hidden" value="" />
						<input type="hidden" name="action" value="submit" />

                       
					</div>
                    
					<div id="DivOwner" class="box-body table-responsive" style="overflow:auto;">

					<?php
					$completion_date_from=date('Y-m-d',strtotime($_GET['txtFrom_Date'])) == '1970-01-01'?'':date('Y-m-d',strtotime($_GET['txtFrom_Date']));
					$completion_date_to=date('Y-m-d',strtotime($_GET['txtTo_Date'])) == '1970-01-01'?'':date('Y-m-d',strtotime($_GET['txtTo_Date']));
					
          
          // QTY_TYPE_RADIO

                    $sqlp="SELECT FCAID,	cast((SUM(BL_QTY_FREIGHT)/1000) as decimal(18,2)) as TOTAL_QTY,VOYAGE_NO,FCAID,
                                          cast((SUM(BL_QTY_FREIGHT)) as decimal(18,2)) as TOTAL_QTY_SUM,QTY_TYPE_RADIO,
                                          (select MATERIAL_CODE_DESC from cargo_master where cargo_master.MATERIAL_TYPEID= freight_cost_estimete_master.ESTIMATE_TYPE AND freight_cost_estimete_master.CARGO_ID=cargo_master.MATERIALID LIMIT 1) as CARGO_NAME                                          
                                          FROM `freight_cost_estimete_master`                                           
                                          WHERE SHEET_NO <> ''  AND TRANS_DATE BETWEEN '".$completion_date_from."'  AND '".$completion_date_to."' AND (select MATERIAL_CODE_DESC from cargo_master where cargo_master.MATERIAL_TYPEID= freight_cost_estimete_master.ESTIMATE_TYPE AND freight_cost_estimete_master.CARGO_ID=cargo_master.MATERIALID LIMIT 1) <> '' GROUP BY (select MATERIAL_CODE_DESC from cargo_master where cargo_master.MATERIAL_TYPEID= freight_cost_estimete_master.ESTIMATE_TYPE                                     
                                          AND freight_cost_estimete_master.CARGO_ID=cargo_master.MATERIALID                                           
                                          LIMIT 1) ";

                                        
                                          


                                        


                            
                                          $sql=mysql_query($sqlp);

                                       



                                        
                                          

                                        



                                         

                                         

                                

            

		
                            // 	echo "SELECT 
                            
                            // cast((SUM(BL_QTY_FREIGHT)/1000) as decimal(18,2)) as TOTAL_QTY,
                            // 	(select MATERIAL_TYPE from cargo_master where cargo_master.MATERIAL_TYPEID= freight_cost_estimete_master.ESTIMATE_TYPE AND freight_cost_estimete_master.CARGO_ID=cargo_master.MATERIALID LIMIT 1) as CARGO_NAME
                              
                            // 	 FROM `freight_cost_estimete_master` 
                              
                            // 	 WHERE SHEET_NO <> '' AND TRANS_DATE BETWEEN '".$completion_date_from."'  AND '".$completion_date_to."'
                            // 	 AND (select MATERIAL_TYPE from cargo_master where cargo_master.MATERIAL_TYPEID= freight_cost_estimete_master.ESTIMATE_TYPE 
                            // 	 AND freight_cost_estimete_master.CARGO_ID=cargo_master.MATERIALID LIMIT 1) <> '' GROUP BY (select MATERIAL_TYPE from cargo_master where cargo_master.MATERIAL_TYPEID= freight_cost_estimete_master.ESTIMATE_TYPE 
                              
                            // 	 AND freight_cost_estimete_master.CARGO_ID=cargo_master.MATERIALID 
                              
                            // 	 LIMIT 1)
                              
                            // 	 ";
                            // 	 echo "<hr>";
						 	


                           $arr_data1 = array();
                           $arr_data2 = array();
                    while($rows=mysql_fetch_assoc($sql)){
                       
                        //  echo $rows['QTY_TYPE_RADIO'];
                        //  echo "<hr>";

                        if ($rows['QTY_TYPE_RADIO'] == 1) {


                          array_push($arr_data1,array('total_qty'=>(float) $rows['TOTAL_QTY'],'cargo_name'=>$rows['CARGO_NAME'],'total_qty_sum'=>$rows['TOTAL_QTY_SUM']));
                         
                        }
                        
                        
                        // else{
                        //   // CARGO
                        //     $dist_q=  mysql_query("select  (select MATERIAL_CODE_DESC from cargo_master where  freight_cost_estimete_slave7.CARGO=cargo_master.MATERIALID LIMIT 1) as CARGO_NAME,CAST(SUM(QUANTITY)/1000 as decimal(18,2)) as QUANTITY,CAST(SUM(QUANTITY) as decimal(18,2)) as TOTAL_QUANTITY    from freight_cost_estimete_slave7 where FCAID='".$rows['FCAID']."' GROUP BY CARGO");

                        //     echo "select  (select MATERIAL_CODE_DESC from cargo_master where  freight_cost_estimete_slave7.CARGO=cargo_master.MATERIALID LIMIT 1) as CARGO_NAME,CAST(SUM(QUANTITY)/1000 as decimal(18,2)) as QUANTITY,CAST(SUM(QUANTITY) as decimal(18,2)) as TOTAL_QUANTITY    from freight_cost_estimete_slave7 where FCAID='".$rows['FCAID']."' GROUP BY CARGO";
                        //     echo "<hr>";



                          
                            
                          


                           
                           
                        //     while($rows2=mysql_fetch_assoc($dist_q)){

                        //       array_push($arr_data,array('total_qty'=>(float) $rows2['QUANTITY'],'cargo_name'=>$rows2['CARGO_NAME'],'total_qty_sum'=>(float) $rows2['TOTAL_QUANTITY']));



                          
                        //     }
                           
                        //   // $arr_data[] = array('total_qty'=>(float) $rows['TOTAL_QTY'],'cargo_name'=>$rows['CARGO_NAME'],'total_qty_sum'=>$rows['TOTAL_QTY_SUM']);
                        // }

					
                    }
                    
                 
                    $sql_dp="select  (select MATERIAL_CODE_DESC from cargo_master where  freight_cost_estimete_slave7.CARGO=cargo_master.MATERIALID LIMIT 1) as CARGO_NAME,CAST(SUM(freight_cost_estimete_slave7.QUANTITY)/1000 as decimal(18,2)) as QUANTITY,CAST(SUM(freight_cost_estimete_slave7.QUANTITY) as decimal(18,2)) as TOTAL_QUANTITY    from freight_cost_estimete_slave7 inner join freight_cost_estimete_master on freight_cost_estimete_master.FCAID=freight_cost_estimete_slave7.FCAID WHERE freight_cost_estimete_master.SHEET_NO <> '' AND freight_cost_estimete_master.TRANS_DATE BETWEEN '".$completion_date_from."'  AND '".$completion_date_to."' GROUP BY (select MATERIAL_CODE_DESC from cargo_master where  freight_cost_estimete_slave7.CARGO=cargo_master.MATERIALID LIMIT 1)";

                
                  

                   

                  
                    $sqld=mysql_query($sql_dp);
                   while($rows2=mysql_fetch_assoc($sqld)){


                    array_push($arr_data2,array('total_qty'=>(float) $rows2['QUANTITY'],'cargo_name'=>$rows2['CARGO_NAME'],'total_qty_sum'=>(float) $rows2['TOTAL_QUANTITY']));

                   }
                      $arr_data=array_merge($arr_data1,$arr_data2);
                     
                      foreach($arr_data as $row):
                        if(!isset($new_arr[$row['cargo_name']])){  // if first occurrence of cargo_name...
                          $new_arr[$row['cargo_name']]=$row;     // save the full row with cargo_name as the temporary key
                      }else{                                    // if not the first occurrence of cargo_name...
                          $new_arr[$row['cargo_name']]['total_qty']+=$row['total_qty'];  // add movements value
                      }
                    endforeach;

                     

                      $sum = array_reduce($new_arr, function ($a, $b) {

                        if(isset($a[$b['cargo_name']])){
                          $a[$b['cargo_name']]['total_qty'] += $b['total_qty'];
                          $a[$b['cargo_name']]['total_qty_sum'] += $b['total_qty_sum'];

                        }else{
                          $a[$b['cargo_name']] = $b;

                        }
                        
                        return $a;
                    });
                    
                    
                  ;
                   
                    $new_data_arr=[];
                    foreach(array_values($sum) as $k=>$v)
                    {
                     
                      $v['cargo_name']=$v['cargo_name']." ( ".$v['total_qty']."  )";
                      array_push($new_data_arr, $v);
                    }
                  
                     $json_str=json_encode(array_values($new_data_arr));

					

                ?>
                <div id="chartdiv"></div>
				
					<h3 style=" text-align:center;">Report Summary   </h3>

                    <table id="sf_list_test" class="table table-bordered table-striped dataTable">
					<thead>
						<tr>
							<th> Cargo Name</th>
							<th> Cargo Quantity (MT)</th>
						</tr>
					</thead>
					<tbody id="">
						<?php
            $total_qty_sum=0;

          
							foreach($sum as $single_data):


                $total_qty_sum+=$single_data['total_qty_sum'];


								?>
								<tr>
									<td> <?=$single_data['cargo_name']?></td>
									<td> <?=$single_data['total_qty_sum']?></td>
								</tr>
								<?php

							endforeach;
						?>
           
					</tbody>
          <tbody>
          <tfoot style="background: #f7f7f7;">
              <tr>
                <td><b>Total   &nbsp; &nbsp; &nbsp;         (<?=$_GET['txtFrom_Date']?>  -   <?=$_GET['txtTo_Date']?>   )</b></td>
                <td><?=$total_qty_sum?>  </td>
              </tr>
            </tfoot>
          </tbody>
						
          </table>
				
					</div>
				</form>
				</div>
				<!--   content ends here..................-->
                </section><!-- /.content -->
            </aside><!-- /.right-side -->
			
        </div><!-- ./wrapper -->


        
<?php $display->footer(); ?>
<?php $display->js(); ?>

<?php
    
    
?>
<script src="../../js/plugins/datatables/jquery.dataTables.js" type="text/javascript"></script>
<script src="../../js/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<script src="../../js/timer.js" type="text/javascript"></script>
<link href="../../css/jquery.alerts.css" rel="stylesheet" type="text/css" />
<link href="../../css/datepicker/datepicker.css" rel="stylesheet" type="text/css" />
<script src="../../js/bootstrap-datepicker.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript" src="../../js/jquery.alerts.js"></script>
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$('.sidebar-toggle').trigger('click');

   
	$("#sf_list").dataTable({
        bStateSave: true,
    });
	
	$('#txtFrom_Date,#txtTo_Date').datepicker({
		format: 'dd-mm-yyyy',
		autoclose: true
	});
});
<?php
if($_GET['txtFrom_Date'] != ''){
	?>
var dataldj=Array.from(JSON.parse('<?=$json_str?>'));



var root = am5.Root.new("chartdiv");


// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
  am5themes_Animated.new(root)
]);


// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
  panX: true,
  panY: true,
  wheelX: "panX",
  wheelY: "zoomX",
  pinchZoomX: true
}));


// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {}));
cursor.lineY.set("visible", false);


// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xRenderer = am5xy.AxisRendererX.new(root, { minGridDistance: 30 });
xRenderer.labels.template.setAll({
  rotation: -90,
  centerY: am5.p50,
  centerX: am5.p100,
  paddingRight: 15
});

xRenderer.grid.template.setAll({
  location: 1
})

var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
  maxDeviation: 0.3,
  categoryField: "cargo_name",
 
  renderer: xRenderer,
  tooltip: am5.Tooltip.new(root, {})
}));



// console.log(xAxis);
// console.log("------------------------------------------------------");
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
  maxDeviation: 0.3,
  
  renderer: am5xy.AxisRendererY.new(root, {
    strokeOpacity: 0.1,
	title:"Expenditure (M)",
  })
}));

yAxis.children.unshift(am5.Label.new(root, {
    text: 'Cargo Qty (MT/1000)',
    textAlign: 'center',
    y: am5.p50,
    rotation: -90,
    fontWeight: 'bold'
  }));


// yAxis.title.text = "Expenditure (M)";


// Create series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
  name: "Series 1",
  text: "{valueYWorking.formatNumber('#.')}",
  
  xAxis: xAxis,
  yAxis: yAxis,
  valueYField: "total_qty",
  valueXField: "cargo_name",
  sequencedInterpolation: true,
  categoryXField:  "cargo_name",
 
  valueY:"{total_qty}",
	
  sprite: am5.Label.new(root, {
		text: "{valueYWorking.formatNumber('#.')}",
		
      fill: root.interfaceColors.get("000"),
     
      centerX: am5.p50,
      populateText: true
  }),
  tooltip: am5.Tooltip.new(root, {
    labelText: "{total_qty}"
  })

 

}));
// console.log(series.children.values[0].children.values);

Object.keys(series.children.values[0].children.values).forEach(function (key) {
  console.log(key+ ': ' + series.children.values[0].children.values[key])
});
// Object.keys(series.children._values[0].children.values).forEach(key => {
//   console.log("hiii")
//   console.log(key, obj[key]);
// });
series.columns.template.setAll({ cornerRadiusTL: 5, cornerRadiusTR: 5, strokeOpacity: 0 });
series.columns.template.adapters.add("fill", function(fill, target) {


  return chart.get("colors").getIndex(series.columns.indexOf(target));
});




series.columns.template.adapters.add("stroke", function(stroke, target) {
  return chart.get("colors").getIndex(series.columns.indexOf(target));
});


// Set data
		var data = dataldj;


		
			

xAxis.data.setAll(data);
series.data.setAll(data);


// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear(10000);
chart.appear(10000, 100);
	<?php
}
?>

function getData(elx)
{

    
	
	let txtFrom_Date= $('#txtFrom_Date').val();
    
	let txtTo_Date= $('#txtTo_Date').val();


    let current_url=window.location.href.split('?')[0];
	$(location).attr('href',current_url+'?txtFrom_Date='+txtFrom_Date+'&txtTo_Date='+txtTo_Date);
	
}
// function getData()
// {
// 	if($("#txtFrom_Date").val() != "" && $("#txtTo_Date").val() != "")
// 	{
// 		$('#DivOwner').html("");
// 		$('#DivOwner').html('<span style="text-align:center;display:block;"><img src="../../img/loading.gif" /></span>');
// 		$.post("options.php?id=51",{txtFrom_Date:""+$("#txtFrom_Date").val()+"",txtTo_Date:""+$("#txtTo_Date").val()+"",selBType:""+$("#selBType").val()+"", selCOASpot:""+$("#selCOASpot").val()+""}, function(html) {
// 			$('#DivOwner').html("");
// 			$('#DivOwner').html(html);
// 			$("#sf_list").dataTable();
// 		});
// 	}else{
// 		jAlert('Please select Date From & Date To', 'Alert Dialog');
// 	}
// }

function getPdf()
{
	location.href='allPdf.php?id=30&txtFrom_Date='+$("#txtFrom_Date").val()+'&txtTo_Date='+$("#txtTo_Date").val()+'&selBType='+$("#selBType").val();
}

function getExcel()
{
	location.href='allExcel.php?id=38&completion_d_from='+$("#txtFrom_Date").val()+'&completion_d_to='+$("#txtTo_Date").val();
}

function getData()
{
    if($("#txtFrom_Date").val() != "" && $("#txtTo_Date").val() != ""){
		let txtFrom_Date= $('#txtFrom_Date').val();
    
	let txtTo_Date= $('#txtTo_Date').val();

	

    let current_url=window.location.href.split('?')[0];
	$(location).attr('href',current_url+'?txtFrom_Date='+txtFrom_Date+'&txtTo_Date='+txtTo_Date);
	



            

    }else{
        jAlert('Please select Date From & Date To', 'Alert Dialog');
    }
}


function printDoc()
{
  $('#chartdiv canvas').first().css('width','1000px')

  document.title='Cargo Tonnage Report';
  window.print(); 
  $('cr-button .action-button').trigger('click');
   
}
var noPrintElements = [];

window.addEventListener("beforeprint", function(event) {
   var hideMe = document.getElementsByClassName("no-print");
   noPrintElements = [];
   Array.prototype.forEach.call(hideMe, function(item, index) {
      noPrintElements.push({"element": item, "display": item.style.display });
      item.style.display = 'none'; // hide the element
   });   
});

window.addEventListener("afterprint", function(event) {
   Array.prototype.forEach.call(noPrintElements, function(item, index) {
      item.element.style.display = item.display; // restore the element
   });      
   noPrintElements = []; // just to be on the safe side
});
</script>
		
</body>
</html>