<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);


include_once 'config.php';



/*include_once "../ichat/admin/route.php";
if ($session->is_logged_in() != true ) {
        redirect_to(WEB_LINK.'/login');
} else {
    $current_user = User::get_specific_id($session->admin_id);
    $current_user->set_online();
    $group = $current_user->prvlg_group;
}*/



  

//require_once("../ichat/admin/assets/includes/Library/SessManager.php");
//require_once("../ichat/admin/assets/includes/Library/User.php");


//$session = new  SessManager();



require_once 'database1.php';

require_once "check_admin.php";

class Dashboard extends database
{
   public function getAllCustomerCount()
   {
        $sql = ' SELECT COUNT(*) AS total_user FROM user WHERE cl_deleted_at IS NULL AND user_type="customer" ';
        return $this->callQuery($sql);
   }

   public function getAllOrderCount()
   {
        $sql = ' SELECT COUNT(*) AS total_order FROM tb_checkout WHERE cl_deleted_at IS NULL  ';
        return $this->callQuery($sql);
   }

   public function getAllSalesToday()
   {
    $sql = ' SELECT SUM(cl_total) AS final_total, COUNT(*) AS total_orders FROM tb_checkout WHERE cl_deleted_at IS NULL AND DATE(cl_created_at)=CURDATE() AND cl_status!="Cancelled" AND cl_status!="Payment Cancelled"  AND cl_status!="Money Refunded" AND cl_status!="Session Expired" ';
    return $this->callQuery($sql);
   }

   public function getAllSalesMonth()
   {
    $sql = ' SELECT SUM(cl_total) AS final_total, COUNT(*) AS total_orders FROM tb_checkout WHERE cl_deleted_at IS NULL AND MONTH(cl_created_at)=' . date('m') . ' AND YEAR(cl_created_at)=' . date('Y') . ' AND cl_status!="Cancelled" AND cl_status!="Payment Cancelled"  AND cl_status!="Money Refunded" AND cl_status!="Session Expired" ';
    return $this->callQuery($sql);
   }

   public function getAllReceivedToday()
   {
    $sql = ' SELECT SUM(cl_total) AS final_total, COUNT(*) AS total_orders FROM tb_checkout WHERE cl_deleted_at IS NULL AND DATE(cl_created_at)=CURDATE() AND cl_status!="Cancelled" AND cl_status!="Payment Cancelled"  AND cl_status!="Money Refunded" AND cl_status!="Session Expired" AND cl_status!="Waiting on Payment" ';
    return $this->callQuery($sql);
   }

   public function getAllReceivedMonth()
   {
    $sql = ' SELECT SUM(cl_total) AS final_total, COUNT(*) AS total_orders FROM tb_checkout WHERE cl_deleted_at IS NULL AND MONTH(cl_created_at)=' . date('m') . ' AND YEAR(cl_created_at)=' . date('Y') . ' AND cl_status!="Cancelled" AND cl_status!="Payment Cancelled"  AND cl_status!="Money Refunded" AND cl_status!="Session Expired" AND cl_status!="Waiting on Payment" ';
    return $this->callQuery($sql);
   }

   public function getAllOrders($limit)
   {
        return $this->fetchAll('tb_checkout', $where, 'cl_created_at', 'DESC', 0, $limit);
   }
	 public function getAllTickets($limit)
   {
        return $this->fetchAll('tb_ticket', $where, 'cl_created_at', 'DESC', 0, $limit);
   }
   	 public function getAllWarranty()
   {
         $sql = 'SELECT w.*, p.cl_name AS product, u.cl_name AS user FROM tb_warranty w INNER JOIN tb_checkout_item ci ON w.cl_checkout_item_id = ci.cl_id INNER JOIN tb_product p ON p.cl_id = ci.cl_product_id INNER JOIN user u ON u.id = ci.cl_user_id  WHERE w.cl_deleted_at IS NULL ORDER BY w.cl_created_at DESC LIMIT 0,50';
        return $this->callQuery($sql);
   }
   public function getTotalInactiveStockProducts()
   {
        $sql = ' SELECT COUNT(*) AS total_products FROM tb_product WHERE cl_deleted_at IS NULL AND cl_active=0 AND cl_stock=0 ';
        return $this->callQuery($sql);
   }

   public function getTotalActiveStockProducts()
   {
        $sql = ' SELECT COUNT(*) AS total_products FROM tb_product WHERE cl_deleted_at IS NULL AND cl_active=1 AND cl_stock=1 ';
        return $this->callQuery($sql);
   }

   public function getwaitingForPaymentOrdersWeek()
   {
    $date = date('Y-m-d', strtotime('-7 days'));
     $sql = ' SELECT COUNT(*) AS order_total FROM tb_checkout WHERE cl_deleted_at IS NULL AND DATE(cl_created_at)<=DATE("' . $date . '") AND cl_status="Waiting on Payment" ';
   
    return $this->callQuery($sql);
   }

   public function getwithoutImageProductCount()
   {
        $sql = ' SELECT COUNT(*) AS product_count FROM tb_product WHERE cl_deleted_at IS NULL AND cl_stock=1 AND cl_active=1 AND (cl_image IS NULL OR cl_image="") ';
        return $this->callQuery($sql);
   }


   public function getOrdersPerDay()
   {
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total, DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 15 DAY AND CURDATE() GROUP BY DATE(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }

   public function getCancelledOrdersPerDay()
   {
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total, DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND (cl_status="Cancelled" OR cl_status="Payment Cancelled" OR cl_status="Session Expired") AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 15 DAY AND CURDATE() GROUP BY DATE(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }

   public function getRefundedOrdersPerDay()
   {
       
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total,  DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND (cl_status="Money Refunded") AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 15 DAY AND CURDATE() GROUP BY DATE(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }

   public function getPaidOrdersPerDay()
   {
       
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total, DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND (cl_status!="Cancelled" AND cl_status!="Payment Cancelled"  AND cl_status!="Money Refunded" AND cl_status!="Session Expired" AND cl_status != "Waiting on payment") AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 15 DAY AND CURDATE() GROUP BY DATE(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }
   
   
   
   
   
   /* month */
   public function getOrdersPerMonth()
   {
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total, DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE() GROUP BY MONTH(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }

   public function getCancelledOrdersPerMonth()
   {
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total, DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND (cl_status="Cancelled" OR cl_status="Payment Cancelled" OR cl_status="Session Expired") AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE() GROUP BY MONTH(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }

   public function getRefundedOrdersPerMonth()
   {
       
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total,  DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND (cl_status="Money Refunded") AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE() GROUP BY MONTH(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }

   public function getPaidOrdersPerMonth()
   {
       
        $sql = 'SELECT COUNT(*) AS total_count, SUM(cl_total) AS final_total, DATE(cl_created_at) AS check_date FROM tb_checkout WHERE cl_deleted_at IS NULL AND (cl_status!="Cancelled" AND cl_status!="Payment Cancelled"  AND cl_status!="Money Refunded" AND cl_status!="Session Expired" AND cl_status != "Waiting on payment") AND DATE(cl_created_at) BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE() GROUP BY MONTH(cl_created_at) ORDER BY cl_created_at DESC';
        return $this->callQuery($sql);
   }
}

$obj = new Dashboard();
$totalCustomers = $obj->getAllCustomerCount();
$totalOrders = $obj->getAllOrderCount();
$totalSalesToday = $obj->getAllSalesToday();
$totalSalesMonth = $obj->getAllSalesMonth();

$totalSalesTodayWithoutWaitingForPayment = $obj->getAllReceivedToday();
$totalSalesMonthWithoutWaitingForPayment = $obj->getAllReceivedMonth();

$totalInctiveStockProducts = $obj->getTotalInactiveStockProducts();
$totalActiveStockProducts = $obj->getTotalActiveStockProducts();

$waitingForPaymentOrdersWeek = $obj->getwaitingForPaymentOrdersWeek();
$waitingofPaymentCount = 0;
if(isset($waitingForPaymentOrdersWeek[0]))
{
    $waitingofPaymentCount = $waitingForPaymentOrdersWeek[0]['order_total'];
}

$withoutImageProductCountArray = $obj->getwithoutImageProductCount();


$userOrders = $obj->getAllOrders(500);

$ticket = $obj ->getAllTickets(50);
$warranty= $obj ->getAllWarranty();


$allOrders = $obj->getOrdersPerDay();
$cancelledOrders = $obj->getCancelledOrdersPerDay();
$refundedOrders = $obj->getRefundedOrdersPerDay();
$paidOrders = $obj->getPaidOrdersPerDay();



$jsonAllOrders = [];
$jsonCancelledOrders = [];
$jsonRefundedOrders = [];
$jsonPaidOrders = [];

$jsonAllOrdersSum = [];
$jsonCancelledOrdersSum = [];
$jsonRefundedOrdersSum = [];
$jsonPaidOrdersSum = [];

$checkingDate = date("Y-m-d");
$checkingDate = strtotime($checkingDate);

if(!empty($allOrders))
{
    foreach($allOrders AS $each)
    {
       // $checkingDate = strtotime($checkingDate);
        $your_date = strtotime($each['check_date']);
        $datediff = $checkingDate - $your_date;

        
         $numberDays = round($datediff / (60 * 60 * 24));
        if($numberDays != 0)
        {
            for($i = 0; $i <= $numberDays; $i++)
            {
                if($i != $numberDays)
                {
                    $jsonAllOrders[] = 0;
                    $jsonAllOrdersSum[] = 0;
                }
                else
                {
                    $jsonAllOrders[] = (int) $each['total_count'];
                    $jsonAllOrdersSum[] = (float) $each['final_total'];
                }

                $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
                $checkingDate = strtotime($checkingDate);
            }
        }
        else
        {
            $jsonAllOrders[] = (int) $each['total_count'];
            $jsonAllOrdersSum[] = (float) $each['final_total'];
           
            $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
            $checkingDate = strtotime($checkingDate);
        }
    }
}



$checkingDate = date("Y-m-d");
$checkingDate = strtotime($checkingDate);

if(!empty($cancelledOrders))
foreach($cancelledOrders AS $each)
{
   // $checkingDate = strtotime($checkingDate);
    $your_date = strtotime($each['check_date']);
    $datediff = $checkingDate - $your_date;

    
     $numberDays = round($datediff / (60 * 60 * 24));
    if($numberDays != 0)
    {
        for($i = 0; $i <= $numberDays; $i++)
        {
            if($i != $numberDays)
            {
                $jsonCancelledOrders[] = 0;
                $jsonCancelledOrdersSum[] = 0;
            }
            else
            {
                $jsonCancelledOrders[] = (int) $each['total_count'];
                $jsonCancelledOrdersSum[] = (float) $each['final_total'];
            }

            $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
            $checkingDate = strtotime($checkingDate);
        }
    }
    else
    {
        $jsonCancelledOrders[] = (int) $each['total_count'];
        $jsonCancelledOrdersSum[] = (float) $each['final_total'];
       
        $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
        $checkingDate = strtotime($checkingDate);
    }
}



$checkingDate = date("Y-m-d");
$checkingDate = strtotime($checkingDate);

if(!empty($refundedOrders))
foreach($refundedOrders AS $each)
{
   // $checkingDate = strtotime($checkingDate);
    $your_date = strtotime($each['check_date']);
    $datediff = $checkingDate - $your_date;

    
     $numberDays = round($datediff / (60 * 60 * 24));
    if($numberDays != 0)
    {
        for($i = 0; $i <= $numberDays; $i++)
        {
            if($i != $numberDays)
            {
                $jsonRefundedOrders[] = 0;
                $jsonRefundedOrdersSum[] = 0;
            }
            else
            {
                $jsonRefundedOrders[] = (int) $each['total_count'];
                $jsonRefundedOrdersSum[] = (float) $each['final_total'];
            }

            $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
            $checkingDate = strtotime($checkingDate);
        }
    }
    else
    {
        $jsonRefundedOrders[] = (int) $each['total_count'];
        $jsonRefundedOrdersSum[] = (float) $each['final_total'];
       
        $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
        $checkingDate = strtotime($checkingDate);
    }
}



$checkingDate = date("Y-m-d");
$checkingDate = strtotime($checkingDate);

if(!empty($paidOrders))
foreach($paidOrders AS $each)
{
   // $checkingDate = strtotime($checkingDate);
    $your_date = strtotime($each['check_date']);
    $datediff = $checkingDate - $your_date;

    
     $numberDays = round($datediff / (60 * 60 * 24));
    if($numberDays != 0)
    {
        for($i = 0; $i <= $numberDays; $i++)
        {
            if($i != $numberDays)
            {
                $jsonPaidOrders[] = 0;
                $jsonPaidOrdersSum[] = 0;
            }
            else
            {
                $jsonPaidOrders[] = (int) $each['total_count'];
                $jsonPaidOrdersSum[] = (float) $each['final_total'];
            }

            $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
            $checkingDate = strtotime($checkingDate);
        }
    }
    else
    {
        $jsonPaidOrders[] = (int) $each['total_count'];
        $jsonPaidOrdersSum[] = (float) $each['final_total'];
       
        $checkingDate = date('Y-m-d', strtotime('-1 day', $checkingDate));
        $checkingDate = strtotime($checkingDate);
    }
}





/* monthly chart*/
$allOrdersMonth = $obj->getOrdersPerMonth();
$cancelledOrdersMonth = $obj->getCancelledOrdersPerMonth();
$paidOrdersMonth = $obj->getPaidOrdersPerMonth();



$jsonAllOrdersMonth = [];
$jsonCancelledOrdersMonth = [];
$jsonRefundedOrdersMonth = [];
$jsonPaidOrdersMonth = [];

$jsonAllOrdersSumMonth = [];
$jsonCancelledOrdersSumMonth = [];
$jsonRefundedOrdersSumMonth = [];
$jsonPaidOrdersSumMonth = [];


$monthArray = [];



if(!empty($allOrdersMonth))
{
    foreach($allOrdersMonth AS $each)
    {
        $jsonAllOrdersMonth[] = (int) $each['total_count'];
        $jsonAllOrdersSumMonth[] = (float) $each['final_total'];
       $monthArray[] = date("M Y", strtotime($each['check_date']));
    }
}

if(!empty($cancelledOrdersMonth))
{
    foreach($cancelledOrdersMonth AS $key => $each)
    {
        if(isset($monthArray[$key]))
        {
            $jsonCancelledOrdersMonth[] = (int) $each['total_count'];
            $jsonCancelledOrdersSumMonth[] = (float) $each['final_total'];
        }
        else
        {
            $jsonCancelledOrdersMonth[] = 0;
            $jsonCancelledOrdersSumMonth[] = 0;
        }
       
    }
}




if(!empty($paidOrdersMonth))
{
    foreach($paidOrdersMonth AS $each)
    {
        if(isset($monthArray[$key]))
        {
            $jsonPaidOrdersMonth[] = (int) $each['total_count'];
            $jsonPaidOrdersSumMonth[] = (float) $each['final_total'];
        }
        else
        {
            $jsonPaidOrdersMonth[] = 0;
            $jsonPaidOrdersSumMonth[] = 0;
        }
       
    }
}



include 'header.php';

?>

<script src = "https://code.highcharts.com/highcharts.js"></script> 
  <script src = "https://code.highcharts.com/highcharts-3d.js"></script>
					 
            <!-- MAIN CONTENT-->
            <div class="main-content">
                <div class="section__content section__content--p30">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="overview-wrap">
                                    <h2 class="title-1 col-xs-12 col-sm-6">Dashboard</h2>
                                    <div class="col-xs-12 col-sm-6" style="text-align: right">
                                        <small class="title-1"><?php echo date('d M Y H:i:s') ?></small>
                                    </div>
                                    
                                </div>
								
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-12 col-sm-6 no-padding" style="text-align: right">
                                <small class="">Total Sales excludes the following status - Cancelled, Money Refunded, Payment Cancelled, Session Expired</small>
                            </div>
                        </div>
                      
							<div class="row">
                                <div class="card col-xs-12 col-sm-12">
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-xs-12 col-sm-6 col-md-3 ">
                                                <a href="/customers" class="alert alert-success col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Customers
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        <?php echo $totalCustomers[0]['total_user'] ?>
                                                    </div>
                                                </a>
                                            </div>
                                            <div class="col-xs-12 col-sm-6 col-md-3">
                                                <a href="/user-orders/list" class="alert alert-primary col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Number of Orders
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        <?php echo $totalOrders[0]['total_order'] ?>
                                                    </div>
                                                </a>
                                            </div>
                                            <div class="col-xs-12 col-sm-6 col-md-3">
                                                <a href="#" class="alert alert-info col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Sales (Today)
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        <?php 
                                                        if(isset($totalSalesToday[0]['final_total']))
                                                        {
                                                            echo '€ ' . $totalSalesToday[0]['final_total'] . ' (' . $totalSalesToday[0]['total_orders'] . ')';
                                                            }
                                                            else{
                                                                echo '€ 0.00';
                                                            } ?>
                                                    </div>
                                                </a>
                                            </div>
                                            <div class="col-xs-12 col-sm-6 col-md-3">
                                                <a href="#" class="alert alert-danger col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Sales (This Month)
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        € <?php 
                                                        if(isset($totalSalesMonth[0]['final_total']))
                                                        {
                                                            echo $totalSalesMonth[0]['final_total'] . ' (' . $totalSalesMonth[0]['total_orders'] . ')';
                                                        }
                                                        else
                                                        {
                                                            echo '0.00';
                                                        }
                                                        ?>
                                                    </div>
                                                </a>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-xs-12 col-sm-6 col-md-3 ">
                                                <a href="#" class="alert alert-success col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Amount Received Today
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        <?php 
                                                        if(isset($totalSalesTodayWithoutWaitingForPayment[0]['final_total']))
                                                        {
                                                            echo '€ ' . $totalSalesTodayWithoutWaitingForPayment[0]['final_total'] . ' (' . $totalSalesTodayWithoutWaitingForPayment[0]['total_orders'] . ')';
                                                            }
                                                            else{
                                                                echo '€ 0.00';
                                                            } ?>
                                                    </div>
                                                </a>
                                            </div>
                                            <div class="col-xs-12 col-sm-6 col-md-3">
                                                <a href="#" class="alert alert-primary col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Amount Received This Month
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        <?php 
                                                        if(isset($totalSalesMonthWithoutWaitingForPayment[0]['final_total']))
                                                        {
                                                            echo '€ ' . $totalSalesMonthWithoutWaitingForPayment[0]['final_total'] . ' (' . $totalSalesMonthWithoutWaitingForPayment[0]['total_orders'] . ')';
                                                            }
                                                            else{
                                                                echo '€ 0.00';
                                                            } ?>
                                                    </div>
                                                </a>
                                            </div>

                                            <div class="col-xs-12 col-sm-6 col-md-3">
                                                <a href="#" class="alert alert-info col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Inactive Products With Stock
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        <?php 
                                                        if(isset($totalInctiveStockProducts[0]['total_products']))
                                                        {
                                                            echo $totalInctiveStockProducts[0]['total_products'];
                                                            }
                                                            else{
                                                                echo '0';
                                                            } ?>
                                                    </div>
                                                </a>
                                            </div>
                                            <div class="col-xs-12 col-sm-6 col-md-3">
                                                <a href="#" class="alert alert-danger col-xs-12 col-sm-12">
                                                    <b>
                                                        Total Active Products With Stock
                                                    </b>
                                                    <div class="colsm-12 col-xs-12">
                                                        <?php 
                                                        if(isset($totalActiveStockProducts[0]['total_products']))
                                                        {
                                                            echo $totalActiveStockProducts[0]['total_products'];
                                                        }
                                                        else
                                                        {
                                                            echo '0';
                                                        }
                                                        ?>
                                                    </div>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">

                                <ul class="nav nav-tabs graph_tab">
                                  <li class="nav-item">
                                    <a class="nav-link active" href="#" id="no_of_orders_li">No. of Orders (By Day)</a>
                                  </li>
                                  <li class="nav-item">
                                    <a class="nav-link" href="#" id="revenue_li">Total Revenue (By Day)</a>
                                  </li>
                                  <li class="nav-item">
                                    <a class="nav-link active" href="#" id="no_of_orders_month_li">No. of Orders (By Month)</a>
                                  </li>
                                  <li class="nav-item">
                                    <a class="nav-link" href="#" id="revenue_month_li">Total Revenue (By Month)</a>
                                  </li>
                                  
                                </ul>
                                
                                
                                <div class="col-12">
                                    <div class="row">
                                        <div class="card col-lg-12">
                                            <div class=" col-12 graph_container" id="graph_number">
                                                 <div id="order_graph_container" style = "width: 100%; height: 400px; margin: 0 auto">

                                                 </div>
                                            </div>

                                            <div class="card col-xs-12 col-12 graph_container" id="graph_cost" style="display:none">
                                                 <div id="order_revenue_graph_container" style = "width: 100%; height: 400px; margin: 0 auto">

                                                 </div>
                                            </div>
                                            
                                            <div class=" col-12 graph_container" id="graph_month_number" style="display:none">
                                                 <div id="order_graph_month_container" style = "width: 100%; height: 400px; margin: 0 auto">

                                                 </div>
                                            </div>

                                            <div class="card col-xs-12 col-12 graph_container" id="graph_month_cost" style="display:none">
                                                 <div id="order_revenue_graph_month_container" style = "width: 100%; height: 400px; margin: 0 auto">

                                                 </div>
                                            </div>
                                        </div>
                                      <div class="card col-lg-6 p-4">
                                      <label>Task</label> 
                                            <form class=" col-12 form" cluster-url="ajax/tasks/add_ajax" cluster-after='getTasks()'>
                                                
                                                 <div class="task_table_container" style="max-height: 300px;overflow:auto">
                                                        <table class="table table-striped mt-2" id='task_table' style="font-size: 13px">
                                                            <thead>
                                                                <tr>
                                                                    <th>
                                                                        Date
                                                                    </th>
                                                                    <th>
                                                                        Task
                                                                    </th>
                                                                    <th>
                                                                        Status
                                                                    </th>
                                                                    <th>

                                                                    </th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>

                                                            </tbody>
                                                        </table>
                                                 </div>
                                                
                                                <div class="error-main"></div>
                                                <div class="input-container">
                                                    <input type="text" class="form-control" placeholder="Enter Task" name="task" id="task"/>
                                                    
                                                    <div class="error-input"></div>
                                                </div>
                                                 <button type="submit" class="btn btn-primary col-12 mt-1 btn-submit" >Submit</button>
                                            </form>
                                        </div>
                                        <div class="card col-lg-3 p-4">
                                      <label>Tickets</label> 
                                         
                                                
                                                 <div class="task_table_container" style="max-height: 300px;overflow:auto">
                                                        <table class="table table-striped mt-2" id='ticket_table' style="font-size: 13px">
                                                            <thead>
                                                                <tr>
                                                                    <th>
                                                                        Title
                                                                    </th>
                                                                    
                                                                    <th>
                                                                        Action
                                                                    </th>
                                                                   
                                                                </tr>
                                                                <?php
                                                                foreach($ticket AS $tic)
                                                                {
                                                                ?>
                                                                <tr>
                                                                	<td> <?php echo $tic['cl_title']; ?>(Status: <?php echo $tic['cl_status']; ?>)</td>
                                                                	<td><a href="ticket/edit?id=<?php echo $tic['cl_id']; ?>">View</a></td>
                                                                </tr>
                                                                <?php
                                                                }
                                                                ?>
                                                            </thead>
                                                            <tbody>

                                                            </tbody>
                                                        </table>
                                                 </div>
                                                
                                               
                                            
                                        </div>
                                        
                                         <div class="card col-lg-3 p-4">
                                      <label>Warranty</label> 
                                         
                                                
                                                 <div class="task_table_container" style="max-height: 300px;overflow:auto">
                                                        <table class="table table-striped mt-2" id='warranty_table' style="font-size: 13px">
                                                            <thead>
                                                                <tr>
                                                                    <th>
                                                                       Item
                                                                    </th>
                                                                    
                                                                   
                                                                    <th>
                                                                        Status
                                                                    </th>
                                                                    <th>

                                                                    </th>
                                                                </tr>
                                                                 <?php
                                                                foreach($warranty AS $war)
                                                                {
                                                                ?>
                                                                <tr>
                                                                	<td> <?php echo $war['product']; ?></td>
                                                                	
                                                                
                                                                	<td> <?php echo $war['cl_status']; ?></td>
                                                                	<td><a href="warranty/edit?id=<?php echo $war['cl_id']; ?>">View</a></td>
                                                                </tr>
                                                                <?php
                                                                }
                                                                ?>
                                                            </thead>
                                                            <tbody>

                                                            </tbody>
                                                        </table>
                                                 </div>
                                                
                                               
                                            
                                        </div>
                                        
                                    </div>
                                </div>
                            </div>
<?php

$dateArray[] = date('d M Y');

for($i = 1; $i <= 15; $i++)
{
    $dateArray[] = date('d M Y', strtotime('-' . $i . ' day', strtotime(date('Y-m-d'))));
}


?>

                            <script language = "JavaScript">
$(document).ready(function(){
    $('#no_of_orders_li').click(function(e){
        e.preventDefault();
        $('.graph_container').hide();
        $('#graph_number').show();

        $('.graph_tab li a').removeClass('active');
        $(this).addClass('active');
    })

    $('#revenue_li').click(function(e){
        e.preventDefault();
        $('.graph_container').hide();
        $('#graph_cost').show();

        $('.graph_tab li a').removeClass('active');
        $(this).addClass('active');
    })
    
    $('#no_of_orders_month_li').click(function(e){
        e.preventDefault();
        $('.graph_container').hide();
        $('#graph_month_number').show();

        $('.graph_tab li a').removeClass('active');
        $(this).addClass('active');
    })
    
    $('#revenue_month_li').click(function(e){
        e.preventDefault();
        $('.graph_container').hide();
        $('#graph_month_cost').show();

        $('.graph_tab li a').removeClass('active');
        $(this).addClass('active');
    })

    
})



         $(document).ready(function() {
            var chart = {
                options3d: {
                  enabled: true

                  
               }
            }
            var title = {
               text: 'Orders'   
            };
            var subtitle = {
               text: ''
            };
            var xAxis = {
               categories: <?php echo json_encode($dateArray) ?>,
               reversed: true
            };
            var yAxis = {
               title: {
                  text: 'Number of orders'
               },
               plotLines: [{
                  value: 0,
                  width: 1,
                  color: '#808080'
               }]
            };   
            var tooltip = {
               valueSuffix: ''
            }
            var legend = {
               layout: 'vertical',
               align: 'right',
               verticalAlign: 'middle',
               borderWidth: 0
            };
            var series =  [{
                  name: 'All Orders',
                  data: <?php echo json_encode($jsonAllOrders) ?>,
                  visible: false
               }, 
               {
                  name: 'Cancelled Orders',
                  data: <?php echo json_encode($jsonCancelledOrders) ?>,
                  visible: false
               }, 
               {
                  name: 'Refunded Orders',
                  data: <?php echo json_encode($jsonRefundedOrders) ?>,
                  visible: false
               },
               {
                    name: 'Paid Orders',
                    data: <?php echo json_encode($jsonPaidOrders) ?>
               }
            ];

            var json = {};
            json.chart = chart;
            json.title = title;
            json.subtitle = subtitle;
            json.xAxis = xAxis;
            json.yAxis = yAxis;
         //   json.tooltip = tooltip;
            json.legend = legend;
            json.series = series;
            
            $('#order_graph_container').highcharts(json);






            var chart = {
                options3d: {
                  enabled: true

                  
               }
            }
            var title = {
               text: 'Orders'   
            };
            var subtitle = {
               text: ''
            };
            var xAxis = {
               categories: <?php echo json_encode($dateArray) ?>,
               reversed: true
            };
            var yAxis = {
               title: {
                  text: 'Revenue'
               },
               plotLines: [{
                  value: 0,
                  width: 1,
                  color: '#808080'
               }]
            };   
            var tooltip = {
               valueSuffix: ''
            }
            var legend = {
               layout: 'vertical',
               align: 'right',
               verticalAlign: 'middle',
               borderWidth: 0
            };
            var series =  [{
                  name: 'All Orders',
                  data: <?php echo json_encode($jsonAllOrdersSum) ?>,
                  visible: false
               }, 
               {
                  name: 'Cancelled Orders',
                  data: <?php echo json_encode($jsonCancelledOrdersSum) ?>,
                  visible: false
               }, 
               {
                  name: 'Refunded Orders',
                  data: <?php echo json_encode($jsonRefundedOrdersSum) ?>,
                  visible: false
               },
               {
                    name: 'Paid Orders',
                    data: <?php echo json_encode($jsonPaidOrdersSum) ?>
               }
            ];

            var json = {};
            json.chart = chart;
            json.title = title;
            json.subtitle = subtitle;
            json.xAxis = xAxis;
            json.yAxis = yAxis;
         //   json.tooltip = tooltip;
            json.legend = legend;
            json.series = series;
            
            $('#order_revenue_graph_container').highcharts(json);
         });
         
         
         
         
         
         
         var chart = {
                options3d: {
                  enabled: true

                  
               }
            }
            var title = {
               text: 'Orders'   
            };
            var subtitle = {
               text: ''
            };
            var xAxis = {
               categories: <?php echo json_encode($monthArray) ?>,
               reversed: true
            };
            var yAxis = {
               title: {
                  text: 'Number of orders'
               },
               plotLines: [{
                  value: 0,
                  width: 1,
                  color: '#808080'
               }]
            };   
            var tooltip = {
               valueSuffix: ''
            }
            var legend = {
               layout: 'vertical',
               align: 'right',
               verticalAlign: 'middle',
               borderWidth: 0
            };
            var series =  [{
                  name: 'All Orders',
                  data: <?php echo json_encode($jsonAllOrdersMonth) ?>,
                  visible: false
               }, 
               {
                  name: 'Cancelled Orders',
                  data: <?php echo json_encode($jsonCancelledOrdersMonth) ?>,
                  visible: false
               }, 
               {
                    name: 'Paid Orders',
                    data: <?php echo json_encode($jsonPaidOrdersMonth) ?>
               }
            ];

            var json = {};
            json.chart = chart;
            json.title = title;
            json.subtitle = subtitle;
            json.xAxis = xAxis;
            json.yAxis = yAxis;
         //   json.tooltip = tooltip;
            json.legend = legend;
            json.series = series;
            
            $('#order_graph_month_container').highcharts(json);
            
            
            
            
            var chart = {
                options3d: {
                  enabled: true

                  
               }
            }
            var title = {
               text: 'Orders'   
            };
            var subtitle = {
               text: ''
            };
            var xAxis = {
               categories: <?php echo json_encode($monthArray) ?>,
               reversed: true
            };
            var yAxis = {
               title: {
                  text: 'Number of orders'
               },
               plotLines: [{
                  value: 0,
                  width: 1,
                  color: '#808080'
               }]
            };   
            var tooltip = {
               valueSuffix: ''
            }
            var legend = {
               layout: 'vertical',
               align: 'right',
               verticalAlign: 'middle',
               borderWidth: 0
            };
            var series =  [{
                  name: 'All Orders',
                  data: <?php echo json_encode($jsonAllOrdersSumMonth) ?>,
                  visible: false
               }, 
               {
                  name: 'Cancelled Orders',
                  data: <?php echo json_encode($jsonCancelledOrdersSumMonth) ?>,
                  visible: false
               }, 
               {
                    name: 'Paid Orders',
                    data: <?php echo json_encode($jsonPaidOrdersSumMonth) ?>
               }
            ];

            var json = {};
            json.chart = chart;
            json.title = title;
            json.subtitle = subtitle;
            json.xAxis = xAxis;
            json.yAxis = yAxis;
         //   json.tooltip = tooltip;
            json.legend = legend;
            json.series = series;
            
            $('#order_revenue_graph_month_container').highcharts(json);
      </script>
                            
                          
                            <div class="row">
                                <div class="card col-xs-12 col-sm-12">
                                    <div class="card-body">
                                        <div class="alert alert-warning">There are <span style="<?php if($waitingofPaymentCount == 0){echo 'color:green';}else{echo 'color:red';} ?>;text-decoration: underline;"><?php echo $waitingofPaymentCount; ?></span> orders under waiting on payment which are ordered before 1 week</div>
                                        <?php
                                        if($withoutImageProductCountArray[0])
                                        { ?>
                                        <div class="alert alert-danger">There are <span style="text-decoration: underline;"><?php echo $withoutImageProductCountArray[0]['product_count']; ?></span> products with no default Image</div>
                                    <?php } ?>
                                        <select class="form-control" id="status">
                                                  <option value="">---Select Status---</option>
                                                   <option value="Processing" <?php if($status == 'Processing'){echo 'selected';} ?>>Processing</option>
                                                   <option value="Processing2" <?php if($status == 'Processing2'){echo 'selected';} ?>>Processing2</option>
                                                 <option value="Processed"<?php if($status == 'Processed'){echo 'selected';} ?>>Processed</option>
                                                 <option value="Waiting on payment" <?php if($status == 'Waiting on payment'){echo 'selected';} ?>>Waiting on payment</option>
                                                   <option value="Payment Received" <?php if($status == 'Payment Received'){echo 'selected';} ?>>Payment Recieved</option>
                                                  <option value="Being prepared for shipping" <?php if($status == 'Being prepared for shipping'){echo 'selected';} ?>>Being prepared for shipping</option>
                                                   <option value="Shipped" <?php if($status == 'Shipped'){echo 'selected';} ?>>Shipped</option>
                                                 <option value="Delivered" <?php if($status == 'Delivered'){echo 'selected';} ?>>Delivered</option>
                                                  <option value="Cancelled"<?php if($status == 'Cancelled'){echo 'selected';} ?>>Cancelled</option>
                                                   <option value="Items ordered" <?php if($status == 'Items ordered'){echo 'selected';} ?>>Items ordered</option>
                                                  <option value="Items received"<?php if($status == 'Items received'){echo 'selected';} ?>>Items received</option>
                                                  <option value="Money refunded" <?php if($status == 'Money refunded'){echo 'selected';} ?>>Money refunded</option>
                                              </select>
                                        <div class="table-responsive" style="width:100%">
                                    <table class="table table-striped table-hover dt-responsive ACP_table_dashboard" style="width:100%">
                                        <thead>
                                            <tr>
                                            <th>Order No.</th>  
                                               <th>Type</th>
                                               <th>
                                                Payment Type
                                               </th>
                                                <th>Name &amp; Shipping Address</th>
                                                <th>Mobile</th>
                                                <th>Email</th>
                                                    <th>Country</th>
                                                
                                                <th>
                                                    Final Amount
                                                </th>
                                              <!--   <th>
                                                    Wallet
                                                </th>
                                                <th>
                                                    Promocode
                                                </th>-->
                                               

                                                <th data-priority="2">
                                                    
                                                    Status
                                                </th>
                                                <th>
                                                    Created At
                                                </th>
                                                <th>
                                                    Invoice
                                                </th>
                                                
                                                <th data-priority="1">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                           <?php
                                            foreach($userOrders AS $orders)
                                            {
                                                $count = 1;
                                                $uid=$orders['cl_user_id'];
                                                if($orders['cl_user_id'])
                                                {
                                                //$us = $obj->getUser($uid);
                                                }
                                            ?>
                                            <tr class="action-container">
                                                    <td data-order="<?php echo $count++ ?>">OR-<?php echo htmlspecialchars($orders['cl_id']);?><br/>

                                                        <?php
                                                        if(date("Y-m-d", strtotime($orders['cl_created_at'])) == date('Y-m-d'))
                                                        {
                                                            echo '<div class="alert alert-warning">Todays Order</div>';
                                                        }
                                                        else if(date("Y-m-d") == date("Y-m-d",strtotime("+1 days", strtotime($orders['cl_created_at']))))
                                                        {
                                                            echo '<div class="alert alert-info">Yesterdays Order</div>';
                                                        }
                                                        
                                                        ?>
                                                    </td>
                                                <td><?php if($orders['cl_checkout_type'] == 'ind'){ echo 'IND';}else{echo 'COM';}?></td>
                                                <td><?php if($orders['cl_payment_type'] == 'Bank Transfer'){ echo 'BT';}else{echo $orders['cl_payment_type'];}?></td>
                                                <td><?php 
                                                if($orders['cl_checkout_type'] == 'ind')
                                                {
                                                    echo htmlspecialchars($orders['cl_fname']).' '.htmlspecialchars($orders['cl_surname']);
                                                }
                                                else
                                                {
                                                    echo htmlspecialchars($orders['cl_company_name']);
                                                    echo '<br/>';
                                                    echo htmlspecialchars('Registration Number : ' . $orders['cl_registration_number']) . '<br/>';
                                                    echo htmlspecialchars('VAT Number : ' . $orders['cl_vat_number']);
                                                }
                                                ?>
                                                <br/><?php echo htmlspecialchars($orders['cl_address']);?><br/><?php echo htmlspecialchars($orders['cl_city']);?><br><?php echo htmlspecialchars($orders['cl_county']);?><br/><?php echo htmlspecialchars($orders['cl_pin']);?>
                                                    <br/>
                                                    IP : <?php echo htmlspecialchars($orders['cl_ip']) ?>
                                                </td>
                                                <td><?php echo htmlspecialchars($orders['cl_mobile']);?></td>
                                                <td><?php echo htmlspecialchars($orders['cl_email']);?></td>
                                                    <td><?php echo htmlspecialchars($orders['cl_country']);?></td>
                                                
                                                <td><?php echo htmlspecialchars($orders['cl_total']) ?></td>
                                             <!--   <td><?php if($orders['cl_wallet_used'] == 1){echo $orders['cl_wallet_amount'];} ?></td>
                                                <td><?php if($orders['cl_promocode_id'] != 0){echo 'Used';} ?></td>-->
                                                
                                                <td>
                                                    <?php
                                                        if($orders['cl_status'] == 'Processing')
                                                        {
                                                            $bgcolor='#FF9100';
                                                        }
                                                        else if($orders['cl_status'] == 'Processing2')
                                                        {
                                                            $bgcolor='#FF9100';
                                                        }
                                                        else if($orders['cl_status'] == 'Processed')
                                                        {
                                                            $bgcolor='#00EF10';
                                                        }
                                                        else if($orders['cl_status'] == 'Waiting on payment')
                                                        {
                                                            $bgcolor='#FFEF00';
                                                        }
                                                        else if($orders['cl_status'] == 'Shipped')
                                                        {
                                                            $bgcolor='#00D3EB';
                                                        }
                                                        else if($orders['cl_status'] == 'Delivered')
                                                        {
                                                            $bgcolor='#91FF00';
                                                        }
                                                        else if($orders['cl_status'] == 'Cancelled')
                                                        {
                                                            $bgcolor='#FF0000';
                                                        }
                                                        else if($orders['cl_status'] == 'Payment Received')
                                                        {
                                                            $bgcolor='#BCFF00';
                                                        }
                                                        else if($orders['cl_status'] == 'Items ordered')
                                                        {
                                                            $bgcolor='#00FF80';
                                                        }
                                                        else if($orders['cl_status'] == 'Items received')
                                                        {
                                                            $bgcolor='#91FF00';
                                                        }
                                                        else if($orders['cl_status'] == 'Money refunded')
                                                        {
                                                            $bgcolor='#FF004D';
                                                        }
                                                        else
                                                        {
                                                            $bgcolor='#FF0000';
                                                        }


                                                    echo '<span style="width:15px;height:15px;background-color:' . $bgcolor . ';border-radius:25px;float: left;
    margin-right: 5px;
    margin-top: 3px;"></span>' . $orders['cl_status'];
                                                  ?>
                                                </td>
                                                <td><?php echo htmlspecialchars(date("d M Y H:i:s", strtotime($orders['cl_created_at'])));?></td>
                                                <td style="font-size: 10px">
                                                    <?php
                                                    if($orders['cl_auto_invoice_doc'] != null)
                                                        { ?>
                                                    <a href="<?php echo MAIN_DOMAIN ?>/uploads/invoice/<?php echo $orders['cl_auto_invoice_doc'] ?>" target="_blank" class="btn btn-success" style="font-size: 10px">Auto</a>
                                                    <?php
                                                }

                                                if($orders['cl_invoice_doc'] != null)
                                                        {
                                                    ?>
                                                    <a target="_blank" href="<?php echo DOMAIN ?>/uploads/invoice/<?php echo $orders['cl_invoice_doc'] ?>" class="btn btn-success" style="font-size: 10px" >Uploaded</a>
                                                    <?php
                                                }
                                                ?>
                                                </td>
                                                
                                                <td> 
                                                    <a id="edit" href="/user-orders/edit?id=<?php  echo htmlspecialchars($orders['cl_id']); ?>" class="btn btn-success">
                                                        <i class="fa fa-edit"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php
                                            }
                                            ?>
                                           
                                        </tbody>
                                    </table>
                                    </div>
                                    </div>
                                </div>
                            </div>
                       
						
						
                       <script>
                            $(document).ready(function(){
                                getTasks();
                                $('.active').removeClass('active');
                                $('#store_menu_ul').show();
                                $('#dashboard-menu').addClass('active');
                                
                            
                            }); 

                            function getTasks()
                            {
                                $('#task_table tbody').html('<tr><td colspan="3">Loading....</td></tr>');
                                $.get('ajax/tasks/list', function(res){
                                    var html = '';
                                    $(res).each(function(i, value){
                                        
                                        var formattedDate = new Date(value.cl_created_at);
                                        var d = formattedDate.getDate();
                                        var m =  formattedDate.getMonth();
                                        m+= 1;  // JavaScript months are 0-11
                                        
                                        if(m < 10)
                                        {
                                            m = '0' + m;
                                        }
                                        var y = formattedDate.getFullYear();

                                        var formattedDate = d + '-' + m + '-' + y;
                                        
                                        html+= '<tr class="action-container"><td>' + formattedDate + '</td><td>' + value.cl_task + '</td>';
                                        var status = value.cl_status;
                                        html+= '<td><select class="form-control task_status" cluster-id="' + value.cl_id + '" style="font-size: 13px;max-height:30px;padding-top:4px">';
                                            html+= '<option value="Unsolved"';
                                                    
                                                if(status == 'Unsolved')
                                                {
                                                    html+= ' selected="selected" ';
                                                }   
                                            html+= '>Unsolved</option>';
                                            html+= '<option value="Solved"';
                                                if(status == 'Solved')
                                                {
                                                    html+= ' selected="selected" ';
                                                }   
                                            html+= '>Solved</option>';
                                        html+= '</select>';
                                        if(status == 'Unsolved')
                                        {
                                            html+= '<button type="button" class="status_button btn btn-danger btn-sm col-12"></button>';
                                        }
                                        else
                                        {
                                            html+= '<button type="button" class="status_button btn btn-success btn-sm col-12"></button>';
                                        }
                                        
                                        html+= '</td><td><button type="button" cluster-href="ajax/tasks/delete_ajax.php?id=' + value.cl_id + '" class="btn btn-delete btn-danger"><i class="bi bi-trash"></i></button><div class="error-input"></div></td></tr>';
                                        
                                        
                                    });
                                    
                                    loadTaskTable(html);
                                }, 'json')
                                        .fail(function(xhr){
                                        $('#task_table tbody').html('<tr><td colspan="3">Failed to load</td></tr>');    
                                });
                            }
                            
                            function loadTaskTable(html)
                            {
                                $('#task_table tbody').html(html); 
                            }
                            
                            $(document).on('change', '.task_status', function(){
                                var id = $(this).attr('cluster-id');
                                var status = $(this).val();
                                var parent = $(this).parents('tr').first();
                                $(parent).find('.error-input').html('<div class="alert alert-warning">Changing Status....</div>');
                                $.post('ajax/tasks/change_status?id=' + id, {status:status}, function(){
                                    
                                    $(parent).find('.error-input').html('<div class="alert alert-success">Status Changed Successfully</div>');
                                    getTasks();
                                }, 'json')
                                .fail(function(){
                                    $(parent).find('.error-input').html('<div class="alert alert-danger">Something went wrong while chnaging status</div>');        
                                });
                            });
                       
                </script>              

  <?php
  include 'footer.php';