<?php
session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200; // 12 hours in seconds

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

// Update last activity time
$_SESSION['LAST_ACTIVITY'] = time();

include('includes/db.php');

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

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

/* ================= User & Facility ================= */
$username     = $_SESSION['username'] ?? 'Receptionist';
$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: reception_dashboard.php");
    exit;
}

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

/* ================= Financial Summary by Day ================= */
$stmt = $pdo->prepare("
    SELECT 
        DATE(created_at) AS day,
        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 facility_id = ? 
      AND is_removed=0 
      AND created_at BETWEEN ? AND ?
    GROUP BY DATE(created_at)
    ORDER BY DATE(created_at)
");
$stmt->execute([$facilityId, $fromDate.' 00:00:00', $toDate.' 23:59:59']);
$financialData = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

foreach ($financialData as $fd) {
    $dayLabels[] = date("d M", strtotime($fd['day']));
    $patientBilledData[] = (float)$fd['patient_billed_outstanding'];
    $patientPaidData[]   = (float)$fd['patient_paid'];
    $insuranceData[]     = (float)$fd['insurance_billed'];
    $totalBilledData[]   = (float)$fd['total_billed'];
}

/* ================= 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();

/* ================= Insurance Summary ================= */
$insuranceSummaryStmt = $pdo->prepare("
    SELECT
        ip.id AS insurance_id,
        ip.name AS insurance_name,
        SUM(i.amount) AS total_billed
    FROM insurance_partners ip
    LEFT JOIN invoices i 
        ON i.facility_id=? 
        AND i.is_removed=0 
        AND i.insurance_amount > 0 
        AND i.created_at BETWEEN ? AND ? 
        AND i.payment_method=ip.name
    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);

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>

<!-- ================= Filter ================= -->
<div class="card mb-4">
<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>
</div>

<!-- ================= Financial Summary Cards ================= -->
<div class="row text-center mb-4">
<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>

<!-- ================= Stats ================= -->
<div class="row mb-4">
<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>Daily 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($dayLabels) ?>,
        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>
