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

/* -------- Access Control -------- */
if (!isset($_SESSION['user_role'])) {
    $_SESSION['flash'] = [
        "message" => "Please log in first!",
        "color" => "#dc3545"
    ];
    header("Location: login.php");
    exit;
}

/* -------- Facility Filter -------- */
$facility_id = $_SESSION['facility_id'] ?? null;
$facility_name = $_SESSION['user_facility_name'] ?? 'Unknown';

if (!$facility_id) {
    $_SESSION['flash'] = [
        "message" => "No facility assigned to your account.",
        "color" => "#dc3545"
    ];
    header("Location: dashboard.php");
    exit;
}

/* -------- Date Filter -------- */
$start_date = $_GET['start_date'] ?? date('Y-m-d');
$end_date   = $_GET['end_date'] ?? date('Y-m-d');

/* -------- Fetch Staff Performance Data -------- */
$sql = "
SELECT 
    d.id AS department_id,
    d.name AS department_name,
    u.id AS staff_id,
    u.username AS staff_name,
    u.user_role,

    /* Total patients handled by staff in this facility */
    (
        SELECT COUNT(DISTINCT v.patient_id)
        FROM visits v
        WHERE v.created_by = u.id
          AND DATE(v.visit_date) BETWEEN ? AND ?
          AND v.facility_id = ?
    ) +
    (
        SELECT COUNT(DISTINCT vt.patient_id)
        FROM visit_tickets vt
        WHERE vt.created_by = u.id
          AND DATE(vt.created_at) BETWEEN ? AND ?
          AND vt.facility_id = ?
    ) AS total_patients,

    /* Total invoice amounts by this staff in this facility */
    (
        SELECT COALESCE(SUM(inv.patient_co_pay + inv.insurance_amount),0)
        FROM invoices inv
        WHERE inv.created_by = u.id
          AND DATE(inv.created_at) BETWEEN ? AND ?
          AND inv.facility_id = ?
    ) AS total_amount_charged

FROM departments d
LEFT JOIN users u 
    ON u.department_id = d.id AND u.facility_id = ?
WHERE u.id IS NOT NULL
ORDER BY d.name ASC, u.username ASC
";

$params = [
    $start_date, $end_date, $facility_id,
    $start_date, $end_date, $facility_id,
    $start_date, $end_date, $facility_id,
    $facility_id
];

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* -------- Group by Department -------- */
$departments = [];
foreach ($rows as $r) {
    $dept = $r['department_name'] ?? 'Unassigned';
    $departments[$dept][] = $r;
}
?>

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

<div class="content-header row mb-3">
<div class="col-md-12">
    <h3>Staff Performance Report - Facility: <?= htmlspecialchars($facility_name) ?></h3>

    <form method="get" class="form-inline mt-2">
        <label class="mr-2">Start Date</label>
        <input type="date" name="start_date" class="form-control mr-2"
               value="<?= htmlspecialchars($start_date) ?>">

        <label class="mr-2">End Date</label>
        <input type="date" name="end_date" class="form-control mr-2"
               value="<?= htmlspecialchars($end_date) ?>">

        <button class="btn btn-primary">Filter</button>
    </form>
</div>
</div>

<div class="content-body">

<?php foreach ($departments as $deptName => $staffList): ?>
<div class="card mb-3">
<div class="card-header bg-light font-weight-bold">
    <?= htmlspecialchars($deptName) ?>
</div>

<div class="card-body table-responsive">
<table class="table table-bordered table-striped deptTable">
<thead>
<tr>
    <th>Staff</th>
    <th>Role</th>
    <th>Total Patients</th>
    <th>Total Amount Charged</th>
</tr>
</thead>

<tbody>
<?php 
$dept_total_amount = 0;
$dept_total_patients = 0;
foreach ($staffList as $s): 
    $dept_total_amount += $s['total_amount_charged'];
    $dept_total_patients += $s['total_patients'];
?>
<tr>
    <td><?= htmlspecialchars($s['staff_name'] ?? '-') ?></td>
    <td><?= htmlspecialchars($s['user_role'] ?? '-') ?></td>
    <td class="text-center"><?= (int)$s['total_patients'] ?></td>
    <td class="text-right"><?= number_format($s['total_amount_charged'], 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>

<tfoot>
<tr class="bg-light font-weight-bold">
    <td colspan="2">Department Total</td>
    <td class="text-center"><?= (int)$dept_total_patients ?></td>
    <td class="text-right"><?= number_format($dept_total_amount, 2) ?></td>
</tr>
</tfoot>
</table>
</div>
</div>
<?php endforeach; ?>

</div>
</div>
</div>

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

<!-- DataTables & Buttons -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">

<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
$('.deptTable').DataTable({
    paging: true,
    searching: true,
    ordering: true,
    info: true,
    pageLength: 10,
    dom: 'Bfrtip',
    buttons: [
        { extend: 'excel', className: 'btn btn-secondary btn-sm mr-1' },
        { extend: 'csv',   className: 'btn btn-secondary btn-sm mr-1' },
        { extend: 'pdf',   className: 'btn btn-secondary btn-sm mr-1' },
        { extend: 'print', className: 'btn btn-secondary btn-sm' }
    ],
    language: {
        paginate: {
            first:    '<button class="btn btn-outline-primary btn-sm">First</button>',
            previous: '<button class="btn btn-outline-primary btn-sm">&laquo;</button>',
            next:     '<button class="btn btn-outline-primary btn-sm">&raquo;</button>',
            last:     '<button class="btn btn-outline-primary btn-sm">Last</button>'
        }
    }
});
</script>
