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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$doctor_id = $_SESSION['user_id'];

// Get doctor commission rate
$doctor_query = "SELECT commission_rate FROM doctors WHERE user_id = ?";
$doctor_stmt = $conn->prepare($doctor_query);
$doctor_stmt->bind_param("i", $doctor_id);
$doctor_stmt->execute();
$doctor = $doctor_stmt->get_result()->fetch_assoc();
$commission_rate = $doctor['commission_rate'] ?? 0;

// Get commission statistics
$stats_query = "SELECT 
    SUM(amount_paid * ? / 100) as total_commission,
    SUM(CASE WHEN MONTH(payment_date) = MONTH(CURDATE()) THEN amount_paid * ? / 100 ELSE 0 END) as current_month,
    SUM(CASE WHEN MONTH(payment_date) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) THEN amount_paid * ? / 100 ELSE 0 END) as last_month,
    SUM(CASE WHEN YEAR(payment_date) = YEAR(CURDATE()) THEN amount_paid * ? / 100 ELSE 0 END) as current_year
FROM payments p
INNER JOIN consultations c ON p.consultation_id = c.consultation_id
WHERE c.doctor_id = ? AND p.payment_status = 'COMPLETED'";

$stats_stmt = $conn->prepare($stats_query);
$stats_stmt->bind_param("ddddi", $commission_rate, $commission_rate, $commission_rate, $commission_rate, $doctor_id);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My 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" type="text/css" />
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

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

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <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">My Commissions</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="ent_consultant_dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">My Commissions</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Commission Rate Info -->
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-info">
                                <i class="ri-information-line me-2"></i>
                                <strong>Your Commission Rate:</strong> <?php echo number_format($commission_rate, 2); ?>% of consultation fees
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Total Earned</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($stats['total_commission'], 2); ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success rounded fs-3">
                                                <i class="bx bx-wallet text-success"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Current Month</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($stats['current_month'], 2); ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info rounded fs-3">
                                                <i class="bx bx-calendar text-info"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Last Month</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($stats['last_month'], 2); ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="bx bx-trending-up text-warning"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Year to Date</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($stats['current_year'], 2); ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="bx bx-line-chart text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Commission Chart -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Monthly Commission Trend</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="commissionChart" height="100"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Commission Details Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="card-title mb-0">Commission Details</h5>
                                        <div>
                                            <button class="btn btn-soft-primary me-2" id="filterBtn">
                                                <i class="ri-filter-line"></i> Filter
                                            </button>
                                            <button class="btn btn-soft-success" id="exportBtn">
                                                <i class="ri-file-excel-line"></i> Export
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <!-- Filter Row -->
                                    <div class="row mb-3" id="filterRow" style="display: none;">
                                        <div class="col-md-4">
                                            <label class="form-label">Date Range</label>
                                            <input type="text" class="form-control" id="dateRange" placeholder="Select date range">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">&nbsp;</label>
                                            <div class="d-flex gap-2">
                                                <button class="btn btn-primary" id="applyFilter">Apply</button>
                                                <button class="btn btn-secondary" id="resetFilter">Reset</button>
                                            </div>
                                        </div>
                                    </div>

                                    <table id="commissionsTable" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Receipt No</th>
                                                <th>Patient</th>
                                                <th>Service</th>
                                                <th>Amount Paid</th>
                                                <th>Commission Rate</th>
                                                <th>Commission Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Data loaded via AJAX -->
                                        </tbody>
                                        <tfoot>
                                            <tr class="table-success">
                                                <th colspan="6" class="text-end"><strong>Total Commission:</strong></th>
                                                <th><strong id="totalCommission">KES 0.00</strong></th>
                                            </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 src="assets/libs/flatpickr/flatpickr.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            var commissionRate = <?php echo $commission_rate; ?>;

            flatpickr("#dateRange", {
                mode: "range",
                dateFormat: "Y-m-d"
            });

            // Load commission chart
            $.ajax({
                url: 'ajax/get_commission_chart_data.php',
                type: 'POST',
                success: function(response) {
                    var data = JSON.parse(response);
                    var ctx = document.getElementById('commissionChart').getContext('2d');
                    new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: data.labels,
                            datasets: [{
                                label: 'Commission (KES)',
                                data: data.values,
                                borderColor: '#2d7a2d',
                                backgroundColor: 'rgba(45, 122, 45, 0.1)',
                                borderWidth: 2,
                                fill: true,
                                tension: 0.4
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: true,
                            plugins: {
                                legend: {
                                    display: true
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return 'KES ' + value.toLocaleString();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });

            var table = $('#commissionsTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: 'ajax/get_commission_details.php',
                    type: 'POST',
                    data: function(d) {
                        d.date_range = $('#dateRange').val();
                    },
                    dataSrc: function(json) {
                        var total = 0;
                        json.data.forEach(function(row) {
                            total += parseFloat(row.commission_amount_raw);
                        });
                        $('#totalCommission').text('KES ' + total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
                        return json.data;
                    }
                },
                columns: [
                    { data: 'payment_date' },
                    { data: 'receipt_number' },
                    { data: 'patient_name' },
                    { data: 'service' },
                    { data: 'amount_paid' },
                    { data: 'commission_rate' },
                    { data: 'commission_amount' }
                ],
                order: [[0, 'desc']],
                pageLength: 25
            });

            $('#filterBtn').on('click', function() {
                $('#filterRow').slideToggle();
            });

            $('#applyFilter').on('click', function() {
                table.ajax.reload();
            });

            $('#resetFilter').on('click', function() {
                $('#dateRange').val('');
                table.ajax.reload();
            });

            $('#exportBtn').on('click', function() {
                var dateRange = $('#dateRange').val();
                window.location.href = 'export/export_commissions.php?date_range=' + dateRange;
            });
        });
    </script>
</body>
</html>