<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

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

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

include('includes/db.php');


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

$username    = $_SESSION['username'] ?? 'User';
$facility    = $_SESSION['user_facility_name'] ?? 'N/A';
$facility_id = $_SESSION['facility_id'] ?? null;

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

// ---------------- Date Filters ----------------
$fromDate = $_GET['from_date'] ?? date('Y-m-01'); // default: start of current month
$toDate   = $_GET['to_date'] ?? date('Y-m-t');    // default: end of current month

// ---------------- Summary Cards ----------------
$summaryQuery = $pdo->prepare("
    SELECT 
        COUNT(DISTINCT v.patient_id) AS total_patients,
        SUM(inv.patient_co_pay) AS total_patient_copay,
        SUM(inv.insurance_amount) AS total_insurance,
        SUM(inv.patient_co_pay + inv.insurance_amount) AS total_combined
    FROM visits v
    LEFT JOIN invoices inv ON v.id = inv.visit_id
    WHERE DATE(v.visit_date) BETWEEN ? AND ? AND v.facility_id = ?
");
$summaryQuery->execute([$fromDate, $toDate, $facility_id]);
$summary = $summaryQuery->fetch(PDO::FETCH_ASSOC);

// ---------------- Daily Insurance Report ----------------
$dailyInsuranceReport = $pdo->prepare("
    SELECT 
        DATE(v.visit_date) AS day,
        i.name AS insurance_name,
        COUNT(DISTINCT v.patient_id) AS patient_count,
        SUM(inv.patient_co_pay) AS patient_copay,
        SUM(inv.insurance_amount) AS insurance_amount,
        SUM(inv.patient_co_pay + inv.insurance_amount) AS total_amount
    FROM visits v
    LEFT JOIN invoices inv ON v.id = inv.visit_id
    LEFT JOIN insurance_partners i ON v.insurance_id = i.id
    WHERE DATE(v.visit_date) BETWEEN ? AND ? AND v.facility_id = ?
    GROUP BY day, i.id
    ORDER BY day ASC, total_amount DESC
");
$dailyInsuranceReport->execute([$fromDate, $toDate, $facility_id]);
$dailyInsuranceData = $dailyInsuranceReport->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Daily Staff Report ----------------
$dailyStaffReport = $pdo->prepare("
    SELECT 
        DATE(v.visit_date) AS day,
        u.username AS staff_name,
        SUM(inv.patient_co_pay + inv.insurance_amount) AS total_amount
    FROM visits v
    LEFT JOIN invoices inv ON v.id = inv.visit_id
    LEFT JOIN users u ON v.created_by = u.id
    WHERE DATE(v.visit_date) BETWEEN ? AND ? AND v.facility_id = ?
    GROUP BY day, u.id
    ORDER BY day ASC, total_amount DESC
");
$dailyStaffReport->execute([$fromDate, $toDate, $facility_id]);
$dailyStaffData = $dailyStaffReport->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Daily Totals for Chart ----------------
$dailyTotalsQuery = $pdo->prepare("
    SELECT 
        DATE(v.visit_date) AS day,
        SUM(inv.patient_co_pay) AS patient_copay,
        SUM(inv.insurance_amount) AS insurance_amount,
        SUM(inv.patient_co_pay + inv.insurance_amount) AS total_combined
    FROM visits v
    LEFT JOIN invoices inv ON v.id = inv.visit_id
    WHERE DATE(v.visit_date) BETWEEN ? AND ? AND v.facility_id = ?
    GROUP BY day
    ORDER BY day ASC
");
$dailyTotalsQuery->execute([$fromDate, $toDate, $facility_id]);
$dailyTotalsData = $dailyTotalsQuery->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Prepare Chart Arrays ----------------
$days = [];
$dailyPatientCopay = [];
$dailyInsurance = [];
$dailyCombined = [];
foreach ($dailyTotalsData as $row) {
    $days[] = $row['day'];
    $dailyPatientCopay[] = (float)$row['patient_copay'];
    $dailyInsurance[] = (float)$row['insurance_amount'];
    $dailyCombined[] = (float)$row['total_combined'];
}
?>


<?php 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 data-scroll-to-active="true" 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">

        <!-- Date Filter -->
        <div class="content-header row">
            <div class="col-md-12">
                <h3 class="content-header-title">Daily Insurance & Billing Dashboard</h3>
            </div>
        </div>

        <div class="content-body">
            <div class="card mb-3">
                <div class="card-body">
                    <form method="get" class="form-inline">
                        <div class="form-group mr-2">
                            <label for="from_date" class="mr-1">From:</label>
                            <input type="date" name="from_date" class="form-control" value="<?= htmlspecialchars($fromDate) ?>">
                        </div>
                        <div class="form-group mr-2">
                            <label for="to_date" class="mr-1">To:</label>
                            <input type="date" name="to_date" class="form-control" value="<?= htmlspecialchars($toDate) ?>">
                        </div>
                        <button type="submit" class="btn btn-primary">Filter</button>
                    </form>
                </div>
            </div>

            <!-- Summary Cards -->
            <div class="row">
                <div class="col-xl-3 col-md-6">
                    <div class="card text-center p-3">
                        <h4>Total Patients</h4>
                        <p><?= $summary['total_patients'] ?? 0 ?></p>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6">
                    <div class="card text-center p-3">
                        <h4>Patient Co-Pay <small>(RWF)</small></h4>
                        <p><?= number_format($summary['total_patient_copay'] ?? 0, 2) ?></p>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6">
                    <div class="card text-center p-3">
                        <h4>Insurance Amount <small>(RWF)</small></h4>
                        <p><?= number_format($summary['total_insurance'] ?? 0, 2) ?></p>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6">
                    <div class="card text-center p-3">
                        <h4>Total Amount <small>(RWF)</small></h4>
                        <p><?= number_format($summary['total_combined'] ?? 0, 2) ?></p>
                    </div>
                </div>
            </div>

            <!-- Daily Chart -->
            <div class="card mt-3">
                <div class="card-body">
                    <h5>Daily Billing</h5>
                    <canvas id="dailyChart" height="150"></canvas>
                </div>
            </div>

            <!-- Daily Insurance Table -->
            <div class="card mt-3">
                <div class="card-body">
                    <h5>Daily Insurance Usage</h5>
                    <div class="table-responsive">
                        <table id="dailyInsuranceTable" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Insurance</th>
                                    <th>Patients Count</th>
                                    <th>Patient Co-Pay <small>(RWF)</small></th>
                                    <th>Insurance Amount <small>(RWF)</small></th>
                                    <th>Total Amount <small>(RWF)</small></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($dailyInsuranceData as $row): ?>
                                    <tr>
                                        <td><?= $row['day'] ?></td>
                                        <td><?= htmlspecialchars($row['insurance_name'] ?? 'N/A') ?></td>
                                        <td><?= $row['patient_count'] ?></td>
                                        <td><?= number_format($row['patient_copay'],2) ?></td>
                                        <td><?= number_format($row['insurance_amount'],2) ?></td>
                                        <td><?= number_format($row['total_amount'],2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Daily Staff Table -->
            <div class="card mt-3">
                <div class="card-body">
                    <h5>Daily Staff Totals</h5>
                    <div class="table-responsive">
                        <table id="dailyStaffTable" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Staff Name</th>
                                    <th>Total Amount <small>(RWF)</small></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($dailyStaffData as $row): ?>
                                    <tr>
                                        <td><?= $row['day'] ?></td>
                                        <td><?= htmlspecialchars($row['staff_name'] ?? 'N/A') ?></td>
                                        <td><?= number_format($row['total_amount'],2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

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

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
$(document).ready(function() {
    $('#dailyInsuranceTable, #dailyStaffTable').DataTable({
        pageLength:10,
        dom: 'Bfrtip',
        buttons: ['copy','csv','excel','pdf','print'],
        order:[[0,'asc']]
    });

    // Daily Chart
    const ctx = document.getElementById('dailyChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?= json_encode($days) ?>,
            datasets: [
                {
                    label: 'Patient Co-Pay <small>(RWF)</small>',
                    data: <?= json_encode($dailyPatientCopay) ?>,
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40,167,69,0.2)',
                    fill: true,
                    tension: 0.2
                },
                {
                    label: 'Insurance Amount <small>(RWF)</small>',
                    data: <?= json_encode($dailyInsurance) ?>,
                    borderColor: '#007bff',
                    backgroundColor: 'rgba(0,123,255,0.2)',
                    fill: true,
                    tension: 0.2
                },
                {
                    label: 'Total Amount <small>(RWF)</small>',
                    data: <?= json_encode($dailyCombined) ?>,
                    borderColor: '#ffc107',
                    backgroundColor: 'rgba(255,193,7,0.2)',
                    fill: true,
                    tension: 0.2
                }
            ]
        },
        options: { responsive:true, plugins:{ legend:{position:'top'} }, scales:{ y:{ beginAtZero:true } } }
    });
});
</script>
