<?php
include('include/session.php');
// session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('include/navigation.php');
include('connection.php');
include('class.php');

// Establish database connection
$dbConnection = new DbConnection();
$connection = $dbConnection->connection;

// Get current month and year
$currentMonth = date('m');
$currentYear = date('Y');

// Function to get start and end dates for each week of the month
function getStartAndEndDateForWeek($week, $month, $year) {
    $firstDayOfMonth = date('Y-m-01', strtotime("$year-$month-01"));
    $startOfWeek = date('Y-m-d', strtotime($firstDayOfMonth . " +".(($week - 1) * 7)." days"));
    $endOfWeek = date('Y-m-d', strtotime($startOfWeek . " +6 days"));
    return array($startOfWeek, $endOfWeek);
}
?>

<html lang="en">
<head>
    <link rel="stylesheet" href="assets/css/style.css">
    <?php include('include/header_links.php'); ?>
</head>

<body>
    <div class="container_main">
         <div id="warantee_button">
                    <div> <button class="reset-button"><a href="_reports.php"><i class="fa-solid fa-backward"></i></a></button></div>
                    
                </div>
        <h1>-- Weekly Sales Reports--</h1>
        <div class="sales_report">
<div class="weekly_sales">
    <?php 
    // Loop through each week of the month
    for ($week = 1; $week <= 5; $week++) {
        // Get start and end dates for the week
        list($startOfWeek, $endOfWeek) = getStartAndEndDateForWeek($week, $currentMonth, $currentYear);
        
        // Query to get total sales for the week
        $weeklySalesQuery = "SELECT SUM(SUBSTRING(total_price, 3)) as total_sales 
                             FROM order_summery
                             WHERE DATE(created_on) BETWEEN '$startOfWeek' AND '$endOfWeek'";
        // Execute query
        $result = mysqli_query($connection, $weeklySalesQuery);
        // Check for errors
        if (!$result) {
            die('Error: ' . mysqli_error($connection));
        }
        // Fetch total sales
        $row = mysqli_fetch_assoc($result);
        $totalSales = $row['total_sales'];
       
        // Generate href based on week number
        $weekPage = "week_" . $week . ".php";
    ?>
    <div class="week">
        <a href="<?php echo $weekPage; ?>" class="btn btn-<?php echo ($week == 1 ? "primary" : ($week == 2 ? "secondary" : ($week == 3 ? "success" : ($week == 4 ? "danger" : "warning")))); ?>">WEEK <?php echo $week; ?></a>
        <!-- Display total sales -->
        <input type="text" placeholder="Total Sales" value="Rs <?php echo $totalSales; ?>">
    </div>
    <?php } ?>
</div>        
        </div>
    </div>
     <section class="footer">
     <?php include('include/footer_two.php');         ?>
     
 </section>
</body>
<?php include("include/footer_link.php"); ?>
<script src="assets/script/script.js"></script>
</html>
?>