<?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'] === 'get18Data') {
        // 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');

        // Calculate the start date for the last 18 days
        $last18DaysStart = (new DateTime('-18 days'))->format('Y-m-d');

        // Calculate the date for yesterday
        $yesterday = (new DateTime('-1 day'))->format('Y-m-d');

        // Calculate the date for the day before yesterday
        $dayBeforeYesterday = (new DateTime('-2 days'))->format('Y-m-d');

        // Initialize arrays to store daily sales and expenses data
        $monthlySales = [];
        $yesterdaySales = 0;
        $dayBeforeYesterdaySales = 0;

        // 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", $last18DaysStart, $currentMonthEnd); // Use $last18DaysStart as the start date
        $monthlyTransactionStmt->execute();
        $monthlyTransactionResult = $monthlyTransactionStmt->get_result();

        // Fetch data and populate the array for monthly sales
        while ($row = mysqli_fetch_assoc($monthlyTransactionResult)) {
            if ($row['day'] == $yesterday) {
                $yesterdaySales = $row['totalSales'];
            } elseif ($row['day'] == $dayBeforeYesterday) {
                $dayBeforeYesterdaySales = $row['totalSales'];
            }
            $monthlySales[$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", $last18DaysStart, $currentMonthEnd); // Use $last18DaysStart as the start date
        $monthlySwimoStmt->execute();
        $monthlySwimoResult = $monthlySwimoStmt->get_result();

        // Fetch data and update the array for monthly sales
        while ($row = mysqli_fetch_assoc($monthlySwimoResult)) {
            if (isset($monthlySales[$row['day']])) {
                $monthlySales[$row['day']] += $row['totalSales'];
            } else {
                $monthlySales[$row['day']] = $row['totalSales'];
            }
        }

        // Calculate the sum of sales for the last 18 days
        $sumMonthlySales = array_sum($monthlySales);

        // Calculate the percentage change between yesterday and the day before yesterday
        $percentageChange = 0;
        if ($dayBeforeYesterdaySales != 0) {
            $percentageChange = (($yesterdaySales - $dayBeforeYesterdaySales) / $dayBeforeYesterdaySales) * 100;
        }

        // Prepare data for JSON response
        $response = [
            'monthlySales' => array_values($monthlySales), // Values only without day keys
            'sumMonthlySales' => $sumMonthlySales, // Sum of sales for the last 18 days
            'percentageChange' => $percentageChange, // Percentage change between yesterday and the day before yesterday
        ];

        // 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);
?>
