<?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) {
        // Convert datetime format to date-only format for SQL comparison
        $startDate = date('Y-m-d', strtotime($start));
        $endDate = date('Y-m-d', strtotime($end));
        
        // Execute the SQL query for the specified date range
        $sql = "SELECT p.payment_method, SUM(p.amount) AS tills
                FROM payments AS p
               LEFT JOIN transaction_receipts AS tr ON p.trans_id = tr.trans_id
                WHERE DATE(tr.seller_date) BETWEEN '$startDate' AND '$endDate' 
                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>' . htmlspecialchars($row['payment_method']) . '</td>
                    <td>' . number_format($row['tills'], 2) . '</td>
                </tr>';
                $monthlyTotal += $row['tills'];
            }

            $response['reportData'] = $reportData;
            $response['monthlyTotal'] = number_format($monthlyTotal, 2);
        } else {
            $response['success'] = false;
            $response['message'] = 'Error executing the SQL query: ' . mysqli_error($conn);
        }
    } 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
    $response = array(
        'success' => false,
        'message' => 'Invalid request method.'
    );
    header('Content-type: application/json');
    echo json_encode($response);
}
?>