<?php
// Your database connection code
require '../../database/shikanisha.kts.php';

// Check if the request method is GET
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Check if the action parameter is set
    if (isset($_GET['action']) && $_GET['action'] === 'getWeekSum') {
        // Get the current month
        $currentMonth = date('m');

        // Get the start and end dates for the current month
        $currentMonthStart = (new DateTime('first day of this month'))->format('Y-m-d');
        $currentMonthEnd = (new DateTime('last day of this month'))->format('Y-m-d');

        // Initialize arrays to store daily sales and expenses data
        $monthlySalesTransactionReceipts = [];
        $monthlySalesSwimo = [];

        // Get daily sales from transaction_receipts for the current month
        $monthlyTransactionQuery = "SELECT DATE(seller_date) AS day, SUM(total) AS totalSales FROM transaction_receipts WHERE seller_date BETWEEN ? AND ? GROUP BY DATE(seller_date)";
        $monthlyTransactionStmt = $conn->prepare($monthlyTransactionQuery);
        $monthlyTransactionStmt->bind_param("ss", $currentMonthStart, $currentMonthEnd);
        $monthlyTransactionStmt->execute();
        $monthlyTransactionResult = $monthlyTransactionStmt->get_result();

        // Fetch data and populate the array for monthly sales (transaction_receipts)
        while ($row = mysqli_fetch_assoc($monthlyTransactionResult)) {
            $monthlySalesTransactionReceipts[$row['day']] = $row['totalSales'];
        }

        // Get daily sales from swimo for the current month
        $monthlySwimoQuery = "SELECT DATE(date_column) AS day, SUM(total_cost) AS totalSales FROM swimo WHERE date_column BETWEEN ? AND ? GROUP BY DATE(date_column)";
        $monthlySwimoStmt = $conn->prepare($monthlySwimoQuery);
        $monthlySwimoStmt->bind_param("ss", $currentMonthStart, $currentMonthEnd);
        $monthlySwimoStmt->execute();
        $monthlySwimoResult = $monthlySwimoStmt->get_result();

        // Fetch data and populate the array for monthly sales (swimo)
        while ($row = mysqli_fetch_assoc($monthlySwimoResult)) {
            $monthlySalesSwimo[$row['day']] = $row['totalSales'];
        }

        // Calculate the sum of sales for each week for transaction_receipts
        $weeklySalesTransactionReceipts = calculateWeeklySum($monthlySalesTransactionReceipts);

        // Calculate the sum of sales for each week for swimo
        $weeklySalesSwimo = calculateWeeklySum($monthlySalesSwimo);

        // Calculate the total sales for each week (sum of swimo + sum of transaction_receipts)
        $weeklyTotalSales = [];
        foreach ($weeklySalesTransactionReceipts as $weekNumber => $sales) {
            if (isset($weeklySalesSwimo[$weekNumber])) {
                $weeklyTotalSales[$weekNumber] = $sales + $weeklySalesSwimo[$weekNumber];
            } else {
                $weeklyTotalSales[$weekNumber] = $sales;
            }
        }

        // Prepare data for JSON response
        $response = [
            'monthlySalesTransactionReceipts' => array_values($monthlySalesTransactionReceipts), // Values only without day keys
            'monthlySalesSwimo' => array_values($monthlySalesSwimo), // Values only without day keys
            'weeklySalesTransactionReceipts' => $weeklySalesTransactionReceipts, // Weekly sales sum for transaction_receipts
            'weeklySalesSwimo' => $weeklySalesSwimo, // Weekly sales sum for swimo
            'weeklyTotalSales' => $weeklyTotalSales, // Weekly total sales (sum of swimo + sum of transaction_receipts)
        ];

        // Send JSON response
        header('Content-Type: application/json');
        echo json_encode($response);
    } else {
        // Invalid action parameter
        header('HTTP/1.1 400 Bad Request');
        echo json_encode(['error' => 'Invalid action parameter']);
    }
} else {
    // Invalid request method
    header('HTTP/1.1 405 Method Not Allowed');
    echo json_encode(['error' => 'Invalid request method']);
}

// Close database connection
mysqli_close($conn);

// Function to calculate the sum of sales for each week
function calculateWeeklySum($monthlySales)
{
    $weeklySales = [];
    foreach ($monthlySales as $day => $sales) {
        $weekNumber = date('W', strtotime($day));
        if (!isset($weeklySales[$weekNumber])) {
            $weeklySales[$weekNumber] = 0;
        }
        $weeklySales[$weekNumber] += $sales;
    }
    return $weeklySales;
}
?>
