<?php
// Include your database connection code
require '../../database/shikanisha.kts.php';

// Get today's date
$today = date('Y-m-d');

// Query to get the sum of 'expense_amount' from 'expenses' table for today
$expenseQuery = "SELECT SUM(expense_amount) as totalExpense FROM expenses WHERE date_incurred = ?";
$expenseStmt = $conn->prepare($expenseQuery);
$expenseStmt->bind_param("s", $today);
$expenseStmt->execute();
$expenseResult = $expenseStmt->get_result();
$totalExpense = $expenseResult->fetch_assoc()['totalExpense'];

// Query to get the sum of 'netPay' from 'table_payslip' table for today
$payslipQuery = "SELECT SUM(netPay) as totalPayslip FROM table_payslip WHERE date = ?";
$payslipStmt = $conn->prepare($payslipQuery);
$payslipStmt->bind_param("s", $today);
$payslipStmt->execute();
$payslipResult = $payslipStmt->get_result();
$totalPayslip = $payslipResult->fetch_assoc()['totalPayslip'];

// Query to get the sum of 'total' from 'invoice' table for today
$invoiceQuery = "SELECT SUM(total) as totalInvoice FROM invoice WHERE date = ?";
$invoiceStmt = $conn->prepare($invoiceQuery);
$invoiceStmt->bind_param("s", $today);
$invoiceStmt->execute();
$invoiceResult = $invoiceStmt->get_result();
$totalInvoice = $invoiceResult->fetch_assoc()['totalInvoice'];

// Calculate the total of all results
$totalDailyExpense = $totalExpense + $totalPayslip + $totalInvoice;

// Close prepared statements
$expenseStmt->close();
$payslipStmt->close();
$invoiceStmt->close();

// Prepare data for the chart
// Prepare data for the chart
$dataForChart = [
    ['Expenses', $totalExpense !== null ? (int)$totalExpense : 0],
    ['Salaries', $totalPayslip !== null ? (int)$totalPayslip : 0],
    ['Purchases', $totalInvoice !== null ? (int)$totalInvoice : 0],
];


// Provide JSON response
echo json_encode(['totalDailyExpense' => $totalDailyExpense, 'dataForChart' => $dataForChart]);

// Close the database connection
$conn->close();
?>
