<?php
session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
include ('../inc/invfunctions.php');
include ('../inc/repfunctions.php');
if(isset($_SESSION["axeslogin"]) && $_SESSION["axeslogin"] == true){
    $_SESSION['cuPages']='home.php'; 
    $cuPage='home.php';
    $aid=$_SESSION['uid'];
    $uty=$_SESSION['utype'];    
    $brid=$_SESSION['abrid'];    
}else{
    header('Location:../index.php');
    exit;    
}
$mhead='home';
if(get_fild_data('tbl_setting','1','sval')==0){$menuh = 'Dashboard';}else{$menuh = 'ড্যাশবোর্ড';}
$phead='home';
if(get_fild_data('tbl_setting','1','sval')==0){$page = 'Dashboard';}else{$page = 'ড্যাশবোর্ড';}
$dtnow = date("Y-m-d h:i:s", time());
$today = strftime("%Y-%m-%d", time());
?>
<?php


if(isset($_POST['ibrid']) && $_POST['ibrid']!=''){
    $ibrid=$_POST['ibrid'];    
}else{
    $ibrid=$brid;    
}
?> 


<?php 

$start=date("Y-m-d", time());
$end=date("Y-m-d", time());

if(isset($_POST['fdate']) && isset($_POST['tdate'])){
$start=$_POST['fdate'];    
$end=$_POST['tdate'];	
}

if(isset($_POST['month'])){
    $start=date("Y-m-d", time());
    $end=date("Y-m-d", time());
}


if(isset($_POST['month'])){
$start=date('Y-m-01');
$end=date('Y-m-t');
}

if(isset($_POST['week'])){
    $start=date('Y-m-d', strtotime('monday this week'));
    $end=date('Y-m-d', strtotime('sunday this week'));
}

if(isset($_POST['year'])){
    $buisness=get_fild_data('tbl_limitset',1,'strDate');
    $buisness = explode('-', $buisness);

    $start_month   = $buisness[1];
    $end_month = $start_month -1;
    if ($start_month == 1) {
        $end_month = 12;
    }
    
    $start_year = date('Y');
    //if current month is less than start month change start year to last year
    if (date('n') < $start_month) {
        $start_year = $start_year - 1;
    }

    $end_year = date('Y');
    //if current month is greater than end month change end year to next year
    if (date('n') > $end_month) {
        $end_year = $start_year + 1;
    }
    $start_date = $start_year . '-' . str_pad($start_month, 2, 0, STR_PAD_LEFT) . '-01';
    $end_date = $end_year . '-' . str_pad($end_month, 2, 0, STR_PAD_LEFT) . '-01';
    $end_date = date('Y-m-t', strtotime($end_date));
    $start=$start_date;
    $end=$end_date;
}
?>


<?php
include('../layout/head.php');
include('../layout/header.php');
include('../layout/side_nav.php');
$sql21="SELECT * FROM tbl_limitset WHERE id=1";
$query21=mysqli_query($con,$sql21)or die(mysqli_error($con));
$row21=mysqli_fetch_array($query21);

$expdate=$row21['expDate'];
$startTimeStamp = strtotime("$today");
$endTimeStamp = strtotime("$expdate");

$timeDiff = abs($endTimeStamp - $startTimeStamp);

$numberDays = $timeDiff/86400;  // 86400 seconds in one day

// and you might want to convert to integer
$numberDays = intval($numberDays);
?>
<?php if($adm['home']==1){?> 
<div class="content-wrapper">
    <?php include('../layout/page_head.php'); ?>
    <!-- Main content -->
    <section class="content">
        <!-- Main row -->
        <div class="row">
            <?php if($numberDays<5){ ?>
                <div class="alert alert-danger alert-dismissable" >
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <i class="zmdi zmdi-block pr-15 pull-left"></i><p class="pull-left">Your license will be expired in <?php echo $numberDays; ?> days.Please, renew the license before it gets expired</p> 
                    <div class="clearfix"></div>
			    </div>  


            <?php } ?>

            <div class="col-md-4 col-xs-12 " >
                <div class="box " style="height: 458px;">
                    <div class="box-header">
                        <i class="fa fa-bell"></i>

                        <h3 class="box-title">
                            Notifications
                        </h3>
                    </div>
                    <div class="box-body" >
                        <div class="col-md-12 no-padding db-notification-container" style="">
                            <table id="" class="table notification_table">
                                    <?php 
                                    if(get_fild_data('tbl_setting','12','sval')==0){
                                        if($uty=='1'){ 
                                            $sql="SELECT * FROM tbl_cheqman ORDER BY apdate DESC,id DESC limit 5"; 
                                        }else{
                                            $sql="SELECT * FROM tbl_cheqman WHERE brid='$brid'ORDER BY apdate DESC,id DESC limit 5"; 
                                        } 
                                        $query=mysqli_query($con,$sql)or die(mysqli_error($con));
                                        while ($row=mysqli_fetch_array($query)){
                                            $invno=$row['refinv'];     
                                            ?>

                                            <tr>
                                                <td width="30px" class="db-noti-icons"><i class="fa fa-shopping-cart"></i></td> 
                                                <td>Cheque No <span class="label label-success"><?php echo $row['chkno'];?></span> &nbsp; &nbsp; &nbsp;<?php if($row['type']=='SU'){echo get_fild_data('tbl_supplier',$row['clientid'],'name');}else{echo get_fild_data('tbl_customer',$row['clientid'],'name');}?></span>&nbsp;&nbsp;<strong><?php echo 'DT:  '. date("d M Y", strtotime($row['chkdt'])); ?></strong>  <strong><?php if($row['paymod']=='PAY'){echo 'Given';}else{ echo 'Receive';}?></strong> </td>                                           
                                                <td class="db-noti-action-links"><a  href="ban_checkman.php" class="btn btn-flat bg-purple btn-xs ">View</a> </td>                                          
                                            </tr>
                                        <?php }} ?>  
                                        <?php 
                                        if($uty=='1'){ 
                                            $sql="SELECT * FROM tbl_purchase ORDER BY apdate DESC,id DESC limit 5"; 
                                        }else{
                                            $sql="SELECT * FROM tbl_purchase WHERE brid='$brid'ORDER BY apdate DESC,id DESC limit 5"; 
                                        } 
                                        $query=mysqli_query($con,$sql)or die(mysqli_error($con));
                                        while ($row=mysqli_fetch_array($query)){
                                            $invno=$row['invno'];     
                                            ?>

                                            <tr>
                                                <td width="30px" class="db-noti-icons"><i class="fa fa-shopping-cart"></i></td> 
                                                <td>Purchase <span class="label label-success"><?php echo $row['invno'];?></span> &nbsp;<?php if($row['type']=='SU'){echo get_fild_data('tbl_supplier',$row['supid'],'name');}else{echo get_fild_data('tbl_customer',$row['supid'],'name');}?></span><strong><?php echo 'T: '.numtolocal($row['total'],get_fild_data('tbl_currency','1','symbol')); ?></strong><br><strong><?php //echo 'D: '.numtolocal($cashst,get_fild_data('tbl_currency','1','symbol')); ?></strong></td>                                           
                                                <td class="db-noti-action-links"><a  href="" class="btn btn-flat bg-purple btn-xs popup" data-callback="">View</a> </td>                                          
                                            </tr>
                                        <?php } ?>  
                                        <!-- sales list -->
                                        <?php 
                                        if($uty=='1'){ 
                                            $sql="SELECT * FROM tbl_sales ORDER BY apdate DESC,id DESC limit 5"; 
                                        }else{
                                            $sql="SELECT * FROM tbl_sales WHERE brid='$brid' ORDER BY apdate DESC,id DESC limit 5"; 
                                        } 
                                        $query=mysqli_query($con,$sql)or die(mysqli_error($con));
                                        while ($row=mysqli_fetch_array($query)){
                                            $invno=$row['invno'];    
                                    //$cashst=($row['total']-get_invcash($invno,'P'));    
                                            ?>

                                            <tr>
                                                <td width="30px" class="db-noti-icons"><i class="fa fa-shopping-cart"></i></td> 
                                                <td>Sales <span class="label label-success"><?php echo $row['invno'];?></span> &nbsp;<strong><?php echo 'T: '.numtolocal($row['total'],get_fild_data('tbl_currency','1','symbol')); ?></strong><br><strong><?php //echo 'D: '.numtolocal($cashst,get_fild_data('tbl_currency','1','symbol')); ?></strong></td>                                           
                                                <td class="db-noti-action-links"><a  href="" class="btn btn-flat bg-purple btn-xs popup" data-callback="">View</a> </td>                                          
                                            </tr>
                                        <?php } ?>
                                <!-- <tr>
                                    <td width="30px" class="db-noti-icons"><i class="fa fa-shopping-cart"></i></td> 
                                    <td>Sale <span class="label label-success"><?php echo $row['invno'];?></span> &nbsp;<?php if($row['type']=='SU'){echo get_fild_data('tbl_supplier',$row['supid'],'name');}else{echo get_fild_data('tbl_customer',$row['supid'],'name');}?></span><strong><?php echo 'T: '.numtolocal($row['total'],get_fild_data('tbl_currency','1','symbol')); ?></strong><br><strong><?php echo 'D: '.numtolocal($cashst,get_fild_data('tbl_currency','1','symbol')); ?></strong></td>                                           
                                    <td class="db-noti-action-links"><a  href="" class="btn btn-flat bg-purple btn-xs popup" data-callback="refresh_dashboard">View</a> <a   class="btn btn-flat bg-purple  btn-xs" onclick="delete_db_notification(77,this)"><i class="fa fa-trash" style="color:#fff"></i></a></td>                                          
                                </tr> -->
                            </table>
                        </div>
                    </div>

                </div> 
                <div class="box box-solid">
                    <div class="box-header with-border">
                      <h3 class="box-title">Due Purchase Cost</h3>
                   </div>
                    <div class="box-body">   
                        <div class="col-md-12 table-responsive">
                            <table class="table table-bordered table-striped" id="datarec">
                                <thead>
                                   <tr>
                                      <th style="width:40px; text-align:center;">SN</th>   
                                      <th>Invoice</th> 
                                      <!-- <th>Name</th>    -->
                                      <th class="text-center">Total</th>    
                                      <th>Due</th>   
                                   </tr>
                                </thead>   
                            
                                <tbody>
                                    <?php 
                                        $i=0;
                                        if($uty=='1'){ 
                                            $sql="SELECT * FROM tbl_purchase ORDER BY apdate DESC,id DESC limit 5"; 
                                        }else{
                                            $sql="SELECT * FROM tbl_purchase WHERE brid='$brid'ORDER BY apdate DESC,id DESC limit 5"; 
                                        } 
                                        $query=mysqli_query($con,$sql)or die(mysqli_error($con));
                                        while ($row=mysqli_fetch_array($query)){
                                            $i=$i+1;
                                            $invno=$row['invno'];    
                // $cashst=($row['total']-get_invcash($invno,'P'));    
                                    ?>
                                    <tr>
                                        <td><?php echo $i;?></td>
                                        <td><?php echo $row['invno'];?></td>
                                        <!-- <td>
                                            <?php if($row['type']=='SU'){echo get_fild_data('tbl_supplier',$row['supid'],'name');}else{echo get_fild_data('tbl_customer',$row['supid'],'name');}?>
                                        </td> -->
                                        <td>
                                            <?php echo numtolocal($row['total'],get_fild_data('tbl_currency','1','symbol')); ?> 
                                        </td>
                                        <td>
                                            <?php echo $cashst=($row['total']-get_invcash($invno,'P'));?>
                                        </td>
                                    </tr>
                                    <?php }?>
                                </tbody>   
                            </table>
                        </div>
                    </div>
                </div>
                <div class="box box-solid">
                    <div class="box-header with-border">
                      <h3 class="box-title">Due Sales Cost</h3>
                   </div>
                    <div class="box-body">   
                        <div class="col-md-12 table-responsive">
                            <table class="table table-bordered table-striped" id="datarec">
                                <thead>
                                   <tr>
                                      <th style="width:40px; text-align:center;">SN</th>   
                                      <th>Invoice</th>   
                                      <th class="text-center">Total</th>    
                                      <th>Due</th>   
                                   </tr>
                                </thead>    
                                <tbody>
                                    <?php 
                                    $j=0;
                                        if($uty=='1'){ 
                                            $sql="SELECT * FROM tbl_sales ORDER BY apdate DESC,id DESC limit 5"; 
                                        }else{
                                            $sql="SELECT * FROM tbl_sales WHERE brid='$brid' ORDER BY apdate DESC,id DESC limit 5"; 
                                        } 
                                        $query=mysqli_query($con,$sql)or die(mysqli_error($con));
                                        while ($row=mysqli_fetch_array($query)){
                                            $j=$j+1;
                                            $invno=$row['invno'];    
                //$cashst=($row['total']-get_invcash($invno,'P'));    
                                    ?>
                                    <tr>
                                        <td><?php echo $j;?></td>
                                        <td><?php echo $row['invno'];?></td>
                                        <td><?php echo numtolocal($row['total'],get_fild_data('tbl_currency','1','symbol')); ?></td>
                                        <td><?php echo $cashst=($row['total']-get_invcash($invno,'P')); ?></td>
                                    </tr>
                                <?php }?>
                                </tbody>   
                            </table>
                        </div>
                    </div>
                </div>


            </div>    

<div class="col-md-8 shortcuts">
<div class="row">
<div class="col-md-11">
<table >
<tr>
<td></td>
<form action="home.php"  method="post" accept-charset="utf-8">
<td style="width: 123px;">
<div class="form-group">
<label>Date From</label>
<div class="input-group date datetimepicker">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" value="<?php if($start){echo $start; }else{echo get_fild_data('tbl_limitset',1,'strDate');}?>" name='fdate'  class="form-control" placeholder="FROM DATE" readonly="true"  />
</div>
</div>
</td>
<td style="width: 123px;">
<div class="form-group">
<label>Date To</label>
<div class="input-group date datetimepicker">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" value="<?php if($end){echo $end;}else{echo $today;} ?>"  class="form-control"  name='tdate'  placeholder="TO DATE" readonly="true"  />
</div>
</div>
</td>
<td>
<div class="form-group" style="padding-top: 23px;">
<input type="submit" value="Submit"  class="btn btn-flat bg-purple "  />
</div>
</td>
</form>
<form action="home.php"  method="post" accept-charset="utf-8">
<td>
<div class="form-group" style="padding-top: 23px;">
<input type="hidden" value="today" name='today' class="btn btn-flat bg-purple "  />
<input type="submit" value="Today"  class="btn btn-flat bg-purple "  />
</div>
</td>
</form> 
<form action="home.php"  method="post" accept-charset="utf-8">
<td>
<div class="form-group" style="padding-top: 23px;">
<input type="hidden" value="week" name='week' class="btn btn-flat bg-purple "  />
<input type="submit" value="This Week"  class="btn btn-flat bg-purple "  />
</div>
</td>
</form>
<form action="home.php"  method="post" accept-charset="utf-8">
<td>
<div class="form-group" style="padding-top: 23px;">
<input type="hidden" value="month" name='month' class="btn btn-flat bg-purple "  />
<input type="submit" value="This Month"  class="btn btn-flat bg-purple "  />
</div>
</td>
</form>
<form action="home.php"  method="post" accept-charset="utf-8">
<td>
<div class="form-group" style="padding-top: 23px;">
<input type="hidden" value="year" name='year' class="btn btn-flat bg-purple "  />
<input type="submit" value="This Year"  class="btn btn-flat bg-purple "  />
</div>
</td>
</form>
</tr>
</table>
   
</div>
</div>
    <div class="row">
        <div class="col-md-3 col-xs-6">
            <!-- small box -->
            <a href="">
                <div class="small-box">
                    <div class="ribbon"><span>Overall</span></div>
                    <?php    
                    if($uty=='1'){ 
                        if($start && $end){
                            $result= mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_purchase Where apdate BETWEEN '$start' AND '$end'"); 
                        }else{
                            $result= mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_purchase"); 
                        }

                       
                    }else{
                        if($start && $end){
                           $result= mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_purchase  WHERE brid='$brid' AND apdate BETWEEN '$start' AND '$end'"); 
                        }else{
                            $result= mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_purchase  WHERE brid='$brid'");

                        }
                    }                

                    $row = mysqli_fetch_assoc($result); 
                    $sum = $row['value_sum'];
                    ?>
                    
                    <div class="inner">
                        <h4 id=""><?php echo $sum ?></h4>
                        <p>Purchase</p>
                    </div>
                    <div class="icon">
                        <i class="fa fa-handshake-o"></i>
                    </div>
                    

                </div>
            </a>
        </div>
        <div class="col-md-3 col-xs-6">
            <!-- small box -->
            <a href="">
                <div class="small-box ">
                    <div class="ribbon"><span>Overall</span></div>
                    <?php 
                    
                    if($uty=='1'){ 
                        if($start && $end){
                            $result1= mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_sales Where apdate BETWEEN '$start' AND '$end'"); 
                        }else{
                            $result1= mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_sales"); 
                        }

                       
                    }else{
                        if($start && $end){
                           $result1= mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_sales  WHERE brid='$brid' AND apdate BETWEEN '$start' AND '$end'"); 
                        }else{
                            $result1 =mysqli_query($con, "SELECT SUM(total) AS value_sum FROM tbl_sales  WHERE brid='$brid'");

                        }
                    }               

                    $row1 = mysqli_fetch_assoc($result1); 
                    $sum1 = $row1['value_sum'];
                    ?>
                    
                    <div class="inner">
                        <h4 id=""><?php echo $sum1 ?></h4>
                        <p>Sales</p>
                    </div>
                    <div class="icon">
                        <i class="fa fa-sun-o"></i>
                    </div>
                </div>
            </a>

        </div>

        <div class="col-md-3 col-xs-6">

            <a href="">
                <!-- small box -->
                <div class="small-box ">
                    <div class="ribbon"><span>Overall</span></div>
                    <div class="inner">
                        <?php

                            if($uty=='1'){ 
                                if($start && $end){
                                    $result6= mysqli_query($con, "SELECT SUM(amount) AS value_sum FROM tbl_expenses Where apdate BETWEEN '$start' AND '$end'"); 
                                }else{
                                    $result6= mysqli_query($con, "SELECT SUM(amount) AS value_sum FROM tbl_expenses"); 
                                }

                            
                            }else{
                                if($start && $end){
                                $result6= mysqli_query($con, "SELECT SUM(amount) AS value_sum FROM tbl_expenses  WHERE brid='$brid' AND apdate BETWEEN '$start' AND '$end'"); 
                                }else{
                                    $result6=  mysqli_query($con, "SELECT SUM(amount) AS value_sum FROM tbl_expenses  WHERE brid='$brid'");

                                }
                            }

                        $row6 = mysqli_fetch_assoc($result6); 
                        $sum6 = $row6['value_sum'];
                        ?>
                        <h4 id=""><?php echo $sum6 ?></h4>
                        <p>Expense</p>
                    </div>
                    <div class="icon">
                        <i class="fa fa-rocket"></i>
                    </div>
                </div>
            </a>

        </div>
        <div class="col-md-3 col-xs-6">
            <a href="">
                <!-- small box -->
                <div class="small-box">
                    <div class="ribbon"><span>Overall</span></div>
                    <div class="icon">
                        <i class="fa fa-shopping-cart"></i>
                    </div>
                    <div class="inner">
                        <?php 
                            $twvt=0;      
                    
                            if($start && $end){
                                $rcdebit=get_goupvalnew('5','D','D','C',$start,$end);
                                $rccredit=get_goupvalnew('5','C','D','C',$start,$end);
                                $rcnet=($rccredit-$rcdebit);
                                $ecdebit=get_goupvalnew('4','D','D','C',$start,$end);
                                $eccredit=get_goupvalnew('4','C','D','C',$start,$end);
                                $ecnet=($ecdebit-$eccredit);

                                $twvt=number_format(($rcnet-$ecnet),2);
                                  
                             }else{

                                    $start=get_fild_data('tbl_limitset',1,'strDate');
                                    $end=get_fild_data('tbl_limitset',1,'expDate');

                                    $rcdebit=get_goupvalnew('5','D','D','C',$start,$end);
                                    $rccredit=get_goupvalnew('5','C','D','C',$start,$end);
                                    $rcnet=($rccredit-$rcdebit);
                                    $ecdebit=get_goupvalnew('4','D','D','C',$start,$end);
                                    $eccredit=get_goupvalnew('4','C','D','C',$start,$end);
                                    $ecnet=($ecdebit-$eccredit);
                                    $twvt=number_format(($rcnet-$ecnet),2);
                              
 
                             }              

                     

                        ?>
                        <?php if(get_pagesecurity('30','views','P')){?> 
                            <h4 id=""><?php echo $twvt; ?></h4>
                        <?php } ?>
                        <p>Profit & Loss</p>
                    </div>
                </div>
            </a>
        </div>
        <div class="clearfix"></div>
    </div>


    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-solid">
                    <div class="box-header with-border">
                      <h3 class="box-title">Low Stock Product</h3>
                   </div>
                   <div class="box-body">   
                        <div class="table-responsive">
                        <div class="cart cart-sm">  
                            <table class="table table-bordered table-striped" >
                                <thead>
                                    <tr>
                                        <th style="width:40px;" class="text-center">SN</th>
                                        <th>Name</th>
                                        <th>SKU</th>          
                                        <th class="text-center">In-Stock</th>   
                                    </tr>   
                                </thead>
                            </table> 
                            <div class="cart-det style-3 item" style="padding:0px;">   
                            <table class="table table-bordered table-striped" >    
                                <tbody id="tradata">
                                    <?php
                                    $sql="SELECT pid,name,pcode,SUM(avqty) AS avqty FROM tbl_brstock GROUP BY pid ORDER BY name ASC LIMIT 25";    
                                    $query=mysqli_query($con,$sql)or die(mysqli_error($con));
                                    while ($row=mysqli_fetch_array($query)){
                                       
                                        if($row['avqty']<2) {  
                                        ?>
                                        
                                        <tr>
                                            <td class="text-center" ><?php echo count_id();?></td>
                                            <td><b class="prodetail" id="PI_<?php echo $row['pid'];?>" style="cursor: pointer;"><?php echo $row['name']; ?></b></td>
                                            <td><?php echo $row['pcode']; ?></td>
                                            <td class="text-center"><?php echo $row['avqty']; ?></td>     
                                        </tr>    
                                    <?php }} ?>     
                                </tbody>
                            </table>
                                        </div>
                                        </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                
            </div>
            <div class="col-md-6">
                
            </div>

        </div>
         
    </section>                                   
</div>


</div>
</div>
</div>
</div>
<?php } ?>
<?php include('../layout/quick.php');?>   
<style>
.cash_balance_box{
    min-height: 71px;
    margin-bottom: 1px;
}
.cash_balance_box .info-box-icon{
    height: 71px;
    width: 50px;
    line-height: 71px;
    font-size: 18px;
}
.cash_balance_box .info-box-content{
    margin-left: 50px;
    text-transform: uppercase;
}
.cash_balance_box .info-box-number{
    font-size: 15px;
}
#overview_services th{
    padding: 5px;
}
</style>

<!-- /.row (main row) -->

</section>   
<!-- /.main content -->    
</div>

<?php include('../layout/footer.php');?>
<!-- page script -->
<script src="../plugins/chart/Chart.js"></script>
<input type='hidden' id='current_page_name' value='dashboard'/>
<script type="text/javascript">
    $(document).ready(function () {
        $('.filter_date').datepicker({format: "yyyy-mm-dd", autoclose: true, clearBtn: true, orientation: 'auto bottom', });
        $('.filter_date_pie').datepicker({format: "yyyy-mm-dd", autoclose: true, clearBtn: true, orientation: 'auto top', });
        refresh_dashboard();

        setTimeout(function () {
            get_enquiries_list();
        }, 800);

        setTimeout(function () {
            load_bussiness_overview();
        }, 1500);
        setTimeout(function () {
            $(".bussiness_insights_wrapper").load("axe_busincsid.php");
        }, 1800);



        setTimeout(function () {
            load_sales_chart_by_emp();
        }, 2000);
        setTimeout(function () {
            load_purchase_graph();
        }, 2500);
        setTimeout(function () {
            load_outstanding_graphs();
        }, 3000);
    });
    
    function refresh_dashboard() {
        $.ajax({
            type: "POST",
            url: "axe_ref_dashboard.php",
            cache: false,
            dataType: 'json',
            data: {'null_post': 1},
            timeout: 15000,
            success: function (data)
            {
                var norecords = '<p class="text-center" style="font-size: 25px;margin-top: 100px;color: #ccc;" >- No Records Found - </p>';
                var norecords2 = '<p class="text-center" style="font-size: 20px;margin-top: 50px;color: #ccc;" >- No Notification Found - </p>';
                if (data) {
                    if (data['dash_notifications'])
                        $('#dash_notifications').html(data['dash_notifications']);
                    else
                        $('#dash_notifications').html(norecords2);
//crm
if (data['crm_list'])
    $('#crm-dashboard').html(data['crm_list']);
else
    $('#crm-dashboard').html(norecords);
//leads
if (data['lead_list'])
    $('#lead-dashboard').html(data['lead_list']);
else
    $('#lead-dashboard').html(norecords);
//opprtunites
if (data['opportunity_list'])
    $('#opportunity-dashboard').html(data['opportunity_list']);
else
    $('#opportunity-dashboard').html(norecords);
//sales
if (data['sales_list'])
    $('#sale-dashboard').html(data['sales_list']);
else
    $('#sale-dashboard').html(norecords);
//broadcasts
if (data['broadcast_list'])
    $('#broadcast-dashboard').html(data['broadcast_list']);
else
    $('#broadcast-dashboard').html(norecords);
//careers                    
if (data['dash_careers'])
    $('#career-dashboard').html(data['dash_careers']);
else
    $('#career-dashboard').html(norecords);
$('#attendance-dashboard').html(data['attendance_list']);
//counts
$('#crm-count').text(data['module_count']['crm']);
$('#lead-count').text(data['module_count']['leads']);
$('#opportunity-count').text(data['module_count']['opportunities']);
$('#sale-count').text(data['module_count']['sales']);
}

},
error: function (jqXHR, textStatus, errorThrown) {}

});
    }

    function load_bussiness_overview(){
        var branch = $('#bussiness_overview_form').find('#bussiness_overview_branch').val();
        var date_from = $('#bussiness_overview_form').find('#bussiness_overview_date_from').val();
        var date_to = $('#bussiness_overview_form').find('#bussiness_overview_date_to').val();
        $.ajax({
            type: "POST",
            url: "axe_busines_ovw.php",
            cache: false,
            data: {'branch': branch, 'date_from': date_from, 'date_to': date_to},
            timeout: 15000,
            dataType: 'json',
            success: function (data)
            {
                $('.bussiness_overview_results').html(data['html']);
                business_overview_graph(data['graph']['months'], data['graph']['values']);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus);
            }

        });
        return false;
    }

    function business_overview_graph(months, monthvalues){
//['January', 'February', 'March', 'April', 'May', 'June', 'July']
//[65, 59, 80, 81, 56, 55, 40]

$('.business_overview_graph_div').html('<canvas id="business_overview_graph" style="height:250px"></canvas>');
var areaChartCanvas = $('#business_overview_graph').get(0).getContext('2d')
var areaChart = new Chart(areaChartCanvas)

var areaChartData = {
    labels: months,
    datasets: [
    {
        label: 'Net Income',
        fillColor: '#c3b533',
        strokeColor: '#c3b533',
        pointColor: '#c3b533',
        pointStrokeColor: '#c3b533',
        pointHighlightFill: '#c3b533',
        pointHighlightStroke: '#c3b533',
        data: monthvalues
    }
    ]
}

var areaChartOptions = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: 'rgba(0,0,0,.05)',
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].lineColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
//Boolean - whether to make the chart responsive to window resizing
responsive: true
}

//Create the line chart
areaChart.Line(areaChartData, areaChartOptions)
}    

function load_sales_chart_by_emp() {

    $.ajax({
        type: "POST",
        url: "axe_saleschart.php",
        cache: false,
        dataType: 'json',
        data: $('#sale_chart_form').serialize(),
        timeout: 15000,
        success: function (data)
        {

            sale_chart(data['chart_data']);
            $('.sales_chart_members').html(data['member_icons']);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
        }

    });
    return false;
}

function sale_chart(chart_data) {
    $('.sales_chart_container').html('<canvas id="sale_chart_graph" style="height:253px"></canvas>');
    var lineChartCanvas = $('#sale_chart_graph').get(0).getContext('2d');
    var lineChart = new Chart(lineChartCanvas);
    var options = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: 'rgba(0,0,0,.05)',
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: true,
//Number - Radius of each point dot in pixels
pointDotRadius: 2,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].lineColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
}

options.datasetFill = false;
lineChart.Line(chart_data, options);
}    

// function load_purchase_graph(){
// var branch = $('#purchase_graph_form').find('#purchase_graph_branch').val();
// var date_from = $('#purchase_graph_form').find('#purchase_graph_date_from').val();
// var date_to = $('#purchase_graph_form').find('#purchase_graph_date_to').val();
// if (date_from && date_to) {
// $('#purchase_graph_form').find('#done').val('Loading..');
// $('#purchase_graph_form').find('#done').prop('disabled', 'true');
// $.ajax({
// type: "POST",
// url: "axe_loadsalegraph.php",
// cache: false,
// data: {'branch': branch, 'date_from': date_from, 'date_to': date_to},
// timeout: 15000,
// 'dataType': 'json',
// success: function (data)
// {
// $('#purchase_graph_form').find('#done').val('generate');
// $('#purchase_graph_form').find('#done').prop('disabled', false);
// sales_graphs(data['ticketing_baggage']['data'], data['ticketing_baggage']['keys'], 'chart_sales_ticketing');
// sales_graphs(data['visa_visa_message']['data'], data['visa_visa_message']['keys'], 'chart_sales_visa');
// sales_graphs(data['hotel']['data'], data['hotel']['keys'], 'chart_sales_hotel');
// sales_graphs(data['ins_otheres']['data'], data['ins_otheres']['keys'], 'chart_sales_others');
// },
// error: function (jqXHR, textStatus, errorThrown) {
// alert(textStatus);
// $('#purchase_graph_form').find('#done').val('generate');
// $('#purchase_graph_form').find('#done').prop('disabled', false);
// }
// });
// } else {
// toaster('Date From and To is required')
// }
// return false;
// }

// function load_outstanding_graphs() {
// var branch = $('#outstanding_graph_form').find('#outstanding_graph_branch').val();
// var date_from = $('#outstanding_graph_form').find('#outstanding_graph_date_from').val();
// var date_to = $('#outstanding_graph_form').find('#outstanding_graph_date_to').val();
// if (date_from && date_to) {
// $('#outstanding_graph_form').find('#done').val('Loading..');
// $('#outstanding_graph_form').find('#done').prop('disabled', 'true');
// $.ajax({
// type: "POST",
// url: "axe_outstgrapg.php",
// cache: false,
// data: {'branch': branch, 'date_from': date_from, 'date_to': date_to},
// timeout: 15000,
// 'dataType': 'json',
// success: function (data)
// {
// $('#outstanding_graph_form').find('#done').val('generate');
// $('#outstanding_graph_form').find('#done').prop('disabled', false);
// oustanding_graph(data['ticketing_baggage'], data['interval'], 'outstanding_sales_ticketing');
// oustanding_graph(data['visa_visa_message'], data['interval'], 'outstanding_sales_visa');
// oustanding_graph(data['hotel'], data['interval'], 'outstanding_sales_hotel');
// oustanding_graph(data['ins_otheres'], data['interval'], 'outstanding_sales_others');
// },
// error: function (jqXHR, textStatus, errorThrown) {
// $('#outstanding_graph_form').find('#done').val('generate');
// $('#outstanding_graph_form').find('#done').prop('disabled', false);
// }
// });
// } else {
// toaster('Date From and To is required')
// }

// return false;
// }

function oustanding_graph(data, date_interval, CanvasId)
{

    var total_sales = data['total_sales'];
    var total_receipt = data['total_receipt'];
    var outstanding = data['outstanding'];
    if (num(total_sales) > 0 || num(total_receipt) > 0 || num(outstanding) > 0) {
        $('#' + CanvasId).html('<canvas id="' + CanvasId + '_canvas" style="height:250px"></canvas>');
        $('#' + CanvasId).show();
        $('.' + CanvasId + '_msg').addClass('hidden');
        var areaChartData = {
            labels: [date_interval, ],
            datasets: [
            {
                label: 'Sales',
                fillColor: '#0092cc',
                strokeColor: '#0092cc',
                pointColor: '#0092cc',
                pointStrokeColor: '#0092cc',
                pointHighlightFill: '#0092cc',
                pointHighlightStroke: '#0092cc',
                data: [total_sales]
            },
            {
                label: 'Receipts',
                fillColor: '#029602',
                strokeColor: '#029602',
                pointColor: '#029602',
                pointStrokeColor: '#029602',
                pointHighlightFill: '#029602',
                pointHighlightStroke: '#029602',
                data: [total_receipt]
            },
            {
                label: 'Outstanding',
                fillColor: '#c3b533',
                strokeColor: '#c3b533',
                pointColor: '#c3b533',
                pointStrokeColor: '#c3b533',
                pointHighlightFill: '#c3b533',
                pointHighlightStroke: '#c3b533',
                data: [outstanding]
            }
            ]
        }

        var barChartCanvas = $('#' + CanvasId + '_canvas').get(0).getContext('2d');
        var barChart = new Chart(barChartCanvas);
        var barChartData = areaChartData;
        var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: 'rgba(0,0,0,.05)',
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke: true,
//Number - Pixel width of the bar stroke
barStrokeWidth: 2,
//Number - Spacing between each of the X value sets
barValueSpacing: 5,
//Number - Spacing between data sets within X values
barDatasetSpacing: 1,
//String - A legend template
legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
//Boolean - whether to make the chart responsive
responsive: true,
tooltipFontSize: 10,
maintainAspectRatio: true
}

barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions);
} else {

    $('#' + CanvasId).html('');
    $('#' + CanvasId).hide();
    $('.' + CanvasId + '_msg').removeClass('hidden');
}
}    

function sales_graphs(PieData, keyVals, canvasId){

    if (PieData.length > 0 && canvasId) {
        $('#' + canvasId).html('<canvas id="' + canvasId + '_canvas" style="height:250px"></canvas>');
        $('.' + canvasId + '_msg').addClass('hidden');
        $('#' + canvasId).show();
        $('#' + canvasId + '_keys').show();
// Get context with jQuery - using jQuery's .get() method.
var pieChartCanvas = $('#' + canvasId + '_canvas').get(0).getContext('2d');
var pieChart = new Chart(pieChartCanvas);
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: '#fff',
//Number - The width of each segment stroke
segmentStrokeWidth: 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: 'easeOutBounce',
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//Boolean - whether to make the chart responsive to window resizing

// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
tooltipFontSize: 9,
responsive: true,
//String - A legend template
legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
}
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
if (keyVals) {
    var htmls = '';
    for (var i = 0; i < keyVals.length; i++) {
        htmls = htmls + '<li><a><i style="color:' + keyVals[i]['color'] + '" class="fa fa-square"></i></a><small> ' + keyVals[i]['value'] + '</small></li>';
        $('#' + canvasId + '_keys').html(htmls);
    }
}
} else {

    $('.' + canvasId + '_msg').removeClass('hidden');
    $('#' + canvasId + '_keys').hide();
    $('#' + canvasId).html('');
    $('#' + canvasId).hide('');
}    
}

function validate_target_chart_filter() {

    $.ajax({
        type: "POST",
        url: "axe_tagerghmem.php",
        cache: false,
        dataType: 'json',
        data: $('#target_chart_form').serialize(),
        timeout: 15000,
        success: function (data)
        {
            if (data['is_graph'] == 1) {
                target_chart(data['chart_data']);
            } else {
                $('.target_chart_container').html('<p>No Records Found</p>');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
        }

    });
    return false;
}    
</script>    
<!-- /page script -->
</html>