<?php
// Include your database connection code here (e.g., dbconn.php)
require_once 'includes/dbconn.php';

// Get the selected month and year from the AJAX request
$selectedMonth = $_POST['month'];
$selectedYear = $_POST['year'];

// Debugging: Log the received data
error_log('Received data - Month: ' . $selectedMonth . ', Year: ' . $selectedYear);

// Fetch data for the selected month and year
$monthlyData = array();

for ($month = 1; $month <= 12; $month++) {
    $totalInvoices = 0;
    $totalExpenses = 0;

    // Calculate total expenses for the month
    $sqlExpenses = "SELECT COALESCE(SUM(amount), 0) AS total_expenses FROM expenses WHERE MONTH(expense_date) = '$month' AND YEAR(expense_date) = '$selectedYear'";
    $resultExpenses = $conn->query($sqlExpenses);
    $rowExpenses = $resultExpenses->fetch_assoc();
    $totalExpenses = $rowExpenses['total_expenses'];

    // Calculate total revenue from invoices for the month
    $sqlInvoices = "SELECT COALESCE(SUM(total_amount), 0) AS total_invoices FROM invoices WHERE MONTH(due_date) = '$month' AND YEAR(due_date) = '$selectedYear' AND payment_status = 'Paid'";
    $resultInvoices = $conn->query($sqlInvoices);
    $rowInvoices = $resultInvoices->fetch_assoc();
    $totalInvoices = $rowInvoices['total_invoices'];

    // Calculate net income
    $netIncome = $totalInvoices - $totalExpenses;

    // Add data to the monthly array
    $monthlyData[] = array(
        'month' => date("F", mktime(0, 0, 0, $month, 1)),
        'totalInvoices' => $totalInvoices,
        'totalExpenses' => $totalExpenses,
        'netIncome' => $netIncome
    );
}

// Prepare the data in JSON format
$data = array(
    'monthlyData' => $monthlyData
);

// Output JSON response
header('Content-Type: application/json');
echo json_encode($data);
$conn->close();
?>
