<?php
include_once 'shikanisha.kts.php';

// Query to fetch sales data
$sql = "SELECT 
    seller_name,
    SUM(amount_received) AS amount_collected,
    SUM(total) AS total_sales,
    SUM(total) - SUM(amount_received) AS debt
FROM 
    transaction_receipts
GROUP BY 
    seller_name";

$result = mysqli_query($conn, $sql);

$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    $statusBadge = '';
    if ($row['amount_collected'] == $row['total_sales']) {
        $statusBadge = '<span class="badge badge-success">Paid</span>';
    } elseif ($row['amount_collected'] < $row['total_sales']) {
        $statusBadge = '<span class="badge badge-warning">Pending</span>';
    } elseif ($row['amount_collected'] > $row['total_sales']) {
        $statusBadge = '<span class="badge badge-danger">Overpayment</span>';
    }

    $data[] = [
        'seller_name' => $row['seller_name'],
        'total_sales' => $row['total_sales'],
        'amount_collected' => $row['amount_collected'],
        'debt' => $row['debt'],
        'status' => $statusBadge, // This will be raw HTML for the badge
    ];
}

// Return the data as JSON
header('Content-Type: application/json');
echo json_encode(['data' => $data]);
?>
