<?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'] === 'getWeeklySalesExpenses') {
        // Get the current week's start and end dates
$currentWeekStart = (new DateTime('monday this week'))->format('Y-m-d');
$currentWeekEnd = (new DateTime('sunday this week'))->format('Y-m-d');

        // Initialize arrays to store daily sales and expenses data
        $dailySales = [];
        $dailyExpenses = [];

        // Get daily sales from transaction_receipts for the current week
          // Get daily sales from transaction_receipts for the current week
        $weeklyTransactionQuery = "SELECT DATE(seller_date) AS day, SUM(total) AS totalSales FROM transaction_receipts WHERE seller_date BETWEEN ? AND ? GROUP BY DATE(seller_date)";
        $weeklyTransactionStmt = $conn->prepare($weeklyTransactionQuery);
        $weeklyTransactionStmt->bind_param("ss", $currentWeekStart, $currentWeekEnd);
        $weeklyTransactionStmt->execute();
        $weeklyTransactionResult = $weeklyTransactionStmt->get_result();

        // Fetch data and populate the array for daily sales
        while ($row = mysqli_fetch_assoc($weeklyTransactionResult)) {
            $dailySales[$row['day']] = $row['totalSales'];
            $dailySales2[$row['day']] = $row['totalSales'];
        }

        // Get daily sales from swimo for the current week
        $weeklySwimoQuery = "SELECT DATE(date_column) AS day, SUM(total_cost) AS totalSales FROM swimo WHERE date_column BETWEEN ? AND ? GROUP BY DATE(date_column)";
        $weeklySwimoStmt = $conn->prepare($weeklySwimoQuery);
        $weeklySwimoStmt->bind_param("ss", $currentWeekStart, $currentWeekEnd);
        $weeklySwimoStmt->execute();
        $weeklySwimoResult = $weeklySwimoStmt->get_result();

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

        // Get daily expenses from expenses table for the current week
        $weeklyExpensesQuery = "SELECT DATE(date_incurred) AS day, SUM(expense_amount) AS totalExpenses FROM expenses WHERE date_incurred BETWEEN ? AND ? GROUP BY DATE(date_incurred)";
        $weeklyExpensesStmt = $conn->prepare($weeklyExpensesQuery);
        $weeklyExpensesStmt->bind_param("ss", $currentWeekStart, $currentWeekEnd);
        $weeklyExpensesStmt->execute();
        $weeklyExpensesResult = $weeklyExpensesStmt->get_result();

        // Fetch data and populate the array for daily expenses
        while ($row = mysqli_fetch_assoc($weeklyExpensesResult)) {
            $dailyExpenses[$row['day']] = $row['totalExpenses'];
        }

        // Get daily purchases for the current week
        $weeklyPurchasesQuery = "SELECT DATE(date) AS day, SUM(total) AS totalPurchases FROM invoice WHERE date BETWEEN ? AND ? GROUP BY DATE(date)";
        $weeklyPurchasesStmt = $conn->prepare($weeklyPurchasesQuery);
        $weeklyPurchasesStmt->bind_param("ss", $currentWeekStart, $currentWeekEnd);
        $weeklyPurchasesStmt->execute();
        $weeklyPurchasesResult = $weeklyPurchasesStmt->get_result();

        // Fetch data and update the array for daily expenses
        while ($row = mysqli_fetch_assoc($weeklyPurchasesResult)) {
            if (isset($dailyExpenses[$row['day']])) {
                $dailyExpenses[$row['day']] += $row['totalPurchases'];
            } else {
                $dailyExpenses[$row['day']] = $row['totalPurchases'];
            }
        }

        // Get daily payslip for the current week
        $weeklyPayslipQuery = "SELECT DATE(date) AS day, SUM(netPay) AS totalPayslip FROM table_payslip WHERE date BETWEEN ? AND ? GROUP BY DATE(date)";
        $weeklyPayslipStmt = $conn->prepare($weeklyPayslipQuery);
        $weeklyPayslipStmt->bind_param("ss", $currentWeekStart, $currentWeekEnd);
        $weeklyPayslipStmt->execute();
        $weeklyPayslipResult = $weeklyPayslipStmt->get_result();

        // Fetch data and update the array for daily expenses
        while ($row = mysqli_fetch_assoc($weeklyPayslipResult)) {
            if (isset($dailyExpenses[$row['day']])) {
                $dailyExpenses[$row['day']] += $row['totalPayslip'];
            } else {
                $dailyExpenses[$row['day']] = $row['totalPayslip'];
            }
        }

        // Prepare data for JSON response
         $allDays = array_merge(array_keys($dailySales), array_keys($dailyExpenses));
        $allDays = array_unique($allDays);
        foreach ($allDays as $day) {
            $dailySales[$day] = isset($dailySales[$day]) ? $dailySales[$day] : 0;
            $dailyExpenses[$day] = isset($dailyExpenses[$day]) ? $dailyExpenses[$day] : 0;
        }

        // Prepare data for JSON response
        $response = [
            'dailySales' => array_values($dailySales), // Values only without day keys
            'dailyExpenses' => array_values($dailyExpenses), // Values only without day keys
        ];

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

