<?php
require_once "include/db.php";
include "include/auth.php";
include "header.php"; 
if(isset($_REQUEST['note-dismiss'])){
    $admin_alert_id = $_REQUEST['note-dismiss'];
    $note_dismiss_query = "UPDATE admin_alert SET admin_alert_show = 4 WHERE admin_alert_id = $admin_alert_id";
    $note_dismiss_query = mysqli_query($conn, $note_dismiss_query);
}
?>
<div id="page-wrapper">
    
<?php

$time12 = strtotime("-1 year", time());
$twelve_mnt = date("Y-m-d h:i:s", $time12);
$twelve_mnt_date = date("Y-m-d", $time12);


$time11 = strtotime("-11 month", time());
$eleven_mnt = date("Y-m-d h:i:s", $time11);

$time1 = strtotime("-1 month", time());
$one_mnt = date("Y-m-d h:i:s", $time1);
$one_mnt_date = date("Y-m-d", $time1);

?>

<?php if($user_type == 'admin'){     ?>
<div class="row">
<div class="col-md-2">
    <span class="head-estimate-stat" style = 'font-size:20px' id = "selected_period"></span>
    </div>
<div class="form-group col-md-1">
<select id = "year-selected" class = "form-control select_dash" name="year" onchange = "year_change()">    
<?php
$current_year = date('Y', time()); 
$prev_year = $current_year - 1;?>
<option class = "option_dash" value="<?php echo $current_year; ?>" selected><?php echo $current_year; ?></option>
<?php
for($i = $prev_year; $i >= 2019; $i--){
?>
<option class = "option_dash" value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
?>   
    

    </select>
    </div>
    <div class="form-group col-md-1">
    <select id = "filter-selected" class = "form-control  select_dash" name="year" onchange = "select_filter()">
    <option class = "option_dash" value="y" selected>Year</option>
    <option class = "option_dash" value="m">Month</option>
    <option class = "option_dash" value="q">Quarter</option>    
    </select>
    </div>
    <div class="form-group col-md-2">
    <select id = "value-selected" class = "form-control  select_dash" name="year" onchange = "set_new_values()" style = 'display:none'>
      
        </select>
    </div>
    
    <div class="form-group col-md-2">
        <label for=""><i class="fa fa-dollar fa-fw"></i>Profit / Loss</label>
        <span class="" style = 'font-size:16px; ' id = "period_profit"></span>
    </div>
    <div class="form-group col-md-2">
    <label for=""><i class="fa fa-briefcase fa-fw"></i>Vendor Pay</label>
    <span class="" style = 'font-size:16px;' id = "period_vendor_pay"></span>
    </div>
    <div class="form-group col-md-2">
    <label for=""><i class="fa fa-users fa-fw"></i>Staff Pay</label>
    <span class="" style = 'font-size:16px;' id = "period_staff_pay"></span>
    </div>
    </div>


    <div class="row">
    <div class="col-md-6">
                        <div class="panel panel-default">
                        <div class="panel-heading">
                            <span class= "head-estimate-stat"><i class="fa fa-send fa-fw"></i> Invoices</span>
                        </div>
                         <!-- /.panel-heading -->
                         <div class="panel-body">                                    
                                <div style= "float:left;font-weight:bolder">$<span id='invoice_generated'></span> INVOICED</div>
                                       
                                    <br>
                                    <div>
                                        <div style= "float:left;font-weight:bolder;"><span style= "font-size:20px">$</span><span id='invoice_paid' style= "font-size:20px"></span> PAID</div>
                                        <div style= "float:right;font-weight:bolder;"><span style= "font-size:20px">$</span><span id='invoice_overdue' style= "font-size:20px"></span> OVERDUE</div>
                                    </div>
                                    <br><br>
                                    <div style="color:grey">
                                        <span style= "float:left">PAID</span>
                                        <span style= "float:right">OVERDUE</span>
                                    </div>
                                    <br> 
                                
                                    <div class="progress prog-item">
                                        <div class="progress-bar prog-item3" id = 'invoice_progress' style = "width:0%;"></div>
                                    </div>
                                 
                                    <div>
                                       <!--  <div style= "float:left;font-weight:bolder">$<span id=''></span> VENDOR PAY&nbsp;&nbsp;&nbsp;</div><div style="color:grey"></div>  -->                                       
                                    </div>
                                </div>
                                <!-- /.panel-body -->
                    </div>
                            
                        </div>
                        <div class="col-md-6">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <span class= "head-estimate-stat"><i class="fa fa-paperclip fa-fw"></i> Estimates</span>
                                </div>
                                <!-- /.panel-heading -->
                                <div class="panel-body">                                    
                                <div style= "float:left;font-weight:bolder">$<span id='estimate_generated'></span> TOTAL ESTIMATE</div>
                                       
                                    <br>
                                    <div>
                                        <div style= "float:left;font-weight:bolder;"><span style= "font-size:20px">$</span><span id='estimate_paid' style= "font-size:20px"></span> PAID</div>
                                        <div style= "float:right;font-weight:bolder;"><span style= "font-size:20px">$</span><span id='estimate_overdue' style= "font-size:20px"></span> OVERDUE</div>
                                    </div>
                                    <br><br>
                                    <div style="color:grey">
                                        <span style= "float:left">PAID</span>
                                        <span style= "float:right">OVERDUE</span>
                                    </div>
                                    <br> 
                                
                                    <div class="progress prog-item">
                                        <div class="progress-bar prog-item2" id = 'estimate_progress' style = "width:0%;"></div>
                                    </div>
                                 
                                   <!--  <div>
                                        <div style= "float:left;font-weight:bolder"><span id=''></span> &nbsp;&nbsp;&nbsp;</div><div style="color:grey"></div>                                       
                                    </div> -->
                                </div>
                                <!-- /.panel-body -->
                            </div>                                
                        </div>
                
                   
                    </div>
<div class="row">
                <div class="col-md-<?php if($user_type == 'admin'){echo 8;}else{ echo 12;}     ?>">
                    
                    <div class="row">                         
                        <div class="col-md-<?php if($user_type == 'admin'){ echo 4; }elseif($user_type == 'staff'){ echo 6;}?>">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-arrow-up fa-fw"></i> Vendor Pay

                                    <?php ?>
                                </div>
                                <div class="panel-body">
                                    <div id="line-chart" style = 'height: 250px;'></div> 
                                </div>
                            </div>
                        </div>
                        <!-- </div> --> 
                        <?php          if($user_type == 'admin'){     ?>
                        <div class="col-md-4">
                        <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-user fa-fw"></i> Staff Pay
                                </div>
                                <div class="panel-body">
                                    <div id="line-chart_staff" style = 'height: 250px;'></div>
                                </div>
                            </div>
                         
                        </div>   <?php	
		
    }?> 

                        <div class="col-md-<?php if($user_type == 'admin'){ echo 4; }elseif($user_type == 'staff'){ echo 6;}?>">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-dollar fa-fw"></i> Client Payments
                                </div>
                                <div class="panel-body">
                                    <div id="line-chart_client" style = 'height: 250px;'></div>
                                </div>
                            </div>
                        </div>  
                      
                    </div>
                    <?php          if($user_type == 'admin'){     ?>
                    <div class="row">                         
                        <div class="col-md-12">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-bar-chart-o fa-fw"></i> Monthly Sales Data
                                </div>
                                <div class="panel-body">
                                    <div id="morris-area-chart"></div>
                                </div>
                            </div>
                        </div>     
                    </div>
                    <?php          }     ?>
                </div>
                <?php          if($user_type == 'admin'){     ?>
                <div class="col-md-4">
                <div class="row"> 
              
               
                                               
                        <div class="col-md-12">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-bar-chart-o fa-fw"></i> Annual Data
                                </div>
                                <div class="panel-body">
                                    <div id="morris-bar-chart"></div>
                                </div>
                            </div>
                        </div>

                    </div>
                                    
                    <div class="row">
                    <div class="col-md-12">
        <?php
    

    $query_admin_alert = "SELECT * FROM admin_alert WHERE admin_alert_show IS NULL ORDER BY admin_alert_id DESC";
    $run_admin_alert = mysqli_query($conn, $query_admin_alert);
    if(mysqli_num_rows($run_admin_alert)>0){
    echo '<h4>Approval Required</h4>';
        foreach($run_admin_alert as $alerts_admin){
            $id = $alerts_admin['admin_alert_id'];
            $emp_id = $alerts_admin['employee_id'];
            $adm_id = $alerts_admin['admin_id'];
            $link = $alerts_admin['admin_alert_link'];
            $activity = $alerts_admin['admin_alert_activity'];
            $emp_name = '';
            if(isset($adm_id)){
                if(strlen($adm_id > 0)){
                    $query111 = "SELECT admin_fname,admin_lname FROM admin WHERE admin_id = $adm_id";
                    $run111 = mysqli_query($conn, $query111);
                    if(mysqli_num_rows($run111) >0){
                        $row111 = mysqli_fetch_array($run111);
                    
                        $emp_name = $row111['admin_fname'] .' '.$row111['admin_lname'];
                    
                    }
                }
            }
            if(isset($emp_id)){
                if(strlen($emp_id > 0)){
                    $query111 = "SELECT employee_fname,employee_lname FROM employee WHERE employee_id = $emp_id";
                    $run111 = mysqli_query($conn, $query111);
                    if(mysqli_num_rows($run111) >0){
                        $row111 = mysqli_fetch_array($run111);
                    
                        $emp_name = $row111['employee_fname'] .' '.$row111['employee_lname'];
                    
                    }
                }
            }               

                
            echo "<div class='alert alert-danger'>
                    <strong><a style = '' class='btn btn-warning' href='$link'>Check</a></strong> &nbsp $emp_name has added $activity
                    <a style = 'float:right' class='btn btn-success' href='index.php?note-dismiss=$id'>Dismiss</a></div>";

                   
        }
    }
    $minus_one_hr = strtotime("- 2 hours", time());
    $minus_one_hr = date("Y-m-d H:i:s", $minus_one_hr);    
                    
    $chron_alert = 'yes';
    $query_chron_problem = "SELECT * FROM client_pay_mail_cron_status WHERE init_time >= '$minus_one_hr' ORDER BY id DESC";  
    $run_chron_problem = mysqli_query($conn, $query_chron_problem);
    if(mysqli_num_rows($run_chron_problem) > 0){
        while($row_chron_problem = mysqli_fetch_array($run_chron_problem)){
            $chron_status = $row_chron_problem['status']; 
            if(isset($chron_status)){
                if($chron_status == 'success'){
                    $chron_alert = 'no';
                }
            }
            break;          
        }
    }    
    if($chron_alert == 'yes'){
        echo '<h4>Attention Required</h4>';
        echo "<div class='alert alert-danger'>
        <strong></strong> Client Payment Email Settlement system has issues currently.
       </div>";
    }
?>
 </div>
        </div> <!-- row -->                   
                    </div>

<?php   } 
?>
        </div>
        <!-- /#page-wrapper -->
 <?php
      
     if ($user_type == 'staff'){
        ?>  
<div class="row">
        <div class="col-md-12">
        <?php  
        
    $query_admin_alert = "SELECT * FROM admin_alert WHERE admin_alert_show = 0 and employee_id= $employee_id ORDER BY admin_alert_id DESC";

    $run_admin_alert = mysqli_query($conn, $query_admin_alert);
        if(mysqli_num_rows($run_admin_alert)>0){
    echo '<h4>Approval Denied</h4>';
            foreach($run_admin_alert as $alerts_admin){
                $id = $alerts_admin['admin_alert_id'];
                $admin_id = $alerts_admin['admin_id'];
                $link = $alerts_admin['admin_alert_link'];
                $activity = $alerts_admin['admin_alert_activity'];
    
                $query111 = "SELECT admin_fname, admin_lname FROM admin WHERE admin_id = $admin_id";
                $run111 = mysqli_query($conn, $query111);
                if(mysqli_num_rows($run111) >0){
                    $row111 = mysqli_fetch_array($run111);
                
                    $admin_name = $row111['admin_fname'] .' '.$row111['admin_lname'];
                   
                }
                echo "<div class='alert alert-danger'>
                        <strong><a style = '' class='btn btn-success' href='index.php?note-dismiss=$id'>Dismiss</a></strong> &nbsp $admin_name has declined your $activity
                        </div>";   
            }
    }

    $query_admin_alert = "SELECT * FROM admin_alert WHERE admin_alert_show = 1 and employee_id= $employee_id ORDER BY admin_alert_id DESC";

    $run_admin_alert = mysqli_query($conn, $query_admin_alert);
        if(mysqli_num_rows($run_admin_alert)>0){
    echo '<h4>Approved</h4>';
            foreach($run_admin_alert as $alerts_admin){
                $id = $alerts_admin['admin_alert_id'];
                $admin_id = $alerts_admin['admin_id'];
                $link = $alerts_admin['admin_alert_link'];
                $activity = $alerts_admin['admin_alert_activity'];
    
                $query111 = "SELECT admin_fname, admin_lname FROM admin WHERE admin_id = $admin_id";
                $run111 = mysqli_query($conn, $query111);
                if(mysqli_num_rows($run111) >0){
                    $row111 = mysqli_fetch_array($run111);
                
                    $admin_name = $row111['admin_fname'] .' '.$row111['admin_lname'];
                   
                }
                echo "<div class='alert alert-success'>
                        <strong><a style = '' class='btn btn-success' href='index.php?note-dismiss=$id'>Dismiss</a></strong> &nbsp $admin_name has accepted your $activity
                        </div>";         
            }           
    } 

?>
 </div> </div>
<?php       
   }

        ?>     

<?php }if($user_type == 'staff'){   ?>

   
    <div class="row">
    <div class="col-md-3">
    <h4 style= 'color:#0b57a4;'>RECENT TRANSACTIONS</h4>
    </div>
        <div class="col-lg-9">
        <style>
        p a, p a:hover{
  color: #505250;
  text-decoration: none;
  font-size:20px;
}
        </style>    
<?php
$arr_prop_order_list = array();
$query_bid_item = "SELECT * FROM invoice WHERE employee_id = $employee_id AND is_delete IS NULL ORDER BY create_time DESC";
$run_bid_item = mysqli_query($conn, $query_bid_item);
if(mysqli_num_rows($run_bid_item) >0){
    while($row_bid_item = mysqli_fetch_array($run_bid_item)){
        $invoice_id =  $row_bid_item['invoice_id'];
        $invoice_no = $row_bid_item['invoice_no'];
        $bid_wo_no = '';        
        $invoice_amount = $row_bid_item['invoice_amount'];
        $client_pay_ref = $row_bid_item['client_pay_ref'];
        if(strlen($row_bid_item['employee_id']) > 0){
            $staff_id = $row_bid_item['employee_id'];
            $emp_details_query = "SELECT * FROM employee WHERE employee_id = $staff_id AND status = 'active'";
            $emp_details_run = mysqli_query($conn, $emp_details_query);
            $emp_details_row = mysqli_fetch_array($emp_details_run);
            $staff_name = $emp_details_row['employee_fname'];
        }elseif(strlen($row_bid_item['admin_id']) > 0){
            $admin_id = $row_bid_item['admin_id'];
            $admin_details_query = "SELECT * FROM admin WHERE admin_id = $admin_id AND status = 'active'";
            $admin_details_run = mysqli_query($conn, $admin_details_query);
            $admin_details_row = mysqli_fetch_array($admin_details_run);
            $staff_name = $admin_details_row['admin_fname'] . ' ' . $admin_details_row['admin_lname'];
        }else{
            $staff_name = '';
        }
        if($row_bid_item['client_pay'] != NULL){
            $client_pay = $row_bid_item['client_pay'];
        }else{
            $client_pay = '';
        }
        if($row_bid_item['client_pay_date'] != NULL){
            $client_pay_date = $row_bid_item['client_pay_date'];
            $client_pay_date = strtotime($client_pay_date);
            $client_pay_date= date('m-d-Y', $client_pay_date);  

        }else{
            $client_pay_date = '';
        }
        $client_name = '';
        if(strlen($row_bid_item['client_id']) > 0){
            $client_id = $row_bid_item['client_id'];
            $client_details_query = "SELECT * FROM client WHERE client_id = $client_id";
            $client_details_run = mysqli_query($conn, $client_details_query);
            $client_details_row = mysqli_fetch_array($client_details_run);
            $client_name = $client_details_row['client_name'];
        }
        if($row_bid_item['vendor_pay'] != NULL){
            $crew_pay = $row_bid_item['vendor_pay'];
        }else{
            $crew_pay = '';
        }
        if($row_bid_item['vendor_pay_date'] != NULL){
            $vendor_pay_date = $row_bid_item['vendor_pay_date'];
            $timestamp2 = strtotime($vendor_pay_date);
            $vendor_pay_date= date('m-d-Y', $timestamp2);  

        }else{
            $vendor_pay_date = '';
        }
       
        $date = $row_bid_item['create_time'];
        $arr_inv_details = array("type"=>"invoice","inv_no"=>"$invoice_no","bid_no"=>"$bid_wo_no","amount"=>"$invoice_amount","client_pay"=>"$client_pay","client_pay_date"=>"$client_pay_date","vendor_pay"=>"$crew_pay","vendor_pay_date"=>"$vendor_pay_date","date"=>"$date","client_pay_ref"=>"$client_pay_ref","staff"=>"$staff_name","inv_id"=>"$invoice_id","bid_id"=>"","client_name" => "$client_name");
        array_push($arr_prop_order_list, $arr_inv_details);

    }
}

$query_bid_detail = "SELECT * FROM bid WHERE employee_id = $employee_id AND is_delete IS NULL ORDER BY create_time DESC";
$run_bid_detail = mysqli_query($conn, $query_bid_detail);
if(mysqli_num_rows($run_bid_detail) >0){
    while($row_bid_detail = mysqli_fetch_array($run_bid_detail)){
        $bid_id =  $row_bid_detail['bid_id'];       
        $bid_wo_no = $row_bid_detail['bid_wo_no'];        
        $bid_amount = $row_bid_detail['bid_amount'];       
        $date = $row_bid_detail['create_time'];
        $client_name = '';
        if(strlen($row_bid_detail['client_id']) > 0){
            $client_id = $row_bid_detail['client_id'];
            $client_details_query = "SELECT * FROM client WHERE client_id = $client_id";
            $client_details_run = mysqli_query($conn, $client_details_query);
            $client_details_row = mysqli_fetch_array($client_details_run);
            $client_name = $client_details_row['client_name'];
        }
        if(strlen($row_bid_detail['employee_id']) > 0){
            $staff_id = $row_bid_detail['employee_id'];
            $emp_details_query = "SELECT * FROM employee WHERE employee_id = $staff_id AND status = 'active'";
            $emp_details_run = mysqli_query($conn, $emp_details_query);
            $emp_details_row = mysqli_fetch_array($emp_details_run);
            $staff_name = $emp_details_row['employee_fname'];

        }elseif(strlen($row_bid_detail['admin_id']) > 0){
            $admin_id = $row_bid_detail['admin_id'];
            $admin_details_query = "SELECT * FROM admin WHERE admin_id = $admin_id AND status = 'active'";
            $admin_details_run = mysqli_query($conn, $admin_details_query);
            $admin_details_row = mysqli_fetch_array($admin_details_run);
            $staff_name = $admin_details_row['admin_fname'] . ' ' . $admin_details_row['admin_lname'];
        }else{
            $staff_name = '';
        }
        $arr_inv_details = array("type"=>"bid","inv_no"=>"","bid_no"=>"$bid_wo_no","amount"=>"$bid_amount","client_pay"=>"","client_pay_date"=>"","vendor_pay"=>"","vendor_pay_date"=>"","date"=>"$date","client_pay_ref"=>"","staff"=>"$staff_name","inv_id"=>"","bid_id"=>"$bid_id","client_name" => "$client_name");
        array_push($arr_prop_order_list, $arr_inv_details);

    }
}

array_multisort(array_column($arr_prop_order_list, 'date'), SORT_DESC, $arr_prop_order_list);

foreach($arr_prop_order_list as $arr_prop_order_list_item){
    $bid_no_item = $arr_prop_order_list_item['bid_no'];
    $invoice_no_item = $arr_prop_order_list_item['inv_no'];
    $client_pay_date_item = $arr_prop_order_list_item['client_pay_date'];
    $vendor_pay_date_item = $arr_prop_order_list_item['vendor_pay_date'];  
    $crew_pay_item = $arr_prop_order_list_item['vendor_pay'];
    $client_pay_item = $arr_prop_order_list_item['client_pay'];
    $client_pay_ref_item = $arr_prop_order_list_item['client_pay_ref'];
    $item_amount = $arr_prop_order_list_item['amount'];
    $staff_name_item = $arr_prop_order_list_item['staff'];
    $bid_id_item = $arr_prop_order_list_item['bid_id'];
    $inv_id_item = $arr_prop_order_list_item['inv_id'];
    $cl_name = $arr_prop_order_list_item['client_name'];
        
    if($arr_prop_order_list_item['type'] == 'invoice'){
        $invoice_amount_item = $item_amount;
        $view_button = "<p><a href='invoice_finalize.php?in_no=$inv_id_item' id = ''>";
    }else{
        $invoice_amount_item = '';
    }
    if($arr_prop_order_list_item['type'] == 'bid'){
        $invoice_amount_item = $item_amount;
        $view_button = "<p><a href='estimate_finalize.php?wo_no=$bid_id_item' id = ''>";
    }
    $projected_profit = ''; 
    $actual_profit = '';
    $act_color = '';
    $pro_color = '';
    $date_item = $arr_prop_order_list_item['date'];
    $date_item = strtotime($date_item);
    $date_item= date('m-d-Y', $date_item);
   

    if(strlen($crew_pay_item) > 0 && strlen($invoice_amount_item) > 0){
            if($invoice_amount_item > 0 && $crew_pay_item > 0){
                $projected_profit = $invoice_amount_item - $crew_pay_item; 
                $projected_profit = number_format($projected_profit, 2, '.', '');

                if($projected_profit > 0){
                    $profit_per_cent = $projected_profit/$invoice_amount_item;
                    $profit_per_cent = $profit_per_cent * 100;

                    if($profit_per_cent > 30){
                        $pro_color = 'style = "background-color:#22803b"';
                    }else{
                        $pro_color = 'style = "background-color:#5de381"';/* light */
                    }                    
                    
                }else if($projected_profit == 0){
                    $pro_color = 'style = "background-color:yellow"';
                }else if ($projected_profit < 0){
                    $pro_color = 'style = "background-color:red"';
                }

            }

        }

        if(strlen($crew_pay_item) > 0 && strlen($client_pay_item) > 0 && strlen($invoice_amount_item) > 0){
            if($crew_pay_item > 0 && $client_pay_item > 0 && $invoice_amount_item > 0){
                $actual_profit = $client_pay_item - $crew_pay_item; 
                $actual_profit = number_format($actual_profit, 2, '.', '');

                if($actual_profit > 0){
                    $a_profit_per_cent = $actual_profit/$crew_pay_item;
                    $a_profit_per_cent = $a_profit_per_cent * 100;

                    if($a_profit_per_cent > 30){
                        $act_color = 'style = "background-color:#22803b"';
                    }else{
                        $act_color = 'style = "background-color:#5de381"';/* light */
                    }                    
                    
                }else if($actual_profit == 0){
                    $act_color = 'style = "background-color:yellow"';
                }else if ($actual_profit < 0){
                    $act_color = 'style = "background-color:red"';
                }

            }
        }
    
      echo $view_button; 
       if(strlen($invoice_no_item) > 0){
            echo 'Invoice ' .$invoice_no_item. '';
       }
       if(strlen($bid_no_item) > 0){
            echo 'Estimate ' .$bid_no_item. '';             
       }       
       $cl_name = strtoupper($cl_name);  
       echo ' | ' .$cl_name. '';
        echo ' | ' .$date_item. '';
        echo ' | $' .$item_amount. ''; 
        echo '</a></p><br><br>';    
      
}
?>

            </div> <!--  col lg 12-->
        </div> <!-- row -->

    <?php }   ?>
        </div>
    <!-- /#wrapper -->

    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')</script>

    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.3.min.js"></script>

    <!-- Metis Menu Plugin JavaScript -->
    <script src="js/metisMenu.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>

    <!-- Morris Charts JavaScript -->
  
 <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
 <script src="js/vendor/flot/excanvas.min.js"></script>
    <script src="js/vendor/flot/jquery.flot.js"></script>
    <script src="js/vendor/flot/jquery.flot.pie.js"></script>
    <script src="js/vendor/flot/jquery.flot.resize.js"></script>
    <script src="js/vendor/flot/jquery.flot.time.js"></script>
    <script src="js/vendor/flot-tooltip/jquery.flot.tooltip.min.js"></script>

    <script src="js/jquery.dataTables.min.js"></script>
    <script src="js/dataTables.bootstrap.min.js"></script>
    <script src="js/dataTables.responsive.js"></script>
 <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script> 
    <?php          if($user_type == 'admin'){     ?>
    <script>
   <?php          if($user_type == 'admin'){     ?>
        var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct","Nov","Dec"];

        new Morris.Area({
            element: 'morris-area-chart',
            data: [ 
<?php 
                    for($x = 11; $x >= 0; $x--){
                        echo "{";                       

                        $chart_month = strtotime("-$x month", time());
                        $chart_month_stamp = date("m", $chart_month);
                        $chart_year_stamp = date("Y", $chart_month);
                        $area_char_mnt = date("Y-m", $chart_month);                       
                        
                        $fetch_month_invoice_query = "SELECT * FROM invoice WHERE is_delete IS NULL AND  MONTH(create_time) = $chart_month_stamp AND YEAR(create_time) = $chart_year_stamp";

                        $fetch_month_invoice_run = mysqli_query($conn, $fetch_month_invoice_query);
                        $area_char_sales = 0;
                        $area_char_client = 0;

                        while($fetch_month_invoice_row = mysqli_fetch_array($fetch_month_invoice_run)){
                            $fetch_one_month_paid_invoice_amount = $fetch_month_invoice_row['invoice_amount'];
                           
                            $fetch_one_month_paid_cleint_amount = $fetch_month_invoice_row['client_pay'];
                            $area_char_sales = $area_char_sales + $fetch_one_month_paid_invoice_amount;

                            $area_char_client = $area_char_client + $fetch_one_month_paid_cleint_amount;
                        }
                        /*  */      
                        $fetch_month_invoice_query12 = "SELECT * FROM staff_pay WHERE pay_type = 'staff' AND is_delete IS NULL AND  MONTH(pay_date) = $chart_month_stamp AND YEAR(pay_date) = $chart_year_stamp";

                        $fetch_month_invoice_run12 = mysqli_query($conn, $fetch_month_invoice_query12);
                        $area_char_staff = 0;
                        
                        while($fetch_month_invoice_row12 = mysqli_fetch_array($fetch_month_invoice_run12)){
                            $fetch_one_month_paid_pay_amount = $fetch_month_invoice_row12['pay_amount'];
                            $area_char_staff = $area_char_staff + $fetch_one_month_paid_pay_amount;
                           
                           
                        }
                        $area_char_vendor = 0;

                        $fetch_month_invoice_query_vendor = "SELECT * FROM staff_pay WHERE pay_type = 'vendor' AND is_delete IS NULL AND  MONTH(pay_date) = $chart_month_stamp AND YEAR(pay_date) = $chart_year_stamp";

                        $fetch_month_invoice_run_vendor = mysqli_query($conn, $fetch_month_invoice_query_vendor);
                        $area_char_staff = 0;
                        
                        while($fetch_month_invoice_row_vendor = mysqli_fetch_array($fetch_month_invoice_run_vendor)){
                            $fetch_one_month_paid_pay_amount_vendor = $fetch_month_invoice_row_vendor['pay_amount'];
                            $area_char_vendor = $area_char_vendor + $fetch_one_month_paid_pay_amount_vendor;
                        }

                        /*  */
                        $area_char_client = (int)$area_char_client;
                        $area_char_sales = (int)$area_char_sales;
                        $area_char_vendor = (int)$area_char_vendor;
                        $area_char_staff = (int)$area_char_staff;


                        echo "month: '$area_char_mnt',";
                        echo "client: $area_char_client,"; 
                        echo "sales: $area_char_sales,"; 
                        echo "vendor: $area_char_vendor,";  
                        echo "staff: $area_char_staff"; 

                        echo "},";
                    }                    
                    ?>            
             ], 
            xkey: 'month',            
            ykeys: ['client','sales','vendor','staff'],
            labels: ['Client Pay','Sales','Vendor Pay','Staff Pay'],            
            pointSize: 2,
            hideHover: 'auto',
            resize: true,
            behaveLikeLine	:true,
            xLabelFormat: function(x) { // <--- x.getMonth() returns valid index
                var month = months[x.getMonth()];
                return month;
            },
            dateFormat: function(x) {
                var month = months[new Date(x).getMonth()];
                return month;
            },
        });

        new Morris.Bar({
        element: 'morris-bar-chart',
        data: [
          <?php 
          $year2 = date("Y");
          $year1_month = strtotime("-1 year", time());
          $year1 = date("Y", $year1_month);
          $year1_stamp = date("Y-m-d h:i:s", $year1_month);                       
          $year1_stamp_date = date("Y-m-d", $year1_month);                       

          $fetch_month_invoice_queryqw =  "SELECT * FROM invoice WHERE is_delete IS NULL AND create_time >= '$year1_stamp'";
          $fetch_month_invoice_runqw = mysqli_query($conn, $fetch_month_invoice_queryqw);
          $annual_client = 0;
          $annual_sales = 0;          
          while($fetch_month_invoice_rowqw =mysqli_fetch_array($fetch_month_invoice_runqw)){
            $invoice_amount123 = $fetch_month_invoice_rowqw['invoice_amount']; 
            $client_pay123 = $fetch_month_invoice_rowqw['client_pay'];  
            $annual_client = $annual_client + $client_pay123;
            $annual_sales = $annual_sales + $invoice_amount123;

          }

          $annual_pay = 0.00;

          $fetch_staff_pay_year_query = "SELECT * FROM staff_pay WHERE pay_type = 'staff' AND is_delete IS NULL AND pay_date >= '$year1_stamp_date'";
          $fetch_staff_pay_year_run = mysqli_query($conn, $fetch_staff_pay_year_query);

          while($fetch_staff_pay_year_row = mysqli_fetch_array($fetch_staff_pay_year_run)){
                $pay_amount = $fetch_staff_pay_year_row['pay_amount'];
                $annual_pay = $annual_pay + $pay_amount;
          }

          $annual_vendor = 0;
          $fetch_vendor_pay_year_query = "SELECT * FROM staff_pay WHERE pay_type = 'vendor' AND is_delete IS NULL AND pay_date >= '$year1_stamp_date'";
          $fetch_vendor_pay_year_run = mysqli_query($conn, $fetch_vendor_pay_year_query);

          while($fetch_vendor_pay_year_row = mysqli_fetch_array($fetch_vendor_pay_year_run)){
                $vendor_pay123 = $fetch_vendor_pay_year_row['pay_amount'];
                $annual_vendor = $annual_vendor + $vendor_pay123;
            }
          
          ?>
          { y: '<?php echo $year1."-".$year2;?>', a: <?php echo $annual_client;?>, b: <?php echo $annual_sales;?>, c:<?php echo $annual_vendor;?>, d:<?php echo $annual_pay;?> },
         
        ],
        xkey: 'y',
        ykeys: ['a', 'b','c','d'],
        labels: ['Client Pay', 'Sales', 'Vendor Pay', 'Staff Pay'],
        horizontal: true,
        stacked: false,
      });

    <?php         }    ?>
    //Flot Line Chart
    <?php 
            $year_line = date("Y");
            $year1_line_prev = strtotime("-1 month", time());
            $year_line_prev = date("Y", $year1_line_prev);

            $month_line = date("m");
            $month1_line_prev = strtotime("-1 month", time());
            $month_line_prev = date("m", $month1_line_prev);
            $arr_vendor_line = array();
            $arr_client_line = array();
            $arr_staff_line= array();
            
            for($i=1;$i<32;$i++){
                $fetch_month_invoice_queryqw1 =  "SELECT * FROM invoice WHERE is_delete IS NULL AND is_settle = 1 AND client_pay_date BETWEEN '$year_line-$month_line-$i 00:00:00' AND '$year_line-$month_line-$i 23:59:59'";
                $fetch_month_invoice_runqw1 = mysqli_query($conn, $fetch_month_invoice_queryqw1);
                $annual_client = 0;
                
                while($fetch_month_invoice_rowqw1 =mysqli_fetch_array($fetch_month_invoice_runqw1)){                  
                    $client_pay123 = $fetch_month_invoice_rowqw1['client_pay'];  
                    $annual_client = $annual_client + $client_pay123;
                   
                }

                $fetch_month_invoice_queryqw_prev =  "SELECT * FROM invoice WHERE is_delete IS NULL AND is_settle = 1 AND client_pay_date BETWEEN '$year_line_prev-$month_line_prev-$i 00:00:00' AND '$year_line_prev-$month_line_prev-$i 23:59:59'";
                $fetch_month_invoice_runqw_prev = mysqli_query($conn, $fetch_month_invoice_queryqw_prev);
                $annual_client_prev = 0;
                while($fetch_month_invoice_rowqw_prev =mysqli_fetch_array($fetch_month_invoice_runqw_prev)){
                    $client_pay123_prev = $fetch_month_invoice_rowqw_prev['client_pay'];  
                    $annual_client_prev = $annual_client_prev + $client_pay123_prev;
                }    
                

                /*  */
                $fetch_month_invoice_queryqwv =  "SELECT * FROM staff_pay WHERE pay_type = 'staff' AND is_delete IS NULL AND pay_date = '$year_line-$month_line-$i'";
                $fetch_month_invoice_runqwv = mysqli_query($conn, $fetch_month_invoice_queryqwv);
                
                $pay_amountv = 0;
                while($fetch_month_invoice_rowqwv =mysqli_fetch_array($fetch_month_invoice_runqwv)){
                    $pay_amount123 = $fetch_month_invoice_rowqwv['pay_amount']; 
                   
                    $pay_amountv = $pay_amountv + $pay_amount123;    
                }

                $fetch_month_invoice_queryqwv2 =  "SELECT * FROM staff_pay WHERE pay_type = 'staff' AND is_delete IS NULL AND pay_date = '$year_line_prev-$month_line_prev-$i'";
                $fetch_month_invoice_runqwv2 = mysqli_query($conn, $fetch_month_invoice_queryqwv2);
                
                $pay_amountv_prev = 0;
                while($fetch_month_invoice_rowqwv2 =mysqli_fetch_array($fetch_month_invoice_runqwv2)){
                    $pay_amount123_prev = $fetch_month_invoice_rowqwv2['pay_amount']; 
                   
                    $pay_amountv_prev = $pay_amountv_prev + $pay_amount123_prev;    
                }


                /*  */
                /*  */
                $fetch_month_invoice_queryqwvzx =  "SELECT * FROM staff_pay WHERE pay_type = 'vendor' AND is_delete IS NULL AND pay_date = '$year_line-$month_line-$i'";
                $fetch_month_invoice_runqwvzx = mysqli_query($conn, $fetch_month_invoice_queryqwvzx);
                
                $pay_amount_vend = 0;
                while($fetch_month_invoice_rowqwvzx =mysqli_fetch_array($fetch_month_invoice_runqwvzx)){
                    $pay_amount123zx = $fetch_month_invoice_rowqwvzx['pay_amount']; 
                   
                    $pay_amount_vend = $pay_amount_vend + $pay_amount123zx;    
                }

                $fetch_month_invoice_queryqwv2zx =  "SELECT * FROM staff_pay WHERE pay_type = 'vendor' AND is_delete IS NULL AND pay_date = '$year_line_prev-$month_line_prev-$i'";
                $fetch_month_invoice_runqwv2zx = mysqli_query($conn, $fetch_month_invoice_queryqwv2zx);
                
                $pay_amount_vend_prev = 0;
                while($fetch_month_invoice_rowqwv2zx =mysqli_fetch_array($fetch_month_invoice_runqwv2zx)){
                    $pay_amount123_prevzx = $fetch_month_invoice_rowqwv2zx['pay_amount']; 
                   
                    $pay_amount_vend_prev = $pay_amount_vend_prev + $pay_amount123_prevzx;    
                }

                /*  */
                /*  */
                
                $time_now = time();

                $time_now1 = strtotime("$year_line-$month_line-$i 00:00:00");
                $key1_line = 'y';
                $key2_line = 'a';
                $key3_line = 'b';
                $y_line= "$year_line_prev-$month_line_prev-$i";
                if($time_now > $time_now1){
                    $array1_vendor_vend = array( $key1_line=> $y_line, $key2_line=> $pay_amount_vend_prev, $key3_line =>  $pay_amount_vend);

                    $array1_client= array( $key1_line=> $y_line, $key2_line=> $annual_client_prev, $key3_line =>  $annual_client);

                    $array1_staff= array( $key1_line=> $y_line, $key2_line=> $pay_amountv_prev, $key3_line =>  $pay_amountv);
                }else{
                    $array1_vendor_vend = array( $key1_line=> $y_line, $key2_line=> $pay_amount_vend_prev);

                    $array1_client= array( $key1_line=> $y_line, $key2_line=> $annual_client_prev);

                    $array1_staff= array( $key1_line=> $y_line, $key2_line=> $pay_amountv_prev);

                }
                array_push($arr_vendor_line,$array1_vendor_vend);
                array_push($arr_client_line,$array1_client);
                array_push($arr_staff_line,$array1_staff);


            }          
        ?>

$(document).ready(function() {    

    var data = <?php 
        $json_vendor_line = json_encode($arr_vendor_line);
        echo trim($json_vendor_line, '"'); ?>,
    config = {
      data: data,
      xkey: 'y',
      ykeys: ['a','b'],
      xLabelFormat: function(y) {
        return y.getDate(); 
  },
    xLabels:'day',

      labels: ['Last Month', 'This Month'],
      fillOpacity: 0.6,
      
      behaveLikeLine: true,
      resize: true,
      pointFillColors:['#4da74d','red'],
      pointStrokeColors: ['#4da74d','red'],
      lineColors:['#4da74d','red'],
     
      dateFormat: function (y) {
    var d = new Date(y);
    return d.getDate(); 
  }

  };

config.element = 'line-chart';
Morris.Line(config);

var data1 = <?php echo json_encode($arr_client_line); ?>,
config = {
      data: data1,
      xkey: 'y',
      ykeys: ['a','b'],
      xLabelFormat: function(y) {
        return y.getDate(); 
  },
    xLabels:'day',

      labels: ['Last Month', 'This Month'],
      fillOpacity: 0.6,
      
      behaveLikeLine: true,
      resize: true,
      pointFillColors:['#4da74d','red'],
      pointStrokeColors: ['#4da74d','red'],
      lineColors:['#4da74d','red'],
     
      dateFormat: function (y) {
    var d = new Date(y);
    return d.getDate(); 
  }

  };

config.element = 'line-chart_client';
Morris.Line(config);


<?php          if($user_type == 'admin'){     ?>
var data2 = <?php echo json_encode($arr_staff_line); ?>,
config = {
      data: data2,
      xkey: 'y',
      ykeys: ['a','b'],
      xLabelFormat: function(y) {
        return y.getDate(); 
  },
    xLabels:'day',

      labels: ['Last Month', 'This Month'],
      fillOpacity: 0.6,
      
      behaveLikeLine: true,
      resize: true,
      pointFillColors:['#4da74d','red'],
      pointStrokeColors: ['#4da74d','red'],
      lineColors:['#4da74d','red'],
     
      dateFormat: function (y) {
    var d = new Date(y);
    return d.getDate(); 
  }

  };

config.element = 'line-chart_staff';
Morris.Line(config);
<?php } ?>
$('#dataTables-bidwiz2').DataTable({
            responsive: true,
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],  
        
        });


});



    </script>
<script>

function set_new_values(){
    var fetch_year = document.getElementById("year-selected").value;
    var fetch_option = document.getElementById("filter-selected").value; 
    if(fetch_option == 'm' || fetch_option == 'q'){
        var fetch_value = document.getElementById("value-selected").value;
    }else{
        var fetch_value = 'none';
    }
    $.ajax({
        url: "dashboard-stats-adata.php?year=" + fetch_year + "&option=" + fetch_option + "&value=" + fetch_value,
        type: "POST",
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
            var data = data.trim();
            var data_response = JSON.parse(data);
            $("#estimate_generated").html(data_response.estimate_generated); 
            $("#estimate_overdue").html(data_response.estimate_overdue);              
            document.getElementById("estimate_progress").style.width = data_response.estimate_progress+ '%';
            $("#estimate_paid").html(data_response.estimate_paid);
            $("#invoice_unpaid").html(data_response.invoice_unpaid); 
            $("#invoice_overdue").html(data_response.invoice_overdue);              
            $("#invoice_not_due").html(data_response.invoice_not_due);
            document.getElementById("invoice_progress").style.width = data_response.invoice_progress+ '%';
            $("#invoice_paid").html(data_response.invoice_paid);
            $("#period_staff_pay").html('$' + data_response.period_staff_pay);
            $("#period_vendor_pay").html('$' + data_response.period_vendor_pay);
            $("#period_profit").html('$' + data_response.period_profit);
            $("#selected_period").html(data_response.select_string);
            $("#invoice_generated").html(data_response.invoice_generated);           
        }          
    });
}
set_new_values();
function select_filter(){
  var opt_filter = document.getElementById("filter-selected").value;
  if(opt_filter == 'm' || opt_filter == 'q'){
    document.getElementById("value-selected").style.display = 'block';
    if(opt_filter == 'm'){
        let dropdown = $('#value-selected');

        dropdown.empty();
        var fetch_year = document.getElementById("year-selected").value;
        var current_year = new Date().getFullYear();

        if(fetch_year == current_year){
            var m_names = ['January', 'February', 'March', 
               'April', 'May', 'June', 'July', 
               'August', 'September', 'October', 'November', 'December'];
            d = new Date();
            var month_digit = d.getMonth();           
            for(var k = 0; k <= 11; k++){
                var n = m_names[k];
                dropdown.append('<option value="' + k + '">'+ n +'</option>');
                if(k == month_digit){
                    break;
                }
            }
           
            document.getElementById("value-selected").selectedIndex = month_digit; 
        }else{
            var m_names = ['January', 'February', 'March', 
               'April', 'May', 'June', 'July', 
               'August', 'September', 'October', 'November', 'December'];
            for(var k = 0; k < 12; k++){
                var n = m_names[k];
                dropdown.append('<option value="' + k + '">'+ n +'</option>');
            }
            document.getElementById("value-selected").selectedIndex = 0;
        }        
    }
    
     if(opt_filter == 'q'){
        let dropdown = $('#value-selected');

        dropdown.empty();
        var fetch_year = document.getElementById("year-selected").value;
        var current_time = new Date();
        current_year =   current_time.getFullYear();
       
        if(fetch_year == current_year){
            var q_names = ['Quarter 1', 'Quarter 2', 'Quarter 3','Quarter 4'];
            var month_digit = current_time.getMonth();
            month_digit = month_digit +1;
            if(month_digit == 1 || month_digit == 2 || month_digit == 3){
                var current_qtr = 0;
            }else if(month_digit == 4 || month_digit == 5 || month_digit == 6){
                var current_qtr = 1;
            }else if(month_digit == 7 || month_digit == 8 || month_digit == 9){
                var current_qtr = 2;
            }else if(month_digit == 10 || month_digit == 11 || month_digit == 12){
                var current_qtr = 3;
            }
            for(var k = 0; k < 4; k++){
                kk = k + 1;
                var n = q_names[k];
                dropdown.append('<option value="' + kk + '">'+ n +'</option>');
                if(k == current_qtr){
                    break;
                }
            }            
            document.getElementById("value-selected").selectedIndex = current_qtr;
        }else{
            var q_names = ['Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4'];
            for(var k = 0; k < 4; k++){
                kk = k + 1;
                var n = q_names[k];
                dropdown.append('<option value="' + kk + '">'+ n +'</option>');
            }
            document.getElementById("value-selected").selectedIndex = 0;
        }
    }
  }
if(opt_filter == 'y'){
        document.getElementById("value-selected").style.display = 'none';
    }
    set_new_values();
}

function year_change(){
    var fetch_year = document.getElementById("year-selected").value;
    var current_year = new Date().getFullYear();
    $('#filter-selected').val('y');

    document.getElementById("value-selected").style.display = 'none';
   
    set_new_values();
}
</script>
    <!-- Custom Theme JavaScript -->
<?php          }   ?>
 
    <?php include_once "search_footer.php" ?>
    
   
</body>

</html>