<?php
include 'database/shikanisha.kts.php';

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

// Set Monday as the first day of the week
$set_first_day_query = "SET @@GLOBAL.sql_mode=CONCAT(@@GLOBAL.sql_mode, ',STRICT_ALL_TABLES')";
$conn->query($set_first_day_query);

// Retrieve data for each day of the week
$sql = "SELECT
    DAYNAME(DATE(cs.seller_date)) AS day,
    COALESCE(SUM(cs.total), 0) AS total_sales,
    COALESCE(SUM(cs.amount_received), 0) AS total_received,
    COALESCE(SUM(cs.total) - SUM(cs.amount_received), 0) AS total_debt,
    COALESCE(SUM(CASE WHEN t.payment_method = 'cash' THEN t.amount ELSE 0 END), 0) AS cash_total,
    COALESCE(SUM(CASE WHEN t.payment_method = 'merchant' THEN t.amount ELSE 0 END), 0) AS merchant_total,
    COALESCE(SUM(CASE WHEN t.payment_method = 'Captains Order' THEN t.amount ELSE 0 END), 0) AS captain_total,
    COALESCE(SUM(CASE WHEN t.payment_method = 'till' THEN t.amount ELSE 0 END), 0) AS till_total
FROM transaction_receipts cs
LEFT JOIN payments t ON cs.trans_id = t.trans_id
WHERE YEARWEEK(cs.seller_date) = YEARWEEK(CURDATE())
GROUP BY DAYNAME(DATE(cs.seller_date))
ORDER BY DAYOFWEEK(cs.seller_date);
";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $labels = array();
    $cash_data = array();
    $till_data = array();
    $merchant_data = array();
    $captain_data = array();
    $debt = array();

    while ($row = $result->fetch_assoc()) {
        array_push($labels, $row["day"]);
        array_push($cash_data, $row["cash_total"]);
        array_push($merchant_data, $row["merchant_total"]);
        array_push($captain_data, $row["captain_total"]);
        array_push($till_data, $row["till_total"]);
        array_push($debt, $row["total_debt"]);
    }

    $response = array(
        'labels' => $labels,
        'cash_data' => $cash_data,
        'till_data' => $till_data,
        'merchant_data' => $merchant_data,
        'captain_data' => $captain_data,
        'debt' => $debt
    );

    echo json_encode($response);
} else {
    echo "0 results";
}

$conn->close();
?>
