<?php
// Handle form data
$start_date = $_POST['start_date'];
$end_date = $_POST['end_date'];

// Your database connection and query
include_once 'shikanisha.kts.php';

// Prepare and bind parameters
$stmt = $conn->prepare("SELECT expense_name, SUM(expense_amount) AS total_amount
                        FROM expenses 
                        WHERE date_incurred BETWEEN ? AND ? 
                        GROUP BY expense_name
                        ORDER BY expense_name");

// Bind parameters
$stmt->bind_param("ss", $start_date, $end_date);

// Execute the query
$stmt->execute();
$result = $stmt->get_result();

// Fetch expenses data
$expenses = [];
while ($row = $result->fetch_assoc()) {
    $expenses[] = $row;
}

// Calculate total expense amount
$totalExpenseAmount = 0;
foreach ($expenses as $expense) {
    $totalExpenseAmount += $expense['total_amount'];
}

// Return data as JSON
$response = [
    'status' => 'success',
    'expenses' => $expenses,
    'totalExpenseAmount' => $totalExpenseAmount
];
echo json_encode($response);

// Close statement and database connection
$stmt->close();
$conn->close();
?>
