<?php
session_start();
include '../layouts/dbconn.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$visitId = $_POST['visit_id'] ?? 0;

$sql = "SELECT 
            v.invoice_number,
            CONCAT(p.first_name, ' ', p.last_name) as patient_name,
            v.total_amount,
            COALESCE(SUM(pay.amount), 0) as paid_amount,
            (v.total_amount - COALESCE(SUM(pay.amount), 0)) as balance
        FROM visits v
        INNER JOIN patients p ON v.patient_id = p.id
        LEFT JOIN payments pay ON v.id = pay.visit_id AND pay.status = 'COMPLETED'
        WHERE v.id = ?
        GROUP BY v.id";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $visitId);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    echo json_encode([
        'success' => true,
        'data' => $row
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invoice not found'
    ]);
}
?>