<?php
include("db/cn.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if(isset($_SESSION['user_name']) && isset($_SESSION['user_role'])&& isset($_SESSION['outlet_name'])
&& isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
	$outlet_address = $_SESSION['outlet_address'];
	$outlet_name = $_SESSION['outlet_name'];
}



$rec10 = mysqli_query($connection, "SELECT order_id, sale_cost FROM log_user_sales WHERE status ='refund'   GROUP BY order_id");

if ($rec10) {
    $total_sales = 0;
    while ($row3 = mysqli_fetch_array($rec10)) {
        @$total_sales += $row3['sale_cost'];
    }
    echo "";
    if (mysqli_num_rows($rec10) == 0) {
        echo "";
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>DashBoard - Whole Sale Retail</title>
    
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="css/custom_css.css" />

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  
</head>

<style>
 #product-container-wrapper {
    max-height: 700px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
/* Custom styles for sidebar */
 #table-container-wrapper {
    max-height: 500px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}

@media (min-width: 880px) {
    .sidebar {
        width: 100%;
        /* Change sidebar width to 100% on mobile */
        max-width: 120px; /* Set maximum width for the sidebar */
    }
}

@media (min-width: 880px) {
    .main-content {
        margin-left: ; /* Width of the sidebar */
    }
}

/* Added new class to control overlay */
.overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    display: none; /* Initially hidden */
}
    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(360deg, #060606, #3C2F23);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }

    .sidebar.hide {
        transform: translateX(-100px);
        /* Move sidebar out of the viewport when it is hidden */
    }

    .sidebar .nav-item {
        padding: 10px 0;
        text-align: center;
        position: relative;
        font-size: 12px;
    }

    .sidebar .nav-link {
        color: #fff;
        position: relative;
        /* Ensure icon and text are positioned relative to the nav link */
        z-index: 2;
        /* Ensure the text and icon are above the hover background */
    }

    .sidebar .nav-link i {
        margin-bottom: 5px;
        /* Adjust the margin of the icon */
    }

    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
        background-color: #fff;
        content: '';
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        /* Ensure the hover background is below the text and icon */
    }

    .sidebar .nav-item:hover .nav-link {
        color: #524C42;
    }

    /* Custom styles for divider */
    .sidebar .nav-item:after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background-color: #fff;
        transition: height 0.3s ease-in-out;
        /* Transition effect for smooth animation */
    }

    /* Custom styles for header */
    .header {
        background: linear-gradient(270deg, #060606, #3C2F23);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }

    .header .navbar-toggler {
        color: #fff;
    }

    .header .navbar-toggler-icon {
        color: #fff;
        /* Set the color of the toggle button to white */
    }

    .header .navbar-toggler.white {
        color: #fff !important;
        /* Ensure the toggle button is white */
    }

    .header .navbar-brand {
        color: #fff;
        /* Set navbar brand text color to white */
    }

    .header .nav-item .nav-link {
        color: #fff;
        /* Set nav link text color to white */
    }

.main-content {
    margin-top: 50px; /* Height of fixed header */
    margin-left: 100px; /* Initially, set margin-left to 0 */
    padding-top: 30px; /* Height of fixed header */
    transition: margin-left 0.3s ease-in-out; /* Add transition for smoother animation */
}


    /* Custom styles for search bar */
    .search-container {
        display: flex;
        align-items: center;
       width:100%;
        margin: 2px auto;
        float:left;
	}

/* Updated hide class to apply to the overlay */
.sidebar.hide, .overlay.hide {
    transform: translateX(-100%);
}

    .search-input {
        width: 100%;
        padding: 10px 30px 10px 10px;
        /* Adjust padding to accommodate the icon */
        border: 1px solid #ccc;
        border-radius: 20px;
        font-size: 16px;
    }

    .search-icon {
        position: relative;
        left: -25px;
        /* Adjust the position of the icon */
        color: #aaa;
    }

    .search-icon i {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }

    .btn-dark {
        background: #503F2E;
        color: #fff;
        border: 1px solid #503F2E;
    }

    .btn-dark:hover {
        background: #fff;
        color: #503F2E;
        border: 1px solid #503F2E;
    }

    .bg-dark2 {
        background: #503F2E;
        color: #fff;
    }

    .modal-content {
        animation: modal-animation 0.5s;
    }

    @keyframes modal-animation {
        from {
            opacity: 0;
            transform: scale(0.8);
        }

        to {
            opacity: 1;
            transform: scale(1);
        }
    }

	
		
		        #searchResults {
            position: absolute;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            max-height: 200px;
            overflow-y: auto;
            width: 85%;
            display: none;
        }
        #searchResults div {
            padding: 10px;
            cursor: pointer;
        }
        #searchResults div:hover {
            background-color: #f1f1f1;
        }
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	.border-left-dark{
	   border-left:7px solid #000;
	   border-right:2px solid #0A5064;
	   border-bottom:2px solid #0A5064;
	   border-top:2px solid #0A5064;	
	   border-radius:7px;
		}
		.btn-black{
		background:#4C0027;
		color:#fff;
		border:1px #4C0027 solid;	
			}
			.btn-black:hover{
			  	background:#fff;
		color:#4C0027;
		border:1px #4C0027 solid;
				}
</style>

<body>

<?php
if(isset($msg)){
	
	echo $msg;
	}
?>
<?php include("common/hd.php"); ?>
<!-- Sidebar -->
<?php include("common/sd.php"); ?>
<div class="main-content">
<div class="container-fluid">
                     <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
                        
                    </div>

                    <div class="container" style="background: linear-gradient(360deg, #060606, #503F2E); border:5px solid #3C2F23; border-radius:20px;">
                    <div class="row">
                    <div class="col-sm-5"> 
                    <br>
                    <img src="img/print_logo.png" width="70" height="70">
                    <br><br>
                    <h3 class="mb-3 text-white" style="font-size:25px">Welcome Admin ,<br>Whole Sale Retail</h3>
                    <p class="text-white btn btn-dark btn-sm">Logged In</p>
                    </div>
                    <div class="col-sm-2"></div>
                    <div class="col-sm-5">
                    
                    <img src="../img/school.png" width="596" height="371" class="img-fluid" />
                    </div>
                    </div>
                    
                    </div>        

<br><br>

                   <div class="container">
                     <div class="row">
<?php 
$date_time22 = date("Y-m-d");

// Get the first and last day of the current month
$first_day_of_month1 = date("Y-m-01");
$last_day_of_month1 = date("Y-m-t");

// First, select the unique order_id with their respective discount_amount
$query = "
    SELECT order_id, discount_amount
    FROM log_user_sales
    WHERE date_time BETWEEN '$first_day_of_month1' AND '$last_day_of_month1'
    GROUP BY order_id
";

$sale_month = mysqli_query($connection, $query);

if ($sale_month) {
    $total_sale_now_month1 = 0; // Initialize as an integer
    while ($row = mysqli_fetch_array($sale_month)) {
        if (isset($row['discount_amount'])) {
            // Make sure discount_amount is a valid number before adding it
            $discount = is_numeric($row['discount_amount']) ? (float)$row['discount_amount'] : 0;
            $total_sale_now_month1 += $discount;
        }
    }
    // echo "Total discount amount for the current month (unique order IDs): " . $total_sale_now_month;
} else {
    echo "Error executing query: " . mysqli_error($connection);
}





// First, select the unique order_id with their respective discount_amount
$queryq = "
    SELECT order_id, discount_amount
    FROM log_user_sales
    WHERE date_time BETWEEN '$first_day_of_month1' AND '$last_day_of_month1' && status = 'refund'
    GROUP BY order_id
";

$sale_month_refund = mysqli_query($connection, $queryq);

if ($sale_month_refund) {
    $total_sale_now_month_refund = 0; // Initialize as an integer
    while ($row = mysqli_fetch_array($sale_month_refund)) {
        if (isset($row['discount_amount'])) {
            // Make sure discount_amount is a valid number before adding it
            $discount_re = is_numeric($row['discount_amount']) ? (float)$row['discount_amount'] : 0;
            $total_sale_now_month_refund += $discount_re;
        }
    }
    // echo "Total discount amount for the current month (unique order IDs): " . $total_sale_now_month;
} else {
    echo "Error executing query: " . mysqli_error($connection);
}




?>



                    <?php
$date_time11 = date("Y-m-d");

// SQL query to select unique order_id with their respective discount_amount
$query = "
    SELECT order_id, discount_amount
    FROM log_user_sales
    GROUP BY order_id
";

$sale_anu = mysqli_query($connection, $query);

if ($sale_anu) {
    $total_sale_anu12 = 0;
    while ($row = mysqli_fetch_assoc($sale_anu)) {
        if (isset($row['discount_amount'])) {
			$discount1 = is_numeric($row['discount_amount']) ? (float)$row['discount_amount'] : 0;
            $total_sale_anu12 += $discount1;
        } else {
            echo "No sale_amount found for order_id: " . $row['order_id'] . "<br>";
        }
    }
   // echo "Total discount amount for unique order IDs: " . $total_sale_anu;
} else {
    echo "Error executing query: " . mysqli_error($connection);
}
?>
<!-- Earnings (Monthly) Card Example -->
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-dark shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-uppercase mb-1"  style="font-size:13px;color:#785F46;">
                                                Sale Revenue(Monthly)</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">Rs.<?php
											@$total_sale_anu = @$total_sale_anu12 -  @$total_sale_now_month_refund;
											 echo round(@$total_sale_anu);
											
											@$total_sale_yearly = round(@$total_sale_anu); ?>/-</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-dollar-sign fa-2x" style="color:#785F46;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Earnings (Monthly) Card Example -->
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-dark shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-uppercase mb-1"  style="font-size:13px;color:#785F46;">
                                                Sale Revenue(Annual)</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">Rs.<?php
											@$total_sale_anu = @$total_sale_anu12 -  @$total_sale_now_month_refund;
											 echo round(@$total_sale_anu);
											
											@$total_sale_yearly = round(@$total_sale_anu); ?>/-</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-dollar-sign fa-2x" style="color:#785F46;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                   

                        <!-- Earnings (Monthly) Card Example -->
                         <?php
// Get the current date
$date_time = date("Y-m-d");

// Get the first and last day of the current month
$first_day_of_month = date("Y-m-01");
$last_day_of_month = date("Y-m-t");

// Query for total sales in the current month
$sale_month_query = mysqli_query($connection, "
    SELECT SUM(sale_cost) AS sale_amount 
    FROM log_user_sales 
    WHERE date_time BETWEEN '$first_day_of_month' AND '$last_day_of_month'
");

$total_sales2 = 0; // Default to 0 in case of failure

if ($sale_month_query) {
    $sale_result = mysqli_fetch_array($sale_month_query);
    if ($sale_result && isset($sale_result['sale_amount'])) {
        $total_sales2 = $sale_result['sale_amount'];
    }
} else {
    echo "Error executing sales query: " . mysqli_error($connection);
}

// Query for total refunds in the current month
$refund_query = mysqli_query($connection, "
    SELECT SUM(sale_cost) AS refund_amount 
    FROM log_user_sales 
    WHERE date_time BETWEEN '$first_day_of_month' AND '$last_day_of_month' AND status = 'refund'
");

$total_refunds = 0; // Default to 0 in case of failure

if ($refund_query) {
    $refund_result = mysqli_fetch_array($refund_query);
    if ($refund_result && isset($refund_result['refund_amount'])) {
        $total_refunds = $refund_result['refund_amount'];
    }
} else {
    echo "Error executing refund query: " . mysqli_error($connection);
}

// Calculate the net sale (sales - refunds)
$total_sale_now_month2 = $total_sales2 - $total_refunds;
?>

<!-- Pending Requests Card Example 
<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-dark shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-uppercase mb-1" style="font-size:13px;color:#785F46;">
                        Sale Cost (Monthly)
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                        Rs. <?php echo round(@$total_sale_now_month2).'/-';
											@$cost_sale_monthly = round(@$total_sale_now_month2 - $total_sales); ?> 
                    </div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-dollar-sign fa-2x" style="color:#785F46;"></i>
                </div>
            </div>
        </div>
    </div>
</div>-->

                            <?php
// Get the current date
$date_time = date("Y-m-d");

// Query for total sales (annual)
$sale_cost_query = mysqli_query($connection, "SELECT SUM(sale_cost) AS sale_amount FROM log_user_sales");
$sale_cost_data = 0; // Default value to prevent undefined variable error

if ($sale_cost_query) {
    $sale_cost_result = mysqli_fetch_array($sale_cost_query);
    if ($sale_cost_result && isset($sale_cost_result['sale_amount'])) {
        $sale_cost_data = $sale_cost_result['sale_amount'];
    }
} else {
    echo "Error executing sales query: " . mysqli_error($connection);
}

// Query for total refunds (annual)
$sale_cost_re_query = mysqli_query($connection, "SELECT SUM(sale_cost) AS sale_amount FROM log_user_sales WHERE status = 'refund'");
$sale_cost_data_re = 0; // Default value to prevent undefined variable error

if ($sale_cost_re_query) {
    $sale_cost_re_result = mysqli_fetch_array($sale_cost_re_query);
    if ($sale_cost_re_result && isset($sale_cost_re_result['sale_amount'])) {
        $sale_cost_data_re = $sale_cost_re_result['sale_amount'];
    }
} else {
    echo "Error executing refund query: " . mysqli_error($connection);
}

// Calculate the net sale (sales - refunds)
$net_sale_cost = $sale_cost_data - $sale_cost_data_re;
?>


<!-- Sale Cost (Annual) Card Example -->
<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-dark shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-uppercase mb-1" style="font-size:13px;color:#785F46;">
                        Sale Cost (Monthly)
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                        Rs. <?php echo round($net_sale_cost - $total_sales); 
                        $SACost = $net_sale_cost - $total_sales;
                        ?> /-
                    </div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-dollar-sign fa-2x" style="color:#785F46;"></i>
                </div>
            </div>
        </div>
    </div>

</div>


<!-- Sale Cost (Annual) Card Example -->
<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-dark shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-uppercase mb-1" style="font-size:13px;color:#785F46;">
                        Sale Cost (Annual)
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                        Rs. <?php echo round($net_sale_cost - $total_sales); ?> /-
                    </div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-dollar-sign fa-2x" style="color:#785F46;"></i>
                </div>
            </div>
        </div>
    </div>

</div>
      </div>               
                     <div class="row">
                       <?php
					$date_time212 = date("Y-m-d");
					
					// Get the first and last day of the current month
					$first_day_of_month = date("Y-m-01");
					$last_day_of_month = date("Y-m-t");
					
					// Modify the SQL query to filter records within the current month
					$cash_out_month = mysqli_query($connection, "
						SELECT SUM(amount) AS total_amounts 
						FROM incash 
						WHERE date_time BETWEEN '$first_day_of_month' AND '$last_day_of_month'
					");
					
					if ($cash_out_month) {
						$cash_outdata_month = mysqli_fetch_array($cash_out_month);
						if ($cash_outdata_month && isset($cash_outdata_month['total_amounts'])) {
							$totalAmount_cashexpense_month = $cash_outdata_month['total_amounts'];
							echo "";
						} else {
							echo "";
						}
					} else {
						echo "Error executing query: " . mysqli_error($connection);
					}
						?>
                    
                        
                         <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-dark shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-uppercase mb-1"  style="font-size:13px;color:#785F46;">
                                                Expense (Monthly)</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">Rs.<?php echo round(@(int)$totalAmount_cashexpense_month); 
											@$expense_cost_month = round(@(int)$totalAmount_cashexpense_month);
											?>/-</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-calendar fa-2x " style="color:#785F46;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                     <?php
					 $date_time21 = date("Y-m-d");
					 $cash_out = mysqli_query($connection, "SELECT SUM(amount) AS total_amountss FROM incash ");
					 if ($cash_out) {
						$cash_outdata = mysqli_fetch_array($cash_out);
						if ($cash_outdata && isset($cash_outdata['total_amountss'])) {
							$totalAmount_cashexpense = $cash_outdata['total_amountss'];
							echo "";
						} else {
							echo "";
						}
						} else {
							echo "Error executing query: " . mysqli_error($connection);
						}
						?>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-dark shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-uppercase mb-1"  style="font-size:13px;color:#785F46;">
                                               Expense (Annual)</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">Rs.<?php echo round(@(int)$totalAmount_cashexpense);
											@$expense_cost_yearly = round(@(int)$totalAmount_cashexpense);
											 ?>/-</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-dollar-sign fa-2x " style="color:#785F46;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Earnings (Monthly) Card Example -->
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-dark shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-uppercase mb-1"  style="font-size:13px;color:#785F46;">
                                               Net-Profit (Monthly)</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">Rs.<?php 
											
											@$netProfita = $total_sale_yearly - $totalAmount_cashexpense   ;
									$netProfit = $netProfita - $SACost ;
											 echo round(@$netProfit);
											
											?>/-</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-dollar-sign fa-2x " style="color:#785F46;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Earnings (Monthly) Card Example -->
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-dark shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-uppercase mb-1"  style="font-size:13px;color:#785F46;">
                                               Net-Profit (Annual)</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">Rs. <?php 
											
									@$netProfita = $total_sale_yearly - $totalAmount_cashexpense   ;
									$netProfit = $netProfita - $SACost ;
											 echo round(@$netProfit);
											 ?>/-</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-dollar-sign fa-2x " style="color:#785F46;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Pending Requests Card Example -->
                        
                        
                     </div>
                     
                   </div>
                   
                   
              
                   <!--line graph-->
                   <div class="container" style="margin-bottom:80px;">
                    <div class="row">
                      <div class="col-sm-8 ">
                        <div class="chart-container">
                        <div>
                                <button class="btn btn-dark btn-sm" onclick="filterData(7)">7 Days</button>
                                <button class="btn btn-dark btn-sm" onclick="filterData(14)">14 Days</button>
                                <button class="btn btn-dark btn-sm" onclick="filterData(28)">28 Days</button>
                            </div>
                          <canvas class="col-sm-12" id="lineChart"></canvas>
                            
                        </div>
                      </div>
                      <div class="col-sm-4">
                         <div class="chart-container">
                           <canvas id="donutChart"></canvas>
                        </div>
                      </div>
                    </div>
                  </div>



                </div>


<?php
// Database connection (assuming $connection is already defined)
$start_of_month = date("Y-m-01");
$end_of_month = date("Y-m-t");

// Fetch daily sales data for the current month
$sales_query = mysqli_query($connection, "
    SELECT DATE(date_time) AS date, SUM(discount_amount) AS total_sales 
    FROM log_user_sales 
    WHERE date_time BETWEEN '$start_of_month' AND '$end_of_month'
    GROUP BY DATE(date_time)
");

$sales_data = [];
while ($row = mysqli_fetch_assoc($sales_query)) {
    $sales_data[$row['date']] = $row['total_sales'];
}

// Fetch daily purchase data for the current month
$purchases_query = mysqli_query($connection, "
    SELECT DATE(date_time) AS date, SUM(sale_cost) AS total_purchases 
    FROM log_user_sales 
    WHERE date_time BETWEEN '$start_of_month' AND '$end_of_month'
    GROUP BY DATE(date_time)
");

$purchases_data = [];
while ($row = mysqli_fetch_assoc($purchases_query)) {
    $purchases_data[$row['date']] = $row['total_purchases'];
}

// Pass data to JavaScript
$sales_data_json = json_encode($sales_data);
$purchases_data_json = json_encode($purchases_data);
?>
  <?php
// Database connection (assuming $connection is already defined)
$current_date_expense = date("Y-m-d");

// Get the first and last day of the current month
$start_of_month_expense = date("Y-m-01");
$end_of_month_expense = date("Y-m-t");

// Sales Query
$sales_query_expense = mysqli_query($connection, "
    SELECT SUM(discount_amount) AS total_sales_expense 
    FROM log_user_sales 
    WHERE date_time BETWEEN '$start_of_month_expense' AND '$end_of_month_expense'
");

$total_sales_expense = 0;
if ($sales_query_expense) {
    $sales_result_expense = mysqli_fetch_array($sales_query_expense);
    if ($sales_result_expense && isset($sales_result_expense['total_sales_expense'])) {
        $total_sales_expense = $sales_result_expense['total_sales_expense'];
    }
}

// Purchase Query
$purchases_query_expense = mysqli_query($connection, "
    SELECT SUM(sale_cost) AS total_purchases_expense 
    FROM log_user_sales 
    WHERE date_time BETWEEN '$start_of_month_expense' AND '$end_of_month_expense'
");

$total_purchases_expense = 0;
if ($purchases_query_expense) {
    $purchases_result_expense = mysqli_fetch_array($purchases_query_expense);
    if ($purchases_result_expense && isset($purchases_result_expense['total_purchases_expense'])) {
        $total_purchases_expense = $purchases_result_expense['total_purchases_expense'];
    }
}

// Expense Query
$expense_query_expense = mysqli_query($connection, "
    SELECT SUM(amount) AS total_expense_expense 
    FROM incash 
    WHERE date_time BETWEEN '$start_of_month_expense' AND '$end_of_month_expense'
");

$total_expense_expense = 0;
if ($expense_query_expense) {
    $expense_result_expense = mysqli_fetch_array($expense_query_expense);
    if ($expense_result_expense && isset($expense_result_expense['total_expense_expense'])) {
        $total_expense_expense = $expense_result_expense['total_expense_expense'];
    }
}

// Pass data to JavaScript
$sales_data_json_expense = json_encode($total_sales_expense);
$purchases_data_json_expense = json_encode($total_purchases_expense);
$expense_data_json_expense = json_encode($total_expense_expense);
?>  
</div>    
</body>
 <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <script>
        // Retrieve PHP data
        var salesData = <?php echo $sales_data_json; ?>;
        var purchasesData = <?php echo $purchases_data_json; ?>;

        // Get the current date and first and last day of the current month
        var currentDate = new Date();
        var firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
        var lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

        // Generate labels for the current month
        var labels = [];
        for (var d = new Date(firstDay); d <= lastDay; d.setDate(d.getDate() + 1)) {
            labels.push(d.toISOString().split('T')[0]);
        }

        // Function to filter data
        function filterData(days) {
            var endDate = new Date();
            var startDate = new Date();
            startDate.setDate(endDate.getDate() - days + 1); // Calculate start date based on days

            var filteredLabels = [];
            var filteredSalesData = [];
            var filteredPurchasesData = [];

            labels.forEach(function(label, index) {
                var currentDate = new Date(label);
                if (currentDate >= startDate && currentDate <= endDate) {
                    filteredLabels.push(label);
                    filteredSalesData.push(salesData[label] || 0);
                    filteredPurchasesData.push(purchasesData[label] || 0);
                }
            });

            // Update chart data
            myChart.data.labels = filteredLabels;
            myChart.data.datasets[0].data = filteredPurchasesData;
            myChart.data.datasets[1].data = filteredSalesData;
            myChart.update();
        }

        // Initial data for the line chart
        var initialSalesDataArray = [];
        var initialPurchasesDataArray = [];

        labels.forEach(function(label) {
            initialSalesDataArray.push(salesData[label] || 0);
            initialPurchasesDataArray.push(purchasesData[label] || 0);
        });

        // Data for the line chart
        var data = {
            labels: labels,
            datasets: [
                {
                    label: 'Purchase',
                    borderColor: 'rgba(80, 63, 46, 1)',
                    backgroundColor: 'rgba(80, 63, 46, 0.2)',
                    data: initialPurchasesDataArray,
                    fill: 'origin'
                },
                {
                    label: 'Sale',
                    borderColor: 'rgba(6, 8, 9, 1)',
                    backgroundColor: 'rgba(6, 8, 9, 0.2)',
                    data: initialSalesDataArray,
                    fill: 'origin'
                }
            ]
        };

        // Chart configuration
        var config = {
            type: 'line',
            data: data,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Purchase Vs Sale Report'
                    }
                },
                scales: {
                    x: {
                        type: 'category',
                        labels: labels
                    }
                },
                animation: {
                    duration: 2800, // 2 seconds
                    easing: 'easeInOutQuad'
                }
            }
        };

        // Create the chart
        var ctx = document.getElementById('lineChart').getContext('2d');
        var myChart = new Chart(ctx, config);
    </script>
  <script>
           // Retrieve PHP data
        var salesDataExpense = <?php echo $sales_data_json_expense; ?>;
        var purchasesDataExpense = <?php echo $purchases_data_json_expense; ?>;
        var expenseDataExpense = <?php echo $expense_data_json_expense; ?>;

        // Data for the doughnut chart
        var dataExpense = {
            labels: ['Expense', 'purchase', 'Sale'],
            datasets: [{
                data: [expenseDataExpense, purchasesDataExpense, salesDataExpense],
                backgroundColor: [
                    'rgba(180, 143, 106, 0.8)',
                    'rgba(120, 95, 70, 0.8)',
                    'rgba(80, 63, 46, 0.8)'
                ],
                hoverBackgroundColor: [
                    'rgba(180, 143, 106, 1)',
                    'rgba(120, 95, 70, 1)',
                    'rgba(80, 63, 46, 1)'
                ]
            }]
        };

        // Chart configuration
        var configExpense = {
            type: 'doughnut',
            data: dataExpense,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Expense, Purchase, and Sale Report'
                    }
                },
                animation: {
                    animateRotate: true,
                    animateScale: true,
                    duration: 2000, // 2 seconds
                    easing: 'easeInOutQuad'
                }
            }
        };

        // Create the chart
        var ctxExpense = document.getElementById('donutChart').getContext('2d');
        var myChartExpense = new Chart(ctxExpense, configExpense);
 
document.addEventListener("DOMContentLoaded", function () {
    var sidebar = document.getElementById("sidebar");
    var overlay = document.createElement("div");
    overlay.classList.add("overlay");
    document.body.appendChild(overlay);

    function toggleSidebar() {
        sidebar.classList.toggle("hide");
        overlay.classList.toggle("hide");

        var mainContent = document.querySelector(".main-content");
        if (sidebar.classList.contains("hide")) {
            mainContent.style.marginLeft = "0";
        } else {
            mainContent.style.marginLeft = "100px"; // Width of the sidebar
        }
    }

    overlay.addEventListener("click", function () {
        toggleSidebar();
    });

    // Add toggle functionality to navbar toggler
    var navbarToggler = document.querySelector(".navbar-toggler");
    navbarToggler.addEventListener("click", function () {
        toggleSidebar();
    });

    // Automatically hide sidebar on all screen sizes
    // sidebar.classList.add("hide");
    // overlay.classList.add("hide");
    
    // Add class to body to prevent scrolling when sidebar is open
    // document.body.classList.add("noscroll");

    // Check if screen size is larger than a certain threshold (e.g., 768px for desktop screens)
    function checkScreenSize() {
        if (window.innerWidth > 768) {
            sidebar.classList.remove("hide");
            overlay.classList.remove("hide");
        } else {
            sidebar.classList.add("hide");
            overlay.classList.add("hide");
        }
    }

    // Check screen size on initial load and whenever the window is resized
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
});
    // Function to toggle submenu
    function toggleSubMenu(element) {
        $(element).next('.sub-menu').slideToggle();
    }
</script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

</html>