<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

// Check permissions
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'FINANCE_MANAGER'])) {
    header('Location: access_denied.php');
    exit();
}

$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');

// Fetch Commissions Summary
$sql = "SELECT 
            d.doctor_id,
            u.full_name,
            d.specialization,
            COUNT(pa.allocation_id) as total_services,
            SUM(pa.total_service_cost) as total_revenue,
            SUM(pa.doctor_allocation) as gross_commission,
            SUM(pa.tax_withheld) as tax,
            SUM(pa.net_doctor_payment) as net_payable,
            SUM(CASE WHEN pa.doctor_payment_status = 'PAID' THEN pa.net_doctor_payment ELSE 0 END) as paid_amount,
            SUM(CASE WHEN pa.doctor_payment_status = 'PENDING' THEN pa.net_doctor_payment ELSE 0 END) as pending_amount
        FROM payment_allocations pa
        JOIN doctors d ON pa.doctor_id = d.doctor_id
        JOIN users u ON d.user_id = u.user_id
        WHERE pa.service_date BETWEEN ? AND ?
        AND pa.allocation_status = 'APPROVED'
        GROUP BY d.doctor_id
        ORDER BY gross_commission DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $date_from, $date_to);
$stmt->execute();
$result = $stmt->get_result();

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Staff Commissions')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Staff Commissions Dashboard</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Commissions</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">From Date</label>
                                            <input type="date" class="form-control" name="date_from"
                                                value="<?php echo htmlspecialchars($date_from); ?>">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">To Date</label>
                                            <input type="date" class="form-control" name="date_to"
                                                value="<?php echo htmlspecialchars($date_to); ?>">
                                        </div>
                                        <div class="col-md-4 d-flex align-items-end">
                                            <button type="submit" class="btn btn-primary w-100"><i
                                                    class="ri-filter-3-line me-1"></i> Filter Report</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Commissions Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Commissions Summary</h5>
                                </div>
                                <div class="card-body">
                                    <table id="commissionsTable"
                                        class="table table-bordered dt-responsive nowrap table-striped align-middle"
                                        style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>Doctor / Staff</th>
                                                <th>Specialization</th>
                                                <th>Services</th>
                                                <th>Total Revenue</th>
                                                <th>Gross Commission</th>
                                                <th>Tax (WHT)</th>
                                                <th>Net Payable</th>
                                                <th>Paid</th>
                                                <th>Pending</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($row['specialization']); ?></td>
                                                    <td><?php echo number_format($row['total_services']); ?></td>
                                                    <td><?php echo number_format($row['total_revenue'], 2); ?></td>
                                                    <td class="text-primary fw-bold">
                                                        <?php echo number_format($row['gross_commission'], 2); ?></td>
                                                    <td class="text-danger"><?php echo number_format($row['tax'], 2); ?>
                                                    </td>
                                                    <td class="text-success fw-bold">
                                                        <?php echo number_format($row['net_payable'], 2); ?></td>
                                                    <td><?php echo number_format($row['paid_amount'], 2); ?></td>
                                                    <td class="text-warning">
                                                        <?php echo number_format($row['pending_amount'], 2); ?></td>
                                                    <td>
                                                        <a href="doctor_earnings_report.php?id=<?php echo $row['doctor_id']; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>"
                                                            class="btn btn-sm btn-info"><i class="ri-eye-line"></i>
                                                            Report</a>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr class="table-light fw-bold">
                                                <td colspan="3">Totals</td>
                                                <td>-</td>
                                                <td>-</td>
                                                <td>-</td>
                                                <td>-</td>
                                                <td>-</td>
                                                <td>-</td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function () {
            var table = $('#commissionsTable').DataTable({
                "footerCallback": function (row, data, start, end, display) {
                    var api = this.api();

                    // Helper to convert string to number
                    var intVal = function (i) {
                        return typeof i === 'string' ?
                            i.replace(/[\$,]/g, '') * 1 :
                            typeof i === 'number' ?
                                i : 0;
                    };

                    // Total over all pages
                    totalRevenue = api.column(3).data().reduce(function (a, b) { return intVal(a) + intVal(b); }, 0);
                    totalGross = api.column(4).data().reduce(function (a, b) { return intVal(a) + intVal(b); }, 0);
                    totalNet = api.column(6).data().reduce(function (a, b) { return intVal(a) + intVal(b); }, 0);

                    // Update footer
                    $(api.column(3).footer()).html(totalRevenue.toLocaleString('en-US', { minimumFractionDigits: 2 }));
                    $(api.column(4).footer()).html(totalGross.toLocaleString('en-US', { minimumFractionDigits: 2 }));
                    $(api.column(6).footer()).html(totalNet.toLocaleString('en-US', { minimumFractionDigits: 2 }));
                }
            });
        });
    </script>
</body>

</html>