<?php
// Include your database connection code here, and ensure $conn is defined.
include_once 'shikanisha.kts.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $response = array();

    // Get start and end dates from the form submission
    $start = isset($_POST['startz']) ? $_POST['startz'] : null;
    $end = isset($_POST['endz']) ? $_POST['endz'] : null;

    if ($start && $end) {
        // Execute the SQL query for the specified date range
        $sql = "SELECT p.payment_method, SUM(p.amount) AS tills
                FROM payments AS p
                JOIN transaction_receipts AS tr ON p.trans_id = tr.trans_id
                WHERE tr.seller_date BETWEEN '$start' AND '$end' 
                GROUP BY p.payment_method;";
        $result = mysqli_query($conn, $sql);

        if ($result) {
            $response['success'] = true;
            $reportData = '';
            $monthlyTotal = 0;

            while ($row = mysqli_fetch_assoc($result)) {
                $reportData .= '<tr>
                    <td>' . $row['payment_method'] . '</td>
                    <td>' . $row['tills'] . '</td>
                </tr>';
                $monthlyTotal += $row['tills'];
            }

            $response['reportData'] = $reportData;
            $response['monthlyTotal'] = $monthlyTotal;
        } else {
            $response['success'] = false;
            $response['message'] = 'Error executing the SQL query.';
        }
    } else {
        $response['success'] = false;
        $response['message'] = 'Invalid start or end date.';
    }

    // Return the response as JSON
    header('Content-type: application/json');
    echo json_encode($response);
} else {
    // Handle non-POST requests
    // You may return an error response or redirect to another page
}
?>