<?php
require_once 'config/database.php';
requireAdmin();

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Reports & Analytics</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">Reports</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Filter Section -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Report Filters</h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Date Range</label>
                                        <select id="dateRange" class="form-control">
                                            <option value="today">Today</option>
                                            <option value="week">This Week</option>
                                            <option value="month" selected>This Month</option>
                                            <option value="quarter">This Quarter</option>
                                            <option value="year">This Year</option>
                                            <option value="custom">Custom Range</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Start Date</label>
                                        <input type="date" id="startDate" class="form-control">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>End Date</label>
                                        <input type="date" id="endDate" class="form-control">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button type="button" id="generateReports" class="btn btn-primary btn-block">
                                            <i class="fas fa-chart-line"></i> Generate Reports
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Summary Cards -->
            <div class="row" id="summaryCards">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3 id="totalMembers">0</h3>
                            <p>Total Members</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-users"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3 id="totalRevenue">₹0</h3>
                            <p>Total Revenue</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-rupee-sign"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-warning">
                        <div class="inner">
                            <h3 id="totalEvents">0</h3>
                            <p>Total Events</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-calendar"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3 id="pendingPayments">0</h3>
                            <p>Pending Payments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-exclamation-circle"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Charts Section -->
            <div class="row">
                <!-- Revenue Chart -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Revenue Trend</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <canvas id="revenueChart" height="200"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Membership Chart -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Membership Growth</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <canvas id="membershipChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Event Attendance Chart -->
            <div class="row">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Event Attendance</h3>
                        </div>
                        <div class="card-body">
                            <canvas id="eventChart" height="150"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Payment Methods</h3>
                        </div>
                        <div class="card-body">
                            <canvas id="paymentChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Detailed Reports Tables -->
            <div class="row">
                <!-- Financial Report -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Financial Summary</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-success btn-sm" onclick="exportReport('financial')">
                                    <i class="fas fa-download"></i> Export
                                </button>
                            </div>
                        </div>
                        <div class="card-body table-responsive p-0">
                            <table class="table table-hover text-nowrap">
                                <thead>
                                    <tr>
                                        <th>Category</th>
                                        <th>Amount</th>
                                        <th>Count</th>
                                    </tr>
                                </thead>
                                <tbody id="financialSummary">
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Member Report -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Member Summary</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-success btn-sm" onclick="exportReport('members')">
                                    <i class="fas fa-download"></i> Export
                                </button>
                            </div>
                        </div>
                        <div class="card-body table-responsive p-0">
                            <table class="table table-hover text-nowrap">
                                <thead>
                                    <tr>
                                        <th>Status</th>
                                        <th>Count</th>
                                        <th>Percentage</th>
                                    </tr>
                                </thead>
                                <tbody id="memberSummary">
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Event Detailed Report -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Event Performance Report</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-success btn-sm" onclick="exportReport('events')">
                                    <i class="fas fa-download"></i> Export
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="eventReportTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Event Name</th>
                                        <th>Date</th>
                                        <th>Registrations</th>
                                        <th>Attendance</th>
                                        <th>Revenue</th>
                                        <th>Status</th>
                                        <th>Performance</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let revenueChart, membershipChart, eventChart, paymentChart;

$(document).ready(function() {
    // Set default date range
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    $('#startDate').val(firstDay.toISOString().split('T')[0]);
    $('#endDate').val(today.toISOString().split('T')[0]);
    
    // Initialize charts
    initializeCharts();
    
    // Load initial data
    generateReports();
    
    // Event listeners
    $('#generateReports').click(generateReports);
    $('#dateRange').change(function() {
        if ($(this).val() !== 'custom') {
            setDateRange($(this).val());
            generateReports();
        }
    });
    
    // Initialize event report table
    $('#eventReportTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/reports/fetch_event_reports.php",
            "data": function(d) {
                d.start_date = $('#startDate').val();
                d.end_date = $('#endDate').val();
            }
        },
        "columns": [
            { "data": "event_name" },
            { "data": "event_date", "render": function(data) {
                return new Date(data).toLocaleDateString();
            }},
            { "data": "registrations" },
            { "data": "attendance" },
            { "data": "revenue", "render": function(data) {
                return '₹' + parseFloat(data).toLocaleString();
            }},
            { "data": "status" },
            { "data": null, "render": function(data) {
                const performance = (data.attendance / data.registrations * 100).toFixed(1);
                let badgeClass = 'secondary';
                if (performance >= 80) badgeClass = 'success';
                else if (performance >= 60) badgeClass = 'warning';
                else badgeClass = 'danger';
                return `<span class="badge badge-${badgeClass}">${performance}%</span>`;
            }}
        ]
    });
});

function setDateRange(range) {
    const today = new Date();
    let startDate, endDate = today;
    
    switch(range) {
        case 'today':
            startDate = today;
            break;
        case 'week':
            startDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
            break;
        case 'month':
            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
            break;
        case 'quarter':
            const quarter = Math.floor(today.getMonth() / 3);
            startDate = new Date(today.getFullYear(), quarter * 3, 1);
            break;
        case 'year':
            startDate = new Date(today.getFullYear(), 0, 1);
            break;
    }
    
    $('#startDate').val(startDate.toISOString().split('T')[0]);
    $('#endDate').val(endDate.toISOString().split('T')[0]);
}

function generateReports() {
    const startDate = $('#startDate').val();
    const endDate = $('#endDate').val();
    
    // Update summary cards
    $.get('api/reports/fetch_report_summary.php', {start_date: startDate, end_date: endDate}, function(response) {
        if (response.success) {
            const data = response.data;
            $('#totalMembers').text(data.total_members);
            $('#totalRevenue').text('₹' + parseFloat(data.total_revenue).toLocaleString());
            $('#totalEvents').text(data.total_events);
            $('#pendingPayments').text(data.pending_payments);
        }
    });
    
    // Update charts
    updateCharts(startDate, endDate);
    
    // Update tables
    updateSummaryTables(startDate, endDate);
    
    // Reload event report table
    $('#eventReportTable').DataTable().ajax.reload();
}

function initializeCharts() {
    // Revenue Chart
    const revenueCtx = document.getElementById('revenueChart').getContext('2d');
    revenueChart = new Chart(revenueCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Revenue',
                data: [],
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
    
    // Membership Chart
    const membershipCtx = document.getElementById('membershipChart').getContext('2d');
    membershipChart = new Chart(membershipCtx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: [{
                label: 'New Members',
                data: [],
                backgroundColor: 'rgba(54, 162, 235, 0.8)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
    
    // Event Chart
    const eventCtx = document.getElementById('eventChart').getContext('2d');
    eventChart = new Chart(eventCtx, {
        type: 'doughnut',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: [
                    '#FF6384',
                    '#36A2EB',
                    '#FFCE56',
                    '#4BC0C0',
                    '#9966FF'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
    
    // Payment Chart
    const paymentCtx = document.getElementById('paymentChart').getContext('2d');
    paymentChart = new Chart(paymentCtx, {
        type: 'pie',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: [
                    '#FF6384',
                    '#36A2EB',
                    '#FFCE56',
                    '#4BC0C0'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}

function updateCharts(startDate, endDate) {
    // Update revenue chart
    $.get('api/charts/fetch_revenue_chart.php', {start_date: startDate, end_date: endDate}, function(response) {
        if (response.success) {
            revenueChart.data.labels = response.data.labels;
            revenueChart.data.datasets[0].data = response.data.values;
            revenueChart.update();
        }
    });
    
    // Update membership chart
    $.get('api/charts/fetch_membership_chart.php', {start_date: startDate, end_date: endDate}, function(response) {
        if (response.success) {
            membershipChart.data.labels = response.data.labels;
            membershipChart.data.datasets[0].data = response.data.values;
            membershipChart.update();
        }
    });
    
    // Update event chart
    $.get('api/charts/fetch_event_chart.php', {start_date: startDate, end_date: endDate}, function(response) {
        if (response.success) {
            eventChart.data.labels = response.data.labels;
            eventChart.data.datasets[0].data = response.data.values;
            eventChart.update();
        }
    });
    
    // Update payment chart
    $.get('api/charts/fetch_payment_chart.php', {start_date: startDate, end_date: endDate}, function(response) {
        if (response.success) {
            paymentChart.data.labels = response.data.labels;
            paymentChart.data.datasets[0].data = response.data.values;
            paymentChart.update();
        }
    });
}

function updateSummaryTables(startDate, endDate) {
    // Financial summary
    $.get('api/finance/fetch_financial_summary.php', {start_date: startDate, end_date: endDate}, function(response) {
        if (response.success) {
            let html = '';
            response.data.forEach(function(item) {
                html += `<tr>
                    <td>${item.category}</td>
                    <td>₹${parseFloat(item.amount).toLocaleString()}</td>
                    <td>${item.count}</td>
                </tr>`;
            });
            $('#financialSummary').html(html);
        }
    });
    
    // Member summary
    $.get('api/fetch_member_summary.php', {start_date: startDate, end_date: endDate}, function(response) {
        if (response.success) {
            let html = '';
            response.data.forEach(function(item) {
                html += `<tr>
                    <td>${item.status}</td>
                    <td>${item.count}</td>
                    <td>${item.percentage}%</td>
                </tr>`;
            });
            $('#memberSummary').html(html);
        }
    });
}

function exportReport(type) {
    const startDate = $('#startDate').val();
    const endDate = $('#endDate').val();
    
    window.open(`api/reports/export_report.php?type=${type}&start_date=${startDate}&end_date=${endDate}`, '_blank');
}
</script>

<?php require_once 'templates/footer.php'; ?>
