<?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');


// ---------------- Helper (hide 0 / NULL amounts) ----------------
function fmt_amount($value, $decimals = 2) {
    if ($value === null || (float)$value == 0.0) {
        return '';
    }
    return number_format((float)$value, $decimals);
}

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

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

// ---------------- Date Filter ----------------
$selectedDate = $_GET['report_date'] ?? date('Y-m-d');

// ---------------- Daily Insurance Report ----------------
$dailyInsurance = $pdo->prepare("
    SELECT 
        i.name AS insurance_name,
        COUNT(DISTINCT v.patient_id) AS patient_count,
        COALESCE(SUM(inv.patient_co_pay),0) AS patient_copay,
        COALESCE(SUM(inv.insurance_amount),0) AS insurance_amount,
        COALESCE(SUM(inv.patient_co_pay + inv.insurance_amount),0) AS total_amount
    FROM visits v
    INNER JOIN invoices inv 
        ON v.id = inv.visit_id 
       AND inv.is_removed = 0
    INNER JOIN insurance_partners i 
        ON v.insurance_id = i.id
    WHERE DATE(v.visit_date) = ?
      AND v.facility_id = ?
    GROUP BY i.id
    HAVING total_amount > 0
    ORDER BY total_amount DESC
");

$dailyInsurance->execute([$selectedDate, $facility_id]);
$dailyInsuranceData = $dailyInsurance->fetchAll(PDO::FETCH_ASSOC);

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

// ---------------- Daily Payment Method Report ----------------
$dailyPayment = $pdo->prepare("
    SELECT 
        inv.payment_method,
        COUNT(DISTINCT v.patient_id) AS patient_count,
        COALESCE(SUM(inv.patient_co_pay + inv.insurance_amount),0) AS total_amount
    FROM visits v
    INNER JOIN invoices inv ON v.id = inv.visit_id AND inv.is_removed = 0
    WHERE DATE(v.visit_date) = ? AND v.facility_id = ?
      AND inv.payment_method IS NOT NULL AND inv.payment_method != ''
    GROUP BY inv.payment_method
    ORDER BY total_amount DESC
");
$dailyPayment->execute([$selectedDate, $facility_id]);
$dailyPaymentData = $dailyPayment->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 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">

    <!-- Header & Date Filter -->
    <div class="content-header row">
        <div class="col-md-12">
            <h3 class="content-header-title">Daily Insurance & Billing Report</h3>
            <form method="get" class="form-inline mt-2 mb-3">
                <label class="mr-2">Date:</label>
                <input type="date" name="report_date" class="form-control mr-2"
                       value="<?= htmlspecialchars($selectedDate) ?>">
                <button type="submit" class="btn btn-primary">Show Report</button>
            </form>
        </div>
    </div>

    <div class="content-body">

        <!-- Insurance Table -->
        <div class="card mb-3 shadow-sm">
            <div class="card-body">
                <h5>Insurance Usage for <?= htmlspecialchars($selectedDate) ?></h5>
                <div class="table-responsive">
                    <table id="dailyInsuranceTable" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Insurance</th>
                                <th>Patients</th>
                                <th>Patient Co-Pay (RWF)</th>
                                <th>Insurance Amount (RWF)</th>
                                <th>Total (RWF)</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($dailyInsuranceData as $row): ?>
                            <tr>
                                <td><?= htmlspecialchars($row['insurance_name']) ?></td>
                                <td><?= (int)$row['patient_count'] ?></td>
                                <td><?= fmt_amount($row['patient_copay']) ?></td>
                                <td><?= fmt_amount($row['insurance_amount']) ?></td>
                                <td><?= fmt_amount($row['total_amount']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Staff Table -->
        <div class="card mb-3 shadow-sm">
            <div class="card-body">
                <h5>Staff Totals for <?= htmlspecialchars($selectedDate) ?></h5>
                <div class="table-responsive">
                    <table id="dailyStaffTable" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Staff</th>
                                <th>Total Amount (RWF)</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($dailyStaffData as $row): ?>
                            <tr>
                                <td><?= htmlspecialchars($row['staff_name']) ?></td>
                                <td><?= fmt_amount($row['total_amount']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Payment Method Table -->
        <div class="card mb-3 shadow-sm">
            <div class="card-body">
                <h5>Payment Methods for <?= htmlspecialchars($selectedDate) ?></h5>
                <div class="table-responsive">
                    <table id="dailyPaymentTable" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Payment Method</th>
                                <th>Patients</th>
                                <th>Total Amount (RWF)</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($dailyPaymentData as $row): ?>
                            <tr>
                                <td><?= htmlspecialchars($row['payment_method']) ?></td>
                                <td><?= (int)$row['patient_count'] ?></td>
                                <td><?= fmt_amount($row['total_amount']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

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

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

<!-- DataTables -->
<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>
$(function(){
    $('#dailyInsuranceTable').DataTable({
        pageLength:10, order:[[4,'desc']], dom:'Bfrtip',
        buttons:['copy','csv','excel','pdf','print']
    });
    $('#dailyStaffTable').DataTable({
        pageLength:10, order:[[1,'desc']], dom:'Bfrtip',
        buttons:['copy','csv','excel','pdf','print']
    });
    $('#dailyPaymentTable').DataTable({
        pageLength:10, order:[[2,'desc']], dom:'Bfrtip',
        buttons:['copy','csv','excel','pdf','print']
    });
});
</script>
