<?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'] === 'getLastSevenMonthsProfit') {
        // Initialize an array to store monthly profits and month names
        $monthlyProfits = [];
        $monthNames = [];

        // Loop through the last seven months
        for ($i = 6; $i >= 0; $i--) {
            // Calculate the start and end dates for the current month
            $currentMonthStart = (new DateTime("first day of -$i months"))->format('Y-m-d');
            $currentMonthEnd = (new DateTime("last day of -$i months"))->format('Y-m-d');

            // Get the month name
            $monthName = (new DateTime("first day of -$i months"))->format('M');
            $monthNames[] = $monthName;

            // Initialize arrays for monthly sales, expenses, and payslip expenses
            $monthlySales = [];
            $monthlyExpenses = [];
            $monthlyPayslipExpenses = [];

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

            // Populate the array for monthly sales
            while ($row = mysqli_fetch_assoc($monthlySalesResult)) {
                $monthlySales[$row['day']] = $row['totalSales'];
            }

            // Fetch 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();

            // 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'];
                }
            }

            // Fetch 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();

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

            // Fetch daily expenses from payslip_expenses table for the current month
            $monthlyPayslipExpensesQuery = "SELECT DATE(date) AS day, SUM(netPay) AS totalPayslip FROM table_payslip WHERE date BETWEEN ? AND ? GROUP BY DATE(date)";
            $monthlyPayslipExpensesStmt = $conn->prepare($monthlyPayslipExpensesQuery);
            $monthlyPayslipExpensesStmt->bind_param("ss", $currentMonthStart, $currentMonthEnd);
            $monthlyPayslipExpensesStmt->execute();
            $monthlyPayslipExpensesResult = $monthlyPayslipExpensesStmt->get_result();

            // Update the array for monthly payslip expenses
            while ($row = mysqli_fetch_assoc($monthlyPayslipExpensesResult)) {
                if (isset($monthlyExpenses[$row['day']])) {
                    $monthlyExpenses[$row['day']] += $row['totalPayslip'];
                } else {
                    $monthlyExpenses[$row['day']] = $row['totalPayslip'];
                }
            }

            // Fetch 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();

            // 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'];
                }
            }

            // Calculate the daily profits for the current month
            $dailyProfits = [];
            foreach ($monthlySales as $day => $sales) {
                $expenses = isset($monthlyExpenses[$day]) ? $monthlyExpenses[$day] : 0;
                $dailyProfit = $sales - $expenses;
                $dailyProfits[$day] = $dailyProfit;
            }

            // Calculate the total profit for the current month
            $totalProfit = array_sum($dailyProfits);

            // Store the total profit in the array for the current month
            $monthlyProfits[$monthName] = $totalProfit;
        }

        // Calculate the percentage profit change between the current month and the previous month
        $percentageChange = 0;
        if (isset($monthlyProfits[0]) && isset($monthlyProfits[1]) && $monthlyProfits[1] != 0) {
            $percentageChange = ($monthlyProfits[0] - $monthlyProfits[1]) / $monthlyProfits[1] * 100;
        }

        // Prepare data for JSON response
        $response = [
            'monthNames' => $monthNames,
            'monthlyProfits' => $monthlyProfits,
            'percentageChange' => $percentageChange,
        ];

        // Send the response as JSON
        header('Content-Type: application/json');
        echo json_encode($response);
    } else {
        // Invalid action parameter
        $response = [
            'success' => false,
            'error' => 'Invalid action parameter',
        ];

        // Send the response as JSON
        header('Content-Type: application/json');
        echo json_encode($response);
    }
} else {
    // Invalid request method
    $response = [
        'success' => false,
        'error' => 'Invalid request method',
    ];

    // Send the response as JSON
    header('Content-Type: application/json');
    echo json_encode($response);
}
?>
