<?php
require_once '../config/db.php';
header('Content-Type: application/json');

$date = trim($_GET['date'] ?? '');
$billNumber = trim($_GET['bill_number'] ?? '');

$sql = "SELECT
            b.bill_number,
            MAX(c.customer_name) AS customer_name,
            MAX(b.entered_date) AS entered_date,
            MAX(s.total_amount) AS total_amount,
            MAX(s.total_discount) AS total_discount,
            MAX(s.received_amount) AS received_amount,
            MAX(s.balance_amount) AS balance_amount,
            MAX(s.entered_user) AS entered_user
        FROM billing_data b
        LEFT JOIN selling_data s ON b.bill_number = s.bill_number
        LEFT JOIN credit_sale_data c ON b.bill_number = c.bill_number
        WHERE 1=1";
$params = [];

if ($date !== '') {
    $sql .= " AND DATE(b.entered_date) = ?";
    $params[] = $date;
}
if ($billNumber !== '') {
    $sql .= " AND b.bill_number LIKE ?";
    $params[] = "%$billNumber%";
}

$sql .= " GROUP BY b.bill_number ORDER BY MAX(b.entered_date) DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
echo json_encode($stmt->fetchAll());