<?php
/* ================= ERROR REPORTING ================= */
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

/* ================= SESSION START ================= */
session_start();

/* ================= SESSION TIMEOUT (12 HOURS) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $SESSION_TIMEOUT) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time();

/* ================= DATABASE ================= */
require_once 'includes/db.php';

/* ================= SAFETY CHECK: PDO ================= */
if (!isset($pdo)) {
    die("Fatal error: Database connection not available.");
}

/* ================= ACCESS CONTROL ================= */
if (
    !isset($_SESSION['user_role']) ||
    $_SESSION['user_role'] !== 'Admin'
) {
    $_SESSION['flash'] = [
        "message" => "Access denied. Admin login required.",
        "color"   => "#dc3545"
    ];
    header("Location: login.php?unauthorized=1");
    exit;
}

/* ================= USER & FACILITY ================= */
$username     = $_SESSION['username'] ?? 'Admin';
$facilityName = $_SESSION['facility_name'] ?? 'N/A';
$facilityId   = isset($_SESSION['facility_id']) ? (int)$_SESSION['facility_id'] : 0;

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

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

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

/* ================= CHART DATA ================= */
$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 ================= */
// Total Users
$totalUsersStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE facility_id = ?");
$totalUsersStmt->execute([$facilityId]);
$totalUsers = (int)$totalUsersStmt->fetchColumn();

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

// Total Visits
$totalVisitsStmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM visits v
    INNER JOIN patients p ON p.id = v.patient_id
    WHERE v.facility_id = ?
      AND v.created_at BETWEEN ? AND ?
");
$totalVisitsStmt->execute([
    $facilityId,
    $fromDate . ' 00:00:00',
    $toDate   . ' 23:59:59'
]);
$totalVisits = (int)$totalVisitsStmt->fetchColumn();

/* ================= INSURANCE SUMMARY ================= */
$insuranceSummaryStmt = $pdo->prepare("
    SELECT
        ip.id AS insurance_id,
        ip.name AS insurance_name,
        SUM(COALESCE(i.insurance_amount,0)) AS total_billed
    FROM insurance_partners ip
    LEFT JOIN visits v
        ON v.insurance_id = ip.id
       AND v.facility_id = ?
       AND v.created_at BETWEEN ? AND ?
    LEFT JOIN invoices i
        ON i.visit_id = v.id
       AND i.is_removed = 0
    WHERE ip.facility_id = ?
    GROUP BY ip.id, ip.name
    ORDER BY ip.name
");
$insuranceSummaryStmt->execute([
    $facilityId,
    $fromDate . ' 00:00:00',
    $toDate   . ' 23:59:59',
    $facilityId
]);
$insuranceSummaryData = $insuranceSummaryStmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= HEADER ================= */
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 ================= -->
<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>Outstanding Amount</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>Paid Amount</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>

<!-- ================= 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>
<!-- ================= 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>




</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>
