<?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'] === 'getMonthlyData') {
        // 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
        $monthlySales = [];
        $monthlyExpenses = [];

        // 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
        while ($row = mysqli_fetch_assoc($monthlyTransactionResult)) {
            $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", $currentMonthStart, $currentMonthEnd);
        $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'];
            }
        }

        // Get daily expenses from expenses table for the current month
        $monthlyExpensesQuery = "SELECT DATE(date_incurred) AS day, SUM(expense_amount) AS totalExpenses FROM expenses WHERE date_incurred BETWEEN ? AND ? GROUP BY DATE(date_incurred)";
        $monthlyExpensesStmt = $conn->prepare($monthlyExpensesQuery);
        $monthlyExpensesStmt->bind_param("ss", $currentMonthStart, $currentMonthEnd);
        $monthlyExpensesStmt->execute();
        $monthlyExpensesResult = $monthlyExpensesStmt->get_result();

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

        // Get daily purchases for the current month
        $monthlyPurchasesQuery = "SELECT DATE(date) AS day, SUM(total) AS totalPurchases FROM invoice WHERE date BETWEEN ? AND ? GROUP BY DATE(date)";
        $monthlyPurchasesStmt = $conn->prepare($monthlyPurchasesQuery);
        $monthlyPurchasesStmt->bind_param("ss", $currentMonthStart, $currentMonthEnd);
        $monthlyPurchasesStmt->execute();
        $monthlyPurchasesResult = $monthlyPurchasesStmt->get_result();

        // Fetch data and update the array for monthly expenses
        while ($row = mysqli_fetch_assoc($monthlyPurchasesResult)) {
            if (isset($monthlyExpenses[$row['day']])) {
                $monthlyExpenses[$row['day']] += $row['totalPurchases'];
            } else {
                $monthlyExpenses[$row['day']] = $row['totalPurchases'];
            }
        }
      
       
          $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", $currentMonthStart, $currentMonthEnd);
        $weeklyPayslipStmt->execute();
        $weeklyPayslipResult = $weeklyPayslipStmt->get_result();

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


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

        // Calculate the monthly profit
        $monthlyProfit = array_map(function ($day) use ($monthlySales, $monthlyExpenses) {
            return $monthlySales[$day] - $monthlyExpenses[$day];
        }, $allDays);

        // Calculate the sum of monthlySales and monthlyExpenses
        $sumMonthlySales = array_sum($monthlySales);
        $sumMonthlyExpenses = array_sum($monthlyExpenses);

// Calculate the monthly profit
$monthlyProfit = $sumMonthlySales - $sumMonthlyExpenses;

// Prepare data for JSON response
$response = [
    'monthlySales' => $sumMonthlySales, // Sum of monthly sales
    'monthlyExpenses' => $sumMonthlyExpenses, // Sum of monthly expenses
    'monthlyProfit' => $monthlyProfit, // Monthly profit
];



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