<?php
global $ar;
$page_security = 'SA_SETUPDISPLAY'; 

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/ui.inc");

include_once("icodes.inc");

if(kv_get_option('hide_dashboard') == 0 ){ 
	$sql_cust_count = "SELECT COUNT(*) FROM `".TB_PREF."debtors_master`" ;
	$sql_cust_count_result = db_query($sql_cust_count, "could not get sales type");
	$cust_coubt = db_fetch_row($sql_cust_count_result);
	$sql_supp_count = "SELECT COUNT(*) FROM `".TB_PREF."suppliers`" ;
	$sql_supp_count_result = db_query($sql_supp_count, "could not get sales type");
	$sup_count= db_fetch_row($sql_supp_count_result);
	$class_balances = class_balances();
	if(kv_get_option('color_scheme') == 'dark' ){
		$color_scheme = '#ffffff'; 
	}else{
		$color_scheme= '#000000';
	}	
	
$ar = array( 1 => 'classbalancechart', 2 => 'sales', 3 => 'customers', 4 => 'suppliers', 5 => 'expenses', 6 => 'taxes', 7 => 'payments', 8 => 'salesinvoices', 9 => 'overduesales', 10 => 'bankbalance', 11 => 'overduesalesrecurrent',
12 => 'avgsalesdaily', 13 => 'overduepurchase', 14 => 'top10items', 15 => 'classbalancetable');
//echo base64_encode(serialize($ar));
$active_graph = kv_get_option('active_graph');
if($active_graph != false){
	$data_offdays = @unserialize(base64_decode($$active_graph));
	if ($data_offdays !== false) 
	    $opt =  array_values(unserialize(base64_decode($active_graph)));
	else
	    $opt = array_values($ar);
}
?>
<style>
.spanclosechart{ float:right;font-weight: bold;margin-right: -10px; cursor:pointer; }

@media (max-width: 600px){
	.container-fluid {
	    font-size: 20px;
	    max-width: 100%;
	}
	h4.title { font-size: 0.7em; }
}
</style>
<!-- Morris -->  
<link rel="stylesheet" href='<?php echo $path_to_root."/themes/".user_theme()."/css/morris.css"; ?>'>
<link rel="stylesheet" href='<?php echo $path_to_root."/themes/".user_theme()."/css/grid.css"; ?>'>
<script src="<?php echo $path_to_root."/themes/".user_theme()."/js/raphael-min.js"; ?>"></script>
<script src="<?php echo $path_to_root."/themes/".user_theme()."/js/morris.min.js"; ?>"></script>
<div class="container-fluid">
	<div class="row">
		<div class="dashboard_stats" > 
		<div class="col-lg-3 col-md-6 col-sm-6 ">
			<div class="card card-stats card_box">				
				<div class="card-content-tiny">
					<div class="title"><?php echo $cust_coubt[0]; ?></div>
					<p class="stats"><?php echo _("Customers"); ?></p>
				</div>
				<div class="card-icon">
					<i class="icon-account_circle"></i>
				</div>	
				<div style="clear: both;" > </div>			
			</div>
		</div>
		<div class="col-lg-3 col-md-6 col-sm-6 ">
			<div class="card card-stats card_box">
				
				<div class="card-content-tiny">
					<div class="title"><?php echo kv_get_current_balance(); ?></div>
					<p class="stats"><?php echo _("Current Balance"); ?> </p>
				</div>
				<div class="card-icon">
					<i class="icon-account_balance_wallet"></i>
				</div>	
				<div style="clear: both;" > </div>			
			</div>
		</div>

		<div class="col-lg-3 col-md-6 col-sm-6 ">
			<div class="card card-stats card_box">				
				<div class="card-content-tiny">
					<div class="title"><?php echo $sup_count[0]; ?></div>
					<p class="stats"><?php echo _("Suppliers"); ?></p>
				</div>
				<div class="card-icon"><i class="icon-account_box"></i></div>	
				<div style="clear: both;" > </div>			
			</div>
		</div>
		
		<div class="col-lg-3 col-md-6 col-sm-6">
			<div class="card card-stats card_box">				
				<div class="card-content-tiny">
					<div class="title"><?php 
					$sql_count_items = "SELECT COUNT(*) FROM `".TB_PREF."item_codes`"; 
					$sql_items_count_result = db_query($sql_count_items, "could not get sales type");

					$items_count= db_fetch_row($sql_items_count_result);
					echo $items_count[0];?></div>
					<p class="stats"><?php echo _("Items and Inventory"); ?></p>
				</div>
				<div class="card-icon"><i class="icon-pie_chart_outlined"></i></div>	
				<div style="clear: both;" > </div>			
			</div>
		</div>
		<div style="clear: both;" > </div>	
	</div>
</div> 
	<?php   
		if(!isset($opt) || (isset($opt) && in_array( 'classbalancechart', $opt))){
		//Class Balances
		echo '<div class="col-sm-6 " id="item-10" data-class="classbalancechart"><div class="card panel-body pheight400 "> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Class Balances').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive">  <div class="col-md-12">  <div class="col-md-6">  </div> <div class="col-md-6" > <select id="ClassPeriods" class="form-control"> <option value="Till Now">'._('Till Now').'</option><option value="Last Week">'._('Last Week').'</option><option value="Last Month">'._('Last Month').'</option> <option value="This Month">'._('This Month').'</option> <option value="Last Quarter Year">'._('Last Quarter Year').'</option></select></div> </div></div> <div id="Class_Balance_chart" style="height: 250px;margin-top:40px;"></div>  </div></div>' ;
		}
		if(!isset($opt) || (isset($opt) && in_array( 'sales', $opt))){
		// Sales 
		echo '<div class="col-sm-6" id="item-9" data-class="sales"><div class="card panel-body pheight400 "> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Sales').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive">  <div class="col-md-12">  <div class="col-md-6">  </div> <div class="col-md-6" > <select id="SalesPeriods" class="form-control"> <option value="Till Now">'._('Till Now').'</option><option value="Last Week">'._('Last Week').'</option><option value="Last Month">'._('Last Month').'</option> <option value="This Month">'._('This Month').'</option> <option value="Last Quarter Year">'._('Last Quarter Year').'</option></select></div> </div></div><div id="Area_chart" style="height: 250px;margin-top:40px;"></div></div></div>'; 
		}
		if(!isset($opt) || (isset($opt) && in_array( 'customers', $opt))){
		//Customers 
		echo '<div class="col-sm-6" id="item-15" data-class="customers"> <div class="card panel-body pheight400"> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Customers').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive">
				<div class="row" ><div class="col-md-4"> </div><div class="col-md-8" > <select id="CustomerPeriods" class="form-control"> <option value="Till Now">'._('Till Now').'</option><option value="Last Week">'._('Last Week').'</option><option value="Last Month">'._('Last Month').'</option> <option value="This Month">'._('This Month').'</option> <option value="Last Quarter Year">'._('Last Quarter Year').'</option></select></div> </div> 
				<div id="donut-customer" style="height: 250px;"></div></div></div></div>'; 
        }
		if(!isset($opt) || (isset($opt) && in_array( 'suppliers', $opt))){// Suppliers
        echo '<div class="col-sm-6" id="item-16" data-class="suppliers"><div class="card panel-body pheight400"> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Suppliers').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive">
							<div class="row"><div class="col-md-4"> </div> <div class="col-md-8"> <select id="SupplierPeriods" class="form-control"> <option value="Till Now">'._('Till Now').'</option><option value="Last Week">'._('Last Week').'</option><option value="Last Month">'._('Last Month').'</option> <option value="This Month">'._('This Month').'</option> <option value="Last Quarter Year">'._('Last Quarter Year').'</option></select></div></div> 
							 <div id="donut-supplier" style="height: 250px;"></div></div> </div></div>';
		}
		if(!isset($opt) || (isset($opt) &&in_array( 'expenses', $opt)) ){ //Expenses
			echo  '<div class="col-sm-6" id="item-16" data-class="expenses"><div class="card panel-body pheight400"> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Expenses').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive">
                     <div class="row"> <div class="col-md-4"> </div> <div class="col-md-8"> <select id="ExpensesPeriods" class="form-control"> <option value="Till Now">'._('Till Now').'</option><option value="Last Week">'._('Last Week').'</option><option value="Last Month">'._('Last Month').'</option> <option value="This Month">'._('This Month').'</option> <option value="Last Quarter Year">'._('Last Quarter Year').'</option></select></div></div><div id="expenses_chart" style="height: 250px;"></div></div></div></div>';
		}
		if(!isset($opt) || (isset($opt) && in_array( 'taxes', $opt))){
        //Taxes
        echo '<div class="col-sm-6" id="item-16" data-class="taxes"><div class="card panel-body pheight400"> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Taxes').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive">
        	<div class="row"> <div class="col-md-4"> </div> <div class="col-md-8"> <select id="TaxPeriods" class="form-control"> <option value="Till Now">'._('Till Now').'</option><option value="Last Week">'._('Last Week').'</option><option value="Last Month">'._('Last Month').'</option> <option value="This Month">'._('This Month').'</option> <option value="Last Quarter Year">'._('Last Quarter Year').'</option></select></div></div>
        	<div id="donut-Taxes" style="height:250px;" ></div>
							<!-- <div class="row"> <div class="col-md-7 "> <p style="font-weight:500;padding-left:15px">Net Payable Tax</p></div> <div class="col-md-5 ">  <p id="GrandTaxTotal">0.00</p> </div> </div>-->  </div> </div></div>'; 
		}
		if(!isset($opt) || (isset($opt) && in_array( 'payments', $opt))){// Payments
		 $Sales_payment_5 = Top_five_invoices(12); 
		 $payment_lines= '';
		 foreach($Sales_payment_5 as $payment){
			$payment_lines .='<tr><th scope="row">'.$payment['reference'].'</th> <td>'.$payment['name'].'</td> <td><span class="label-info" style="padding:0 5px;">'.$payment['curr_code'].'</span></td> <td>'.$payment['TotalAmount'].'</td> </tr>'; 
		 }
		echo'<div class="col-sm-6" id="item-16" data-class="payments"><div class="card panel-body pheight400"> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Payments').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive"> <table class="table "><thead> <tr> <th>#</th><th>'._('Name').'</th> <th>'._('Currency').'</th> <th>'._('Total Amount').'</th></tr> </thead><tbody>'.$payment_lines.'</tbody></table></div></div></div> '; 
		
		}
		if(!isset($opt) || (isset($opt) && in_array( 'salesinvoices', $opt))){//Sales Invoice
		$Sales_invoice_5 = Top_five_invoices(); 
		$invoice_lines = ''; 
		foreach($Sales_invoice_5 as $invoice){
			$invoice_lines .= '<tr><th scope="row">'.$invoice['reference'].'</th> <td>'.$invoice['name'].'</td> <td><span class="label-info" style="padding:0 5px;">'.$invoice['due_date'].'</span></td> <td>'.round($invoice['TotalAmount']).'</td> </tr>';
		}
		
		echo'<div class="col-sm-6" id="item-16" data-class="salesinvoices"><div class="card panel-body pheight400"> <div class="card-header" data-background-color="orange"><h4 class="title">'._('Sales Invoices').'<span class="spanclosechart"> X </span></h4></div><div class="card-content table-responsive"><table class="table "><thead> <tr> <th>#</th><th>'._('Name').'</th> <th>'._('Currency').'</th> <th>'._('Total Amount').'</th></tr> </thead><tbody>'.$invoice_lines.'</tbody></table></div></div></div>';
		}
		if(!isset($opt) || (isset($opt) && in_array( 'overduesales', $opt))){
		
			echo '<div class="col-sm-6" data-class="overduesales"><div class="card panel-body"> <div class="card-header" data-background-color="orange">
	          <h4 class="title">'._("Overdue Sales Invoices").'<span class="spanclosechart"> X </span></h4> </div> <div class="card-content table-responsive big">
	          '. kv_customer_trans().'</div> </div></div>';
		}
		if(!isset($opt) || (isset($opt) && in_array( 'bankbalance', $opt))){  
		echo '	<div class="col-sm-6" data-class="bankbalance">
							<div class="card panel-body ">
	                            <div class="card-header" data-background-color="orange">
	                                <h4 class="title">'._("Bank Account Balances").' <span class="spanclosechart"> X </span></h4>
	                            </div>
	                            <div class="card-content table-responsive">'. kv_bank_balance().'</div>
	                        </div>
						</div>';
			}
		if(!isset($opt) || (isset($opt) && in_array( 'overduesalesrecurrent', $opt))){ 
			echo '<div class="col-sm-6" data-class="overduesalesrecurrent">
							<div class="card panel-body ">
	                            <div class="card-header" data-background-color="orange">
	                                <h4 class="title">'._("Overdue Recurrent Sales Invoices").' <span class="spanclosechart"> X </span></h4>
	                            </div>
	                            <div class="card-content table-responsive big">'. kv_customer_recurrent_invoices().' </div>
	                        </div>
						</div>';
			}
		if(!isset($opt) || (isset($opt) && in_array( 'avgsalesdaily', $opt))){ 
			echo '<div class="col-sm-6" data-class="avgsalesdaily">
							<div class="card panel-body ">
	                            <div class="card-header" data-background-color="orange">
	                                <h4 class="title">'._("Average Daily Sales").' <span class="spanclosechart"> X </span></h4>
	                            </div>
	                            <div class="card-content table-responsive big">'. kv_weekly_sales().' </div>
	                        </div>
						</div>';
			}
		if(!isset($opt) || (isset($opt) && in_array( 'overduepurchase', $opt))){ 					
			echo '<div class="col-sm-6" data-class="overduepurchase">
							<div class="card panel-body ">
	                            <div class="card-header" data-background-color="orange">
	                                <h4 class="title">'._("Overdue Purchase Invoices").' <span class="spanclosechart"> X </span></h4>
	                            </div>
	                            <div class="card-content table-responsive big">'.  kv_supplier_trans().' </div>
	                        </div>
						</div>';
		}
		if(!isset($opt) || (isset($opt) && in_array( 'top10items', $opt))){
			echo '<div class="col-sm-6" data-class="top10items">
							<div class="card panel-body ">
	                            <div class="card-header" data-background-color="orange">
	                                <h4 class="title">'._("Top 10 Selling Items and Inventory").' <span class="spanclosechart"> X </span></h4>
	                            </div>
	                            <div class="card-content table-responsive">'. kv_stock_top().' </div>
	                        </div>
						</div>';
				}
		if(!isset($opt) || (isset($opt) && in_array( 'classbalancetable', $opt))){
			echo '<div class="col-sm-6" data-class="classbalancetable">
							<div class="card panel-body ">
	                            <div class="card-header" data-background-color="orange">
	                                <h4 class="title">'. _("Class Balances").' <span class="spanclosechart"> X </span></h4>
	                            </div>
	                            <div class="card-content table-responsive">'.  kv_gl_top().'</div>
	                        </div>
						</div>';

		}

$protocol = $protocol = $_SERVER['REQUEST_SCHEME'] . '://'; //stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$actual_link = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

$actual_link =  strtok($actual_link, '?');
$actual_link = str_replace("index.php", "", $actual_link);
 ?>

<script>
$(function(){ 
 $(".spanclosechart").on("click", function(){
	 var summa = $(this).parent().parent().parent().parent();
		 var dataclass = summa. data('class'); 		 
		 $.ajax({
				type: "POST",
				url: "<?php echo $actual_link; ?>themes/onlinksoft/includes/ajax.php?Remove_Chart="+dataclass,
				data: 0,
				success: function(data){
				  if(data == 'true'){
					  summa.hide();
				  }				  
				}
		  });
	  }); 
}); 
if($("#donut-Taxes").length){ //  #################  
  var Tax_Donut_Chart = Morris.Donut({
    element: 'donut-Taxes',
    behaveLikeLine: true,
    parseTime : false,
    data: [{"value":"","label":"", labelColor: '<?php echo $color_scheme; ?>'}],  
    colors: [ '#f26c4f', '#00a651', '#00bff3', '#0072bc','#ff6264', '#455064',  '#707f9b', '#b92527',  '#242d3c', '#d13c3e', '#d13c3e',  '#ff6264', '#ffaaab', '#b92527'],
    redraw: true,
  });
  $("#TaxPeriods").on("change", function(){
       var option = $(this).val(); 
       $.ajax({
          type: "POST",
          url: "<?php echo $actual_link; ?>themes/onlinksoft/includes/ajax.php?Tax_chart="+option,
          data: 0,
          dataType: 'json',
          success: function(taxdata){      
        		//var grandtotal = data.grandtotal;	 // delete data.grandtotal;	  //delete data[4];
        		console.log(taxdata);
            Tax_Donut_Chart.setData(taxdata);
        		// var arr = $.parseJSON(data);  //alert(data.grandtotal);	  //$("#GrandTaxTotal").html(grandtotal);
            /* setCookie('numbers',data,3); $('.flash').show(); $('.flash').html("Template Updated")*/
          }
    });
  }); 
 }

 if($("#expenses_chart").length){ //   ######### 
	 var Expenses_Bar_Chart = Morris.Bar({
	  element: 'expenses_chart',
	  behaveLikeLine: true,
	  parseTime : false,
	  data: [{ "y": "Nothing" , "a" : "0", "labelColor": '<?php echo $color_scheme; ?>'} ],
	  xkey: 'y',
	  ykeys: ['a'],
	  labels: ['Expenses' ],
	  barColors: ['#f26c4f', '#00a651', '#00bff3', '#0072bc', '#707f9b', '#455064', '#242d3c', '#b92527', '#d13c3e', '#ff6264', '#ffaaab'],
	  redraw: true
	});
	 $("#ExpensesPeriods").on("change", function(){
		 var option = $(this).val(); 
		 $.ajax({
				type: "POST",
				url: "<?php echo $actual_link; ?>themes/onlinksoft/includes/ajax.php?Expense_chart="+option,
				data: 0,
				dataType: 'json',
				success: function(data){
				  console.log(data);
				  Expenses_Bar_Chart.setData(data);
				   /* setCookie('numbers',data,3); $('.flash').show(); $('.flash').html("Template Updated")*/
				}
		  });
	  }); 
  }

    //  ##########################################
   if($("#Class_Balance_chart").length){
      var Line_Chart = Morris.Line({
        element: 'Class_Balance_chart',
        behaveLikeLine: true,
        parseTime : false,
        data: [ <?php foreach($class_balances as $balance) { echo " { class: '".$balance['class_name']."', value: ".abs($balance['total'])." }," ; } ?> ],    
        xkey: 'class',
        ykeys: ['value'],
        labels: ['Value'],
        lineColors: ['#f26c4f', '#00a651', '#00bff3', '#0072bc', '#707f9b', '#455064', '#242d3c', '#b92527', '#d13c3e', '#ff6264', '#ffaaab'],
        redraw: true,
        pointFillColors: ['#455064']
      });

      $("#ClassPeriods").on("change", function(){
         var type = $(this).val(); 
         $.ajax({
            type: "POST",
            url: "<?php echo $actual_link; ?>themes/onlinksoft/includes/ajax.php?Line_chart="+type,
            data: 0,
            dataType: 'json',
            success: function(data){    console.log(data);
              Line_Chart.setData(data);
              /* setCookie('numbers',data,3); $('.flash').show(); $('.flash').html("Template Updated")*/
            }
        });
      }); 
   }	

if($("#Area_chart").length){//  ################   
    var Area_chart = Morris.Area({
      element: 'Area_chart',  
      behaveLikeLine: true,
      parseTime : false, 
      data: [ ],
      xkey: 'y',
      ykeys: ['a', 'b'],
      labels: ['Sales', 'Cost'],
      pointFillColors: ['#707f9b'],
      pointStrokeColors: ['#ffaaab'],
      lineColors: ['#f26c4f', '#00a651', '#00bff3'],
      redraw: true      
    });

    $("#SalesPeriods").on("change", function(){
     var selected_user_ID = $(this).val(); 
     $.ajax({
            type: "POST",
            url: "<?php echo $actual_link; ?>themes/onlinksoft/includes/ajax.php?Area_chart="+selected_user_ID,
            data: 0,
            dataType: 'json',
            success: function(data){
              console.log(data);
              Area_chart.setData(data);
            }
          });
  }); 
}

if($("#donut-customer").length){//  #################  
    var Customer_Donut_Chart = Morris.Donut({
      element: 'donut-customer',
      behaveLikeLine: true,
      parseTime : false,
      data: [{"value":"","label":"", "labelColor": '<?php echo $color_scheme; ?>'}],
      colors: ['#f26c4f', '#00a651', '#00bff3', '#0072bc', '#707f9b', '#455064', '#242d3c', '#b92527', '#d13c3e', '#ff6264', '#ffaaab'],
      redraw: true,
    });
    $("#CustomerPeriods").on("change", function(){
         var option = $(this).val(); 
         $.ajax({
            type: "POST",
            url: "<?php echo $actual_link; ?>themes/onlinksoft/includes/ajax.php?Customer_chart="+option,
            data: 0,
            dataType: 'json',
            success: function(data){
             console.log(data);
              Customer_Donut_Chart.setData(data);
              /* setCookie('numbers',data,3); $('.flash').show(); $('.flash').html("Template Updated")*/
            }
        });
    });
}

if($("#donut-supplier").length){ //  #################  
var Supplier_Donut_Chart = Morris.Donut({
  element: 'donut-supplier',
  behaveLikeLine: true,
  parseTime : false,
  data: [{"value":"","label":"", "labelColor": '<?php echo $color_scheme; ?>'}],  
  colors: [  '#ff6264', '#455064', '#d13c3e', '#d13c3e',  '#ff6264', '#ffaaab', '#f26c4f', '#00a651', '#00bff3', '#0072bc', '#b92527', '#707f9b', '#b92527',  '#242d3c'],
  redraw: true,
});
$("#SupplierPeriods").on("change", function(){
     var option = $(this).val(); 
     $.ajax({
        type: "POST",
        url: "<?php echo $actual_link; ?>themes/onlinksoft/includes/ajax.php?Supplier_chart="+option,
        data: 0,
        dataType: 'json',        
        success: function(data){
          console.log(data);
          Supplier_Donut_Chart.setData(data);
          /* setCookie('numbers',data,3); $('.flash').show(); $('.flash').html("Template Updated")*/
        }
      });
  }); 
 }

  $(document).ready(function(e){
      $("#SalesPeriods").trigger("change");
      $("#CustomerPeriods").trigger("change");
      $("#SupplierPeriods").trigger("change");
      $("#ExpensesPeriods").trigger("change");
      $("#TaxPeriods").trigger("change");
  }); 
 </script>
 <div style="clear:both;" > </div>
<?php } else { 

echo '<div style="line-height:200px; text-align:center;font-size:24px; vertical-align:middle;" > '._('Page not found').' </div>'; 

} ?>