<?php
session_start();
include('includes/db.php');

/* ================= Access Control ================= */
if (!isset($_SESSION['user_role'])) {
    header("Location: login.php");
    exit;
}

if ($_SESSION['user_role'] !== 'Super_admin') {
    $_SESSION['flash'] = ["message"=>"Access denied!","color"=>"#dc3545"];
    header("Location: dashboard.php");
    exit;
}

/* ================= User & Facility ================= */
$username     = $_SESSION['username'] ?? 'Super_admin';
$facilityName = $_SESSION['facility_name'] ?? 'N/A';
$facilityId   = (int)($_SESSION['facility_id'] ?? 0);

if ($facilityId <= 0) {
    $_SESSION['flash'] = ["message"=>"Facility not assigned.","color"=>"#dc3545"];
    header("Location: dashboard.php");
    exit;
}

/* ================= Date Filter ================= */
$fromDate = $_GET['from_date'] ?? date('Y-m-01');
$toDate   = $_GET['to_date']   ?? date('Y-m-t');

/* ================= Financial Summary for Assigned Facility ================= */
$stmt = $pdo->prepare("
    SELECT
        MONTH(created_at) AS month,
        SUM(patient_co_pay - amount_paid) AS patient_billed_outstanding,
        SUM(amount_paid) AS patient_paid,
        SUM(insurance_amount) AS insurance_billed,
        SUM(amount) AS total_billed
    FROM invoices
    WHERE created_at BETWEEN ? AND ?
      AND facility_id = ?
      AND is_removed = 0
    GROUP BY MONTH(created_at)
");
$stmt->execute([$fromDate.' 00:00:00',$toDate.' 23:59:59',$facilityId]);
$financialData = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= Chart Arrays ================= */
$monthLabels = [];
$patientBilledData = [];
$patientPaidData   = [];
$insuranceData     = [];
$totalBilledData   = [];

for ($m = 1; $m <= 12; $m++) {
    $monthLabels[] = date("F", mktime(0,0,0,$m,10));

    $row = null;
    foreach ($financialData as $fd) {
        if ((int)$fd['month'] === $m) {
            $row = $fd;
            break;
        }
    }

    $patientBilledData[] = (float)($row['patient_billed_outstanding'] ?? 0);
    $patientPaidData[]   = (float)($row['patient_paid'] ?? 0);
    $insuranceData[]     = (float)($row['insurance_billed'] ?? 0);
    $totalBilledData[]   = (float)($row['total_billed'] ?? 0);
}

/* ================= KPIs ================= */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE facility_id=?");
$stmt->execute([$facilityId]);
$totalUsers = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM patients WHERE facility_id=?");
$stmt->execute([$facilityId]);
$totalPatients = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM visits WHERE facility_id=? AND created_at BETWEEN ? AND ?");
$stmt->execute([$facilityId, $fromDate.' 00:00:00', $toDate.' 23:59:59']);
$totalVisits = (int)$stmt->fetchColumn();


/* ================= Financial Summary by All Facilities ================= */
$facilitySummaryStmt = $pdo->prepare("
    SELECT
        f.id,
        f.name AS facility_name,
        SUM(i.patient_co_pay - i.amount_paid) AS patient_billed_outstanding,
        SUM(i.amount_paid) AS patient_paid,
        SUM(i.insurance_amount) AS insurance_billed,
        SUM(i.amount) AS total_billed
    FROM facility f
    LEFT JOIN invoices i ON i.facility_id = f.id AND i.is_removed=0 AND i.created_at BETWEEN ? AND ?
    GROUP BY f.id, f.name
");
$facilitySummaryStmt->execute([$fromDate.' 00:00:00',$toDate.' 23:59:59']);
$facilitySummaryData = $facilitySummaryStmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= Insurance Summary by Facility (JOIN insurance_partners) ================= */
$insuranceSummaryStmt = $pdo->prepare("
    SELECT
        f.id AS facility_id,
        f.name AS facility_name,
        ip.id AS insurance_id,
        ip.name AS insurance_name,
        SUM(i.amount) AS total_billed
    FROM insurance_partners ip
    JOIN facility f ON ip.facility_id = f.id
    LEFT JOIN invoices i 
        ON i.facility_id=f.id
        AND i.is_removed=0
        AND i.insurance_amount > 0
        AND i.created_at BETWEEN ? AND ?
        AND i.payment_method=ip.name
    GROUP BY f.id, ip.id, ip.name
    ORDER BY f.name, ip.name
");
$insuranceSummaryStmt->execute([$fromDate.' 00:00:00',$toDate.' 23:59:59']);
$insuranceSummaryData = $insuranceSummaryStmt->fetchAll(PDO::FETCH_ASSOC);

include('includes/header.php');
?>

<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
<?php include('includes/navbar.php'); ?>
</nav>

<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
<?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
<div class="content-wrapper">

<h3 class="mb-3">Dashboard</h3>

<!-- ================= Financial Summary for Assigned Facility ================= -->
<div class="card mb-4">
<div class="card-header"><h4>Financial Summary </h4></div>
<div class="card-body">

<form method="get" class="form-inline mb-3">
<input type="date" name="from_date" value="<?= htmlspecialchars($fromDate) ?>" class="form-control mr-2">
<input type="date" name="to_date" value="<?= htmlspecialchars($toDate) ?>" class="form-control mr-2">
<button class="btn btn-primary">Filter</button>
</form>

<div class="row text-center">
<div class="col-md-3">
<div class="card bg-info text-white p-2">
<h6>Patient Outstanding</h6>
<h4><?= number_format(array_sum($patientBilledData)) ?> RWF</h4>
</div>
</div>

<div class="col-md-3">
<div class="card bg-success text-white p-2">
<h6>Patient Paid</h6>
<h4><?= number_format(array_sum($patientPaidData)) ?> RWF</h4>
</div>
</div>

<div class="col-md-3">
<div class="card bg-warning text-white p-2">
<h6>Insurance Billed</h6>
<h4><?= number_format(array_sum($insuranceData)) ?> RWF</h4>
</div>
</div>

<div class="col-md-3">
<div class="card bg-primary text-white p-2">
<h6>Total Billed</h6>
<h4><?= number_format(array_sum($totalBilledData)) ?> RWF</h4>
</div>
</div>
</div>

</div>
</div>

<!-- ================= Financial Summary by All Facilities ================= -->
<div class="card mb-4">
<div class="card-header"><h4>Financial Summary by Facility</h4></div>
<div class="card-body">
<div class="row">
<?php foreach ($facilitySummaryData as $f): ?>
<div class="col-md-3 mb-3">
<div class="card p-2 text-center border-primary">
<h6><?= htmlspecialchars($f['facility_name']) ?></h6>
<p>Outstanding: <strong><?= number_format($f['patient_billed_outstanding'] ?? 0) ?> RWF</strong></p>
<p>Paid: <strong><?= number_format($f['patient_paid'] ?? 0) ?> RWF</strong></p>
<p>Insurance: <strong><?= number_format($f['insurance_billed'] ?? 0) ?> RWF</strong></p>
<p>Total: <strong><?= number_format($f['total_billed'] ?? 0) ?> RWF</strong></p>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>



<!-- ================= Chart ================= -->
<div class="card mb-4">
<div class="card-header"><h4>Monthly Financial Overview</h4></div>
<div class="card-body">
<canvas id="financialChart" height="120"></canvas>
</div>
</div>

<!-- ================= Stats ================= -->
<div class="row">
<div class="col-md-4">
<div class="card text-center p-3"><h5>Total Users</h5><?= $totalUsers ?></div>
</div>
<div class="col-md-4">
<div class="card text-center p-3"><h5>Total Patients</h5><?= $totalPatients ?></div>
</div>
<div class="col-md-4">
<div class="card text-center p-3"><h5>Total Visits</h5><?= $totalVisits ?></div>
</div>

</div>

</div>
</div>

<?php include('includes/footer.php'); ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
new Chart(document.getElementById('financialChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($monthLabels) ?>,
        datasets: [
            {
                label: 'Patient Outstanding',
                data: <?= json_encode($patientBilledData) ?>,
                backgroundColor: '#17a2b8'
            },
            {
                label: 'Patient Paid',
                data: <?= json_encode($patientPaidData) ?>,
                backgroundColor: '#28a745'
            },
            {
                label: 'Insurance Billed',
                data: <?= json_encode($insuranceData) ?>,
                backgroundColor: '#ffc107'
            },
            {
                label: 'Total Billed',
                data: <?= json_encode($totalBilledData) ?>,
                backgroundColor: '#007bff'
            }
        ]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'bottom' } },
        scales: {
            y: { beginAtZero: true, ticks: { callback: v => v.toLocaleString() + ' RWF' } }
        }
    }
});
</script>
