<?php
// Database connection string
require '../../database/shikanisha.kts.php';

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get the current week start and end dates
$currentWeekStart = date('Y-m-d', strtotime('monday this week'));
$currentWeekEnd = date('Y-m-d', strtotime('sunday this week'));

// SQL query to get the sum of amounts paid grouped by payment methods for the current week
$sql1 = "SELECT p.payment_method, SUM(p.amount) AS total_amount
FROM payments AS p
JOIN transaction_receipts AS tr ON p.trans_id = tr.trans_id
WHERE tr.seller_date BETWEEN '$currentWeekStart' AND '$currentWeekEnd'
GROUP BY p.payment_method";

$result1 = $conn->query($sql1);

// SQL query to get data from the `room_payments` table
$sql2 = "SELECT `paid_amount`, `pay_method` AS payment_method, `date` FROM `room_payments` WHERE date BETWEEN '$currentWeekStart' AND '$currentWeekEnd'
GROUP BY pay_method";  // Fix the GROUP BY clause

$result2 = $conn->query($sql2);

// Initialize an array to store the combined data
$combinedData = [];

if ($result1->num_rows > 0) {
    // Fetch results from the first query as an associative array
    $data1 = $result1->fetch_all(MYSQLI_ASSOC);

    // Filter out unwanted payment methods
    $filteredData1 = array_filter($data1, function ($row) {
        $allowedMethods = ['cash', 'merchant', 'till'];
        return in_array($row['payment_method'], $allowedMethods);
    });

    // Merge the filtered data from the first query into the combined data array
    $combinedData = array_merge($combinedData, $filteredData1);
}

if ($result2->num_rows > 0) {
    // Fetch results from the second query as an associative array
    $data2 = $result2->fetch_all(MYSQLI_ASSOC);

    // Merge the data from the second query into the combined data array
    $combinedData = array_merge($combinedData, $data2);
}

// Calculate total amounts for each payment method
$totals = array();

foreach ($combinedData as $entry) {
    $paymentMethod = $entry['payment_method'];
    $amount = isset($entry['total_amount']) ? $entry['total_amount'] : $entry['paid_amount'];

    if (!isset($totals[$paymentMethod])) {
        $totals[$paymentMethod] = 0;
    }

    $totals[$paymentMethod] += floatval($amount);
}

// Format the totals array to match the structure of the combined data
$totalsArray = array_map(function ($paymentMethod, $totalAmount) {
    return array('payment_method' => $paymentMethod, 'total_amount' => number_format($totalAmount, 2));
}, array_keys($totals), $totals);

// Re-index the array to have consecutive numeric keys
$combinedData = array_values($totalsArray);

echo json_encode($combinedData);

$conn->close();
?>
