<?php
require_once 'config/database.php';
require_once 'config/auth_enhanced.php';
requireAdmin(); // Ensure only admins can access this page

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 text-dark">
                        <i class="fas fa-tachometer-alt text-primary"></i> 
                        Dashboard
                    </h1>
                    <small class="text-muted">Welcome back, manage your KSO operations</small>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#" class="text-primary">Home</a></li>
                        <li class="breadcrumb-item active">Dashboard</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Enhanced Stats Cards with Premium Design -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="info-box shadow-sm">
                        <span class="info-box-icon bg-gradient-info elevation-1">
                            <i class="fas fa-users"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Members</span>
                            <span class="info-box-number" id="totalMembers">
                                0
                                <small class="text-muted">registered</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar bg-info" style="width: 70%"></div>
                            </div>
                            <span class="progress-description">
                                <span id="memberProgress"><i class="fas fa-spinner fa-spin"></i> Loading...</span>
                            </span>
                        </div>
                        <div class="info-box-more">
                            <a href="members.php" class="text-info">
                                <i class="fas fa-arrow-circle-right"></i>
                            </a>
                        </div>
                    </div>
                </div>

                <div class="col-lg-3 col-6">
                    <div class="info-box shadow-sm">
                        <span class="info-box-icon bg-gradient-success elevation-1">
                            <i class="fas fa-calendar-alt"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Events</span>
                            <span class="info-box-number" id="totalEvents">
                                0
                                <small class="text-muted">planned</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar bg-success" style="width: 50%"></div>
                            </div>
                            <span class="progress-description">
                                <span id="eventProgress"><i class="fas fa-spinner fa-spin"></i> Loading...</span>
                            </span>
                        </div>
                        <div class="info-box-more">
                            <a href="events.php" class="text-success">
                                <i class="fas fa-arrow-circle-right"></i>
                            </a>
                        </div>
                    </div>
                </div>

                <div class="col-lg-3 col-6">
                    <div class="info-box shadow-sm">
                        <span class="info-box-icon bg-gradient-warning elevation-1">
                            <i class="fas fa-rupee-sign"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Income</span>
                            <span class="info-box-number" id="totalIncome">
                                ₹0
                                <small class="text-muted">collected</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar bg-warning" style="width: 85%"></div>
                            </div>
                            <span class="progress-description">
                                <span id="incomeProgress"><i class="fas fa-spinner fa-spin"></i> Loading...</span>
                            </span>
                        </div>
                        <div class="info-box-more">
                            <a href="finance.php" class="text-warning">
                                <i class="fas fa-arrow-circle-right"></i>
                            </a>
                        </div>
                    </div>
                </div>

                <div class="col-lg-3 col-6">
                    <div class="info-box shadow-sm">
                        <span class="info-box-icon bg-gradient-danger elevation-1">
                            <i class="fas fa-clock"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">Pending Approvals</span>
                            <span class="info-box-number" id="pendingApprovals">
                                0
                                <small class="text-muted">waiting</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar bg-danger" style="width: 30%"></div>
                            </div>
                            <span class="progress-description">
                                <span id="approvalProgress"><i class="fas fa-spinner fa-spin"></i> Loading...</span>
                            </span>
                        </div>
                        <div class="info-box-more">
                            <a href="member-approval.php" class="text-danger">
                                <i class="fas fa-arrow-circle-right"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Actions Row -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card card-outline card-primary">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-bolt text-primary"></i> Quick Actions
                            </h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-2 col-6">
                                    <a href="member-registration.php" class="btn btn-app bg-primary">
                                        <i class="fas fa-user-plus"></i>
                                        Add Member
                                    </a>
                                </div>
                                <div class="col-md-2 col-6">
                                    <a href="events.php?action=new" class="btn btn-app bg-success">
                                        <i class="fas fa-calendar-plus"></i>
                                        New Event
                                    </a>
                                </div>
                                <div class="col-md-2 col-6">
                                    <a href="finance.php" class="btn btn-app bg-warning">
                                        <i class="fas fa-money-bill-wave"></i>
                                        Finance
                                    </a>
                                </div>
                                <div class="col-md-2 col-6">
                                    <a href="reports.php" class="btn btn-app bg-info">
                                        <i class="fas fa-chart-line"></i>
                                        Reports
                                    </a>
                                </div>
                                <div class="col-md-2 col-6">
                                    <a href="notifications.php" class="btn btn-app bg-secondary">
                                        <i class="fas fa-bell"></i>
                                        Notifications
                                    </a>
                                </div>
                                <div class="col-md-2 col-6">
                                    <a href="settings.php" class="btn btn-app bg-dark">
                                        <i class="fas fa-cog"></i>
                                        Settings
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Premium Data Tables Section -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <!-- Enhanced Recent Members Card -->
                <div class="col-md-6">
                    <div class="card card-outline card-info shadow">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-users text-info"></i> Recent Members
                            </h3>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 150px;">
                                    <select id="memberStatusFilter" class="form-control form-control-sm">
                                        <option value="">All Status</option>
                                        <option value="approved">
                                            <i class="fas fa-check"></i> Approved
                                        </option>
                                        <option value="pending">
                                            <i class="fas fa-clock"></i> Pending
                                        </option>
                                        <option value="rejected">
                                            <i class="fas fa-times"></i> Rejected
                                        </option>
                                    </select>
                                </div>
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                                <button type="button" class="btn btn-tool" data-card-widget="maximize">
                                    <i class="fas fa-expand"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div id="membersTableContainer" class="table-responsive">
                                <table id="membersTable" class="table table-striped table-hover">
                                    <thead class="bg-light">
                                        <tr>
                                            <th class="text-center">#</th>
                                            <th>
                                                <i class="fas fa-user"></i> Member
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-id-card"></i> KSO ID
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-info-circle"></i> Status
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-calendar"></i> Joined
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td colspan="5" class="text-center py-4">
                                                <div class="spinner-border text-info" role="status">
                                                    <span class="sr-only">Loading...</span>
                                                </div>
                                                <div class="mt-2">Loading members...</div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="card-footer bg-light">
                            <div class="row">
                                <div class="col-sm-6">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle"></i> 
                                        Last updated: <span id="membersLastUpdate">Just now</span>
                                    </small>
                                </div>
                                <div class="col-sm-6 text-right">
                                    <a href="members.php" class="btn btn-sm btn-info">
                                        <i class="fas fa-eye"></i> View All
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Enhanced Events Card -->
                <div class="col-md-6">
                    <div class="card card-outline card-success shadow">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-calendar-alt text-success"></i> Events Overview
                            </h3>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 150px;">
                                    <select id="eventFilter" class="form-control form-control-sm">
                                        <option value="upcoming">
                                            <i class="fas fa-clock"></i> Upcoming
                                        </option>
                                        <option value="current">
                                            <i class="fas fa-play"></i> Current
                                        </option>
                                        <option value="past">
                                            <i class="fas fa-history"></i> Past
                                        </option>
                                        <option value="all">
                                            <i class="fas fa-list"></i> All Events
                                        </option>
                                    </select>
                                </div>
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                                <button type="button" class="btn btn-tool" data-card-widget="maximize">
                                    <i class="fas fa-expand"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div id="eventsTableContainer" class="table-responsive">
                                <table id="eventsTable" class="table table-striped table-hover">
                                    <thead class="bg-light">
                                        <tr>
                                            <th class="text-center">#</th>
                                            <th>
                                                <i class="fas fa-calendar-check"></i> Event
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-calendar"></i> Date
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-info-circle"></i> Status
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-users"></i> Attendees
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td colspan="5" class="text-center py-4">
                                                <div class="spinner-border text-success" role="status">
                                                    <span class="sr-only">Loading...</span>
                                                </div>
                                                <div class="mt-2">Loading events...</div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="card-footer bg-light">
                            <div class="row">
                                <div class="col-sm-6">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle"></i> 
                                        Last updated: <span id="eventsLastUpdate">Just now</span>
                                    </small>
                                </div>
                                <div class="col-sm-6 text-right">
                                    <a href="events.php" class="btn btn-sm btn-success">
                                        <i class="fas fa-eye"></i> View All
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Premium Analytics Row -->
            <div class="row">
                <!-- Enhanced Member Statistics Chart -->
                <div class="col-md-8">
                    <div class="card card-outline card-primary shadow">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-chart-line text-primary"></i> Member Analytics & Growth
                            </h3>
                            <div class="card-tools">
                                <div class="btn-group" role="group" aria-label="Chart Controls">
                                    <button type="button" class="btn btn-tool btn-sm" id="chartPeriod" data-period="month">
                                        <i class="fas fa-calendar-alt"></i> Monthly
                                    </button>
                                    <button type="button" class="btn btn-tool btn-sm" data-period="year">
                                        <i class="fas fa-calendar"></i> Yearly
                                    </button>
                                </div>
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                                <button type="button" class="btn btn-tool" data-card-widget="maximize">
                                    <i class="fas fa-expand"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-sm-3">
                                    <div class="description-block">
                                        <span class="description-percentage text-success" id="newMembersGrowth">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </span>
                                        <h5 class="description-header" id="newMembersCount">-</h5>
                                        <span class="description-text">NEW MEMBERS</span>
                                    </div>
                                </div>
                                <div class="col-sm-3">
                                    <div class="description-block">
                                        <span class="description-percentage text-warning" id="pendingGrowth">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </span>
                                        <h5 class="description-header" id="pendingCount">-</h5>
                                        <span class="description-text">PENDING</span>
                                    </div>
                                </div>
                                <div class="col-sm-3">
                                    <div class="description-block">
                                        <span class="description-percentage text-success" id="approvalRateGrowth">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </span>
                                        <h5 class="description-header" id="approvalRateValue">-</h5>
                                        <span class="description-text">APPROVAL RATE</span>
                                    </div>
                                </div>
                                <div class="col-sm-3">
                                    <div class="description-block">
                                        <span class="description-percentage text-info" id="revenueGrowth">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </span>
                                        <h5 class="description-header" id="revenueValue">-</h5>
                                        <span class="description-text">REVENUE</span>
                                    </div>
                                </div>
                            </div>
                            <div class="chart-container" style="position: relative; height: 300px; max-height: 300px;">
                                <canvas id="membershipChart"></canvas>
                            </div>
                        </div>
                        <div class="card-footer bg-light">
                            <div class="row">
                                <div class="col-sm-6">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle"></i> 
                                        Data updated every hour
                                    </small>
                                </div>
                                <div class="col-sm-6 text-right">
                                    <a href="reports.php?type=member-analytics" class="btn btn-sm btn-primary">
                                        <i class="fas fa-chart-bar"></i> Detailed Report
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Enhanced Activity Feed -->
                <div class="col-md-4">
                    <div class="card card-outline card-warning shadow">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-bell text-warning"></i> Recent Activity
                            </h3>
                            <div class="card-tools">
                                <span class="badge badge-warning" id="activityCount">5</span>
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0" style="max-height: 400px; overflow-y: auto;">
                            <ul class="list-unstyled">
                                <li class="p-3 border-bottom">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="bg-success rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-user-plus text-white"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ml-3">
                                            <div class="font-weight-bold">New Member Registration</div>
                                            <small class="text-muted">Rajesh Kumar joined KSO</small>
                                            <div class="small text-muted">
                                                <i class="fas fa-clock"></i> 2 minutes ago
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                <li class="p-3 border-bottom">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="bg-info rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-calendar text-white"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ml-3">
                                            <div class="font-weight-bold">Event Created</div>
                                            <small class="text-muted">Annual Sports Meet scheduled</small>
                                            <div class="small text-muted">
                                                <i class="fas fa-clock"></i> 15 minutes ago
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                <li class="p-3 border-bottom">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-rupee-sign text-white"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ml-3">
                                            <div class="font-weight-bold">Payment Received</div>
                                            <small class="text-muted">Membership fee ₹5,000</small>
                                            <div class="small text-muted">
                                                <i class="fas fa-clock"></i> 1 hour ago
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                <li class="p-3 border-bottom">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="bg-danger rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-exclamation text-white"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ml-3">
                                            <div class="font-weight-bold">System Alert</div>
                                            <small class="text-muted">Database backup completed</small>
                                            <div class="small text-muted">
                                                <i class="fas fa-clock"></i> 2 hours ago
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                <li class="p-3">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-cog text-white"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ml-3">
                                            <div class="font-weight-bold">Settings Updated</div>
                                            <small class="text-muted">Email notifications enabled</small>
                                            <div class="small text-muted">
                                                <i class="fas fa-clock"></i> 3 hours ago
                                            </div>
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <div class="card-footer bg-light text-center">
                            <a href="notifications.php" class="btn btn-sm btn-warning">
                                <i class="fas fa-list"></i> View All Activities
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Premium Financial Overview Row -->
            <div class="row">
                <div class="col-12">
                    <div class="card card-outline card-success shadow">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-chart-pie text-success"></i> Financial Overview & Transactions
                            </h3>
                            <div class="card-tools">
                                <div class="btn-group" role="group">
                                    <select id="transactionFilter" class="form-control form-control-sm">
                                        <option value="">All Types</option>
                                        <option value="income">
                                            <i class="fas fa-plus"></i> Income
                                        </option>
                                        <option value="expense">
                                            <i class="fas fa-minus"></i> Expense
                                        </option>
                                    </select>
                                </div>
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                                <button type="button" class="btn btn-tool" data-card-widget="maximize">
                                    <i class="fas fa-expand"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row mb-4">
                                <div class="col-md-3">
                                    <div class="description-block border-right">
                                        <h5 class="description-header text-success" id="totalIncomeValue">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </h5>
                                        <span class="description-text">TOTAL INCOME</span>
                                        <div class="sparkbar" id="incomeSparkbar" data-color="#00a65a" data-height="20">0,0,0,0,0,0,0</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="description-block border-right">
                                        <h5 class="description-header text-warning" id="totalExpensesValue">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </h5>
                                        <span class="description-text">TOTAL EXPENSES</span>
                                        <div class="sparkbar" id="expensesSparkbar" data-color="#f39c12" data-height="20">0,0,0,0,0,0,0</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="description-block border-right">
                                        <h5 class="description-header text-info" id="netProfitValue">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </h5>
                                        <span class="description-text">NET PROFIT</span>
                                        <div class="sparkbar" id="profitSparkbar" data-color="#00c0ef" data-height="20">0,0,0,0,0,0,0</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="description-block">
                                        <h5 class="description-header text-primary" id="thisMonthValue">
                                            <i class="fas fa-spinner fa-spin"></i> Loading...
                                        </h5>
                                        <span class="description-text">THIS MONTH</span>
                                        <div class="sparkbar" id="monthlySparkbar" data-color="#3c8dbc" data-height="20">0,0,0,0,0,0,0</div>
                                    </div>
                                </div>
                            </div>
                            <div id="transactionsTableContainer" class="table-responsive">
                                <table id="transactionsTable" class="table table-striped table-hover">
                                    <thead class="bg-light">
                                        <tr>
                                            <th class="text-center">#</th>
                                            <th>
                                                <i class="fas fa-user"></i> Member/Source
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-tags"></i> Type
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-rupee-sign"></i> Amount
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-info-circle"></i> Status
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-calendar"></i> Date
                                            </th>
                                            <th class="text-center">
                                                <i class="fas fa-cog"></i> Actions
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td colspan="7" class="text-center py-4">
                                                <div class="spinner-border text-success" role="status">
                                                    <span class="sr-only">Loading...</span>
                                                </div>
                                                <div class="mt-2">Loading transactions...</div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="card-footer bg-light">
                            <div class="row">
                                <div class="col-sm-6">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle"></i> 
                                        Financial data updated real-time
                                    </small>
                                </div>
                                <div class="col-sm-6 text-right">
                                    <a href="finance.php" class="btn btn-sm btn-success">
                                        <i class="fas fa-chart-line"></i> Full Finance Report
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Enhanced Performance Metrics Row -->
            <div class="row">
                <div class="col-md-3">
                    <div class="info-box shadow-sm bg-gradient-info">
                        <span class="info-box-icon elevation-1">
                            <i class="fas fa-user-check"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">Active Members</span>
                            <span class="info-box-number" id="activeMembersCount">
                                0
                                <small class="text-white-50">members</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 80%"></div>
                            </div>
                            <span class="progress-description text-white-50">
                                <i class="fas fa-arrow-up"></i> 5% from last month
                            </span>
                        </div>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="info-box shadow-sm bg-gradient-success">
                        <span class="info-box-icon elevation-1">
                            <i class="fas fa-calendar-check"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">This Month Events</span>
                            <span class="info-box-number" id="monthlyEventsCount">
                                0
                                <small class="text-white-50">events</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 60%"></div>
                            </div>
                            <span class="progress-description text-white-50">
                                <i class="fas fa-arrow-up"></i> 3 more than last month
                            </span>
                        </div>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="info-box shadow-sm bg-gradient-warning">
                        <span class="info-box-icon elevation-1">
                            <i class="fas fa-rupee-sign"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">Monthly Income</span>
                            <span class="info-box-number" id="monthlyIncomeCount">
                                ₹0
                                <small class="text-white-50">collected</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 70%"></div>
                            </div>
                            <span class="progress-description text-white-50">
                                <i class="fas fa-arrow-up"></i> ₹5K above target
                            </span>
                        </div>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="info-box shadow-sm bg-gradient-danger">
                        <span class="info-box-icon elevation-1">
                            <i class="fas fa-tasks"></i>
                        </span>
                        <div class="info-box-content">
                            <span class="info-box-text">Pending Actions</span>
                            <span class="info-box-number" id="pendingActionsCount">
                                0
                                <small class="text-white-50">tasks</small>
                            </span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 25%"></div>
                            </div>
                            <span class="progress-description text-white-50">
                                <i class="fas fa-arrow-down"></i> 2 resolved today
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap 4 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables & Plugins -->
<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.bootstrap4.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>

<!-- Additional CSS for Chart Sizing -->
<style>
.chart-container {
    position: relative !important;
    height: 300px !important;
    max-height: 300px !important;
    overflow: hidden !important;
}

.chart-container canvas {
    max-height: 300px !important;
    height: 300px !important;
}

/* Ensure chart responsiveness on mobile */
@media (max-width: 768px) {
    .chart-container {
        height: 250px !important;
        max-height: 250px !important;
    }
    
    .chart-container canvas {
        max-height: 250px !important;
        height: 250px !important;
    }
}
</style>

<!-- KSO Enhanced JavaScript Components (loaded after jQuery) -->
<script src="dist/js/preloader.js"></script>
<script src="dist/js/theme-manager.js"></script>
<script src="dist/js/toast.js"></script>
<script src="dist/js/timeline.js"></script>
<script src="dist/js/dashboard-widgets.js"></script>
<script src="dist/js/print-system.js"></script>
<script src="dist/js/quick-print-button.js"></script>
<script src="dist/js/breadcrumbs.js"></script>
<!-- Notification System -->
<script src="dist/js/notifications/notification-system.js"></script>

<script>
    $(document).ready(function() {
        // Load all dashboard data
        console.log('Starting dashboard initialization...');
        loadDashboardStats();
        initializeDataTables();
        initializeMemberChart();

        function loadDashboardStats() {
            // First, set default "No Data" values
            setNoDataValues();
            
            console.log('Loading dashboard stats...');
            
            $.ajax({
                url: 'api/dashboard/fetch_dashboard_stats.php',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    console.log('Dashboard API Response:', response);
                    if (response.success) {
                        const stats = response.data;
                        
                        // Update member stats
                        updateStatDisplay('totalMembers', stats.member_stats.total_members, 'members');
                        $('#memberProgress').html(stats.member_stats.total_members > 0 ? 
                            '<i class="fas fa-users text-info"></i> ' + stats.member_stats.active_members + ' active' : 
                            '<i class="fas fa-exclamation-circle text-warning"></i> No members');
                        
                        // Update event stats
                        updateStatDisplay('totalEvents', stats.event_stats.total_events, 'events');
                        $('#eventProgress').html(stats.event_stats.total_events > 0 ? 
                            '<i class="fas fa-calendar-check text-success"></i> ' + stats.event_stats.upcoming_events + ' upcoming' : 
                            '<i class="fas fa-exclamation-circle text-warning"></i> No events');
                        
                        // Update finance stats
                        updateStatDisplay('totalIncome', stats.finance_stats.total_income, 'finance', true);
                        $('#incomeProgress').html(stats.finance_stats.total_income > 0 ? 
                            '<i class="fas fa-money-bill-wave text-success"></i> From ' + stats.finance_stats.total_transactions + ' transactions' : 
                            '<i class="fas fa-exclamation-circle text-warning"></i> No transactions');
                        
                        // Update pending approvals
                        const pendingCount = parseInt(stats.member_stats.pending_members || 0);
                        updateStatDisplay('pendingApprovals', pendingCount, 'approvals');
                        $('#approvalProgress').html(pendingCount > 0 ? 
                            '<i class="fas fa-user-clock text-warning"></i> Requiring attention' : 
                            '<i class="fas fa-check-circle text-success"></i> All up to date');
                        
                        // Update expense stats if they exist
                        if (stats.expense_stats) {
                            updateStatDisplay('totalExpenses', stats.expense_stats.total_expenses_amount, 'expenses', true);
                            updateStatDisplay('pendingExpenses', stats.expense_stats.pending_expenses, 'expenses');
                        }
                        
                        // Update Member Analytics Chart Statistics
                        updateMemberAnalytics(stats);
                        
                        // Update Financial Analytics Statistics
                        updateFinancialAnalytics(stats);
                    } else {
                        console.error('Error loading dashboard stats:', response.message);
                        console.error('Debug info:', response.debug);
                        // Show error message
                        if (typeof toastr !== 'undefined') {
                            toastr.error('Failed to load dashboard statistics. Please try refreshing the page.');
                        }
                        setNoDataValues();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error loading dashboard stats:', error);
                    console.error('XHR:', xhr);
                    console.error('Status:', status);
                    console.error('Response Text:', xhr.responseText);
                    
                    // Show error message
                    if (typeof toastr !== 'undefined') {
                        toastr.error('Failed to connect to the server. Please check your connection and try again.');
                    }
                    setNoDataValues();
                }
            });
        }
        
        // Function to set "No Data" values when data isn't available
        function setNoDataValues() {
            // Member stats
            $('#totalMembers').html('0 <small class="text-muted">members</small>');
            $('#memberProgress').html('<i class="fas fa-exclamation-circle text-warning"></i> No data available');
            
            // Event stats
            $('#totalEvents').html('0 <small class="text-muted">events</small>');
            $('#eventProgress').html('<i class="fas fa-exclamation-circle text-warning"></i> No data available');
            
            // Finance stats
            $('#totalIncome').html('₹0 <small class="text-muted">income</small>');
            $('#incomeProgress').html('<i class="fas fa-exclamation-circle text-warning"></i> No data available');
            
            // Pending approvals
            $('#pendingApprovals').html('0 <small class="text-muted">pending</small>');
            $('#approvalProgress').html('<i class="fas fa-exclamation-circle text-warning"></i> No data available');
            
            // Expense stats
            $('#totalExpenses').html('₹0 <small class="text-muted">expenses</small>');
            $('#pendingExpenses').text('0');
        }
        
        // Helper function to update display with proper formatting
        function updateStatDisplay(elementId, value, type, isCurrency = false) {
            const element = $('#' + elementId);
            
            // If value is zero or null, display appropriate message
            if (value === 0 || value === null) {
                if (elementId.startsWith('total')) {
                    // For main stat boxes, show "No [Type]" with explanation
                    if (isCurrency) {
                        element.html('₹0 <small class="text-muted">no data</small>');
                    } else {
                        element.html('0 <small class="text-muted">no data</small>');
                    }
                } else {
                    // For secondary stats, just show zero
                    element.text('0');
                }
            } else {
                // Format and display actual data
                if (isCurrency) {
                    element.html('₹' + formatCurrency(value) + 
                        (elementId === 'totalIncome' ? ' <small class="text-muted">collected</small>' : ''));
                } else {
                    if (elementId === 'totalMembers') {
                        element.html(value + ' <small class="text-muted">registered</small>');
                    } else if (elementId === 'totalEvents') {
                        element.html(value + ' <small class="text-muted">planned</small>');
                    } else if (elementId === 'pendingApprovals') {
                        element.html(value + ' <small class="text-muted">waiting</small>');
                    } else {
                        element.text(value);
                    }
                }
            }
        }
        
        // Function to update Member Analytics section with real data
        function updateMemberAnalytics(stats) {
            const memberStats = stats.member_stats || {};
            const financeStats = stats.finance_stats || {};
            
            // Calculate new members (recent members from current month/period)
            const newMembers = memberStats.new_members_this_month || memberStats.total_members || 0;
            const previousMembers = memberStats.previous_month_members || 0;
            const membersGrowth = calculateGrowthPercentage(newMembers, previousMembers);
            
            // Pending members
            const pendingMembers = memberStats.pending_members || 0;
            const previousPending = memberStats.previous_pending || 0;
            const pendingGrowth = calculateGrowthPercentage(pendingMembers, previousPending);
            
            // Approval rate calculation
            const totalApplications = (memberStats.total_members || 0) + (memberStats.pending_members || 0);
            const approvedMembers = memberStats.total_members || 0;
            const approvalRate = totalApplications > 0 ? Math.round((approvedMembers / totalApplications) * 100) : 0;
            const previousApprovalRate = memberStats.previous_approval_rate || approvalRate;
            const approvalGrowth = approvalRate - previousApprovalRate;
            
            // Revenue calculation
            const currentRevenue = financeStats.total_income || 0;
            const previousRevenue = financeStats.previous_income || 0;
            const revenueGrowth = calculateGrowthPercentage(currentRevenue, previousRevenue);
            
            // Update new members
            $('#newMembersCount').text(newMembers);
            updateGrowthIndicator('newMembersGrowth', membersGrowth);
            
            // Update pending
            $('#pendingCount').text(pendingMembers);
            updateGrowthIndicator('pendingGrowth', pendingGrowth, true); // true = reverse colors (down is good for pending)
            
            // Update approval rate
            $('#approvalRateValue').text(approvalRate + '%');
            updateGrowthIndicator('approvalRateGrowth', approvalGrowth);
            
            // Update revenue
            $('#revenueValue').text('₹' + formatCurrency(currentRevenue));
            updateGrowthIndicator('revenueGrowth', revenueGrowth);
        }
        
        // Helper function to calculate growth percentage
        function calculateGrowthPercentage(current, previous) {
            if (previous === 0) return current > 0 ? 100 : 0;
            return Math.round(((current - previous) / previous) * 100);
        }
        
        // Helper function to update growth indicators
        function updateGrowthIndicator(elementId, growthPercent, reverse = false) {
            const element = $('#' + elementId);
            const isPositive = growthPercent >= 0;
            
            // For pending members, reverse the color logic (decrease is good)
            const colorClass = reverse ? 
                (isPositive ? 'text-warning' : 'text-success') :
                (isPositive ? 'text-success' : 'text-danger');
            
            const icon = isPositive ? 'fa-caret-up' : 'fa-caret-down';
            const sign = isPositive ? '+' : '';
            
            element.removeClass('text-success text-warning text-danger text-info')
                   .addClass(colorClass)
                   .html(`<i class="fas ${icon}"></i> ${sign}${growthPercent}%`);
        }
        
        // Function to update Financial Analytics section with real data
        function updateFinancialAnalytics(stats) {
            const financeStats = stats.finance_stats || {};
            const expenseStats = stats.expense_stats || {};
            
            // Get financial data
            const totalIncome = financeStats.total_income || 0;
            const totalExpenses = expenseStats.total_expenses_amount || 0;
            const netProfit = totalIncome - totalExpenses;
            const thisMonthIncome = financeStats.current_month_income || 0;
            
            // Update the values
            $('#totalIncomeValue').html('₹' + formatCurrency(totalIncome));
            $('#totalExpensesValue').html('₹' + formatCurrency(totalExpenses));
            $('#netProfitValue').html('₹' + formatCurrency(netProfit));
            $('#thisMonthValue').html('₹' + formatCurrency(thisMonthIncome));
            
            // Update sparkbars with real trend data
            updateSparkbars(stats);
        }
        
        // Function to update sparkbar charts with real trend data
        function updateSparkbars(stats) {
            // Get trend data (last 7 periods - days/weeks/months)
            const financeStats = stats.finance_stats || {};
            const expenseStats = stats.expense_stats || {};
            
            // Income trend (last 7 periods)
            const incomeTrend = financeStats.income_trend || generateDefaultTrend(financeStats.total_income);
            $('#incomeSparkbar').attr('data-sparkline', incomeTrend.join(','));
            
            // Expenses trend
            const expensesTrend = expenseStats.expenses_trend || generateDefaultTrend(expenseStats.total_expenses_amount);
            $('#expensesSparkbar').attr('data-sparkline', expensesTrend.join(','));
            
            // Profit trend (calculated from income - expenses for each period)
            const profitTrend = incomeTrend.map((income, index) => {
                const expense = expensesTrend[index] || 0;
                return Math.max(0, income - expense);
            });
            $('#profitSparkbar').attr('data-sparkline', profitTrend.join(','));
            
            // Monthly trend (last 7 months)
            const monthlyTrend = financeStats.monthly_trend || generateDefaultTrend(financeStats.current_month_income);
            $('#monthlySparkbar').attr('data-sparkline', monthlyTrend.join(','));
            
            // Reinitialize sparklines if available
            if (typeof $.fn.sparkline !== 'undefined') {
                $('.sparkbar').each(function() {
                    const data = $(this).attr('data-sparkline');
                    if (data) {
                        const values = data.split(',').map(v => parseInt(v) || 0);
                        $(this).sparkline(values, {
                            type: 'bar',
                            height: 20,
                            barColor: $(this).data('color') || '#007bff',
                            barWidth: 3,
                            barSpacing: 1
                        });
                    }
                });
            }
        }
        
        // Generate default trend data when real trend is not available
        function generateDefaultTrend(baseValue, periods = 7) {
            if (!baseValue || baseValue === 0) {
                return new Array(periods).fill(0);
            }
            
            // Generate realistic trend around the base value
            const trend = [];
            const avgPerPeriod = baseValue / periods;
            
            for (let i = 0; i < periods; i++) {
                // Add some realistic variation (±30%)
                const variation = (Math.random() - 0.5) * 0.6; // -30% to +30%
                const value = Math.max(0, Math.round(avgPerPeriod * (1 + variation)));
                trend.push(value);
            }
            
            return trend;
        }

        function initializeDataTables() {
            // Initialize Members DataTable
            const membersTable = $('#membersTable').DataTable({
                ajax: {
                    url: 'api/datatable.php?table=members&recent=true',
                    dataSrc: function(json) {
                        if (json.success && json.data && json.data.length > 0) {
                            return json.data;
                        } else if (!json.success && json.message === 'Unauthorized access') {
                            // Handle authentication error
                            window.location.href = 'login.php';
                            return [];
                        } else {
                            // Handle empty data
                            $('#membersTableContainer').html(
                                '<div class="alert alert-info m-3">' +
                                '<i class="fas fa-info-circle mr-2"></i> No members found in the database. ' +
                                '<a href="member-registration.php" class="alert-link">Add a new member</a> to get started.' +
                                '</div>'
                            );
                            return [];
                        }
                    },
                    error: function(xhr, error, thrown) {
                        console.error('Error loading members data:', error);
                        $('#membersTableContainer').html(
                            '<div class="alert alert-danger m-3">' +
                            '<i class="fas fa-exclamation-circle mr-2"></i> Failed to load member data. ' +
                            'Please try refreshing the page.' +
                            '</div>'
                        );
                        
                        // Try to parse the response
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.message === 'Unauthorized access') {
                                window.location.href = 'login.php';
                            }
                        } catch (e) {
                            console.error('Invalid JSON response from server');
                        }
                    }
                },
                columns: [
                    { 
                        data: 'kso_id',
                        render: function(data) {
                            return '<span class="badge badge-info">' + data + '</span>';
                        }
                    },
                    { 
                        data: null,
                        render: function(data) {
                            return data.first_name + ' ' + data.last_name;
                        }
                    },
                    { 
                        data: 'status',
                        render: function(data) {
                            let badgeClass = 'secondary';
                            if (data === 'active') badgeClass = 'success';
                            if (data === 'pending') badgeClass = 'warning';
                            if (data === 'approved') badgeClass = 'info';
                            if (data === 'suspended') badgeClass = 'danger';
                            return '<span class="badge badge-' + badgeClass + '">' + data + '</span>';
                        }
                    },
                    {
                        data: 'id',
                        render: function(data) {
                            return '<div class="btn-group">' +
                                   '<a href="members.php?id=' + data + '" class="btn btn-xs btn-info"><i class="fas fa-eye"></i></a>' +
                                   '</div>';
                        }
                    }
                ],
                pageLength: 5,
                lengthChange: false,
                searching: true,
                ordering: true,
                info: false,
                paging: true,
                language: {
                    emptyTable: '<div class="text-center text-muted p-3"><i class="fas fa-users fa-3x mb-3"></i><br><strong>No members found</strong><br><small>No members have been registered yet</small></div>',
                    zeroRecords: '<div class="text-center text-muted p-3"><i class="fas fa-search fa-2x mb-2"></i><br><strong>No matching members</strong><br><small>Try adjusting your filter</small></div>',
                    loadingRecords: '<div class="text-center p-3"><i class="fas fa-spinner fa-spin"></i> Loading members...</div>'
                }
            });

            // Initialize Events DataTable
            const eventsTable = $('#eventsTable').DataTable({
                ajax: {
                    url: 'api/fetch_events.php',
                    data: function(d) {
                        d.filter = $('#eventFilter').val() || 'upcoming';
                    },
                    dataSrc: function(json) {
                        if (json.success && json.data && json.data.length > 0) {
                            return json.data;
                        } else if (!json.success && json.message === 'Unauthorized access') {
                            window.location.href = 'login.php';
                            return [];
                        } else {
                            // Handle empty data
                            $('#eventsTableContainer').html(
                                '<div class="alert alert-info m-3">' +
                                '<i class="fas fa-info-circle mr-2"></i> No events found in the database. ' +
                                '<a href="events.php" class="alert-link">Add a new event</a> to get started.' +
                                '</div>'
                            );
                            return [];
                        }
                    },
                    error: function(xhr, error, thrown) {
                        console.error('Events DataTable AJAX Error:', error, thrown);
                        console.error('Response:', xhr.responseText);
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.message === 'Unauthorized access') {
                                window.location.href = 'login.php';
                            }
                        } catch (e) {
                            console.error('Invalid JSON response from server');
                        }
                        
                        // Show error message to user
                        $('#eventsTableContainer').html(
                            '<div class="alert alert-danger m-3">' +
                            '<i class="fas fa-exclamation-circle mr-2"></i> Failed to load event data. ' +
                            'Please try refreshing the page.' +
                            '</div>'
                        );
                    }
                },
                columns: [
                    { data: 'title', render: function(data) { return `<strong>${data}</strong>`; } },
                    {
                        data: 'event_date',
                        render: function(data) {
                            return `<small>${formatDate(data)}</small>`;
                        }
                    },
                    {
                        data: 'status',
                        render: function(data) {
                            const statusClass = data === 'active' ? 'success' : 
                                              data === 'upcoming' ? 'info' : 'secondary';
                            const statusText = data.charAt(0).toUpperCase() + data.slice(1);
                            return `<span class="badge badge-${statusClass}">${statusText}</span>`;
                        }
                    },
                    {
                        data: 'attendees',
                        render: function(data) {
                            return `<span class="badge badge-primary">${data || 0}</span>`;
                        }
                    }
                ],
                pageLength: 5,
                lengthChange: false,
                searching: true,
                ordering: true,
                info: false,
                paging: true,
                language: {
                    emptyTable: '<div class="text-center text-muted p-3"><i class="fas fa-calendar fa-3x mb-3"></i><br><strong>No events found</strong><br><small>No events have been scheduled yet</small></div>',
                    zeroRecords: '<div class="text-center text-muted p-3"><i class="fas fa-search fa-2x mb-2"></i><br><strong>No matching events</strong><br><small>Try changing the filter</small></div>',
                    loadingRecords: '<div class="text-center p-3"><i class="fas fa-spinner fa-spin"></i> Loading events...</div>'
                }
            });

            // Initialize Transactions DataTable
            const transactionsTable = $('#transactionsTable').DataTable({
                ajax: {
                    url: 'api/finance/fetch_transactions.php',
                    data: function(d) {
                        d.filter = $('#transactionFilter').val();
                    },
                    dataSrc: function(json) {
                        if (json.success && json.data && json.data.length > 0) {
                            return json.data;
                        } else if (!json.success && json.message && json.message.includes('Unauthorized')) {
                            window.location.href = 'login.php';
                            return [];
                        } else {
                            // Handle empty data
                            $('#transactionsTableContainer').html(
                                '<div class="alert alert-info m-3">' +
                                '<i class="fas fa-info-circle mr-2"></i> No transactions found in the database. ' +
                                '<a href="finance.php" class="alert-link">Add a new transaction</a> to get started.' +
                                '</div>'
                            );
                            return [];
                        }
                    },
                    error: function(xhr, error, thrown) {
                        console.error('Transactions DataTable AJAX Error:', error, thrown);
                        console.error('Response:', xhr.responseText);
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.message && response.message.includes('Unauthorized')) {
                                window.location.href = 'login.php';
                            }
                        } catch (e) {
                            console.error('Invalid JSON response from server');
                        }
                        
                        // Show error message to user
                        $('#transactionsTableContainer').html(
                            '<div class="alert alert-danger m-3">' +
                            '<i class="fas fa-exclamation-circle mr-2"></i> Failed to load transaction data. ' +
                            'Please try refreshing the page.' +
                            '</div>'
                        );
                    }
                },
                columns: [
                    { data: 'member_name', defaultContent: 'N/A' },
                    {
                        data: 'type',
                        render: function(data) {
                            const typeClass = data === 'income' ? 'success' : 'danger';
                            return `<span class="badge badge-${typeClass}">${data}</span>`;
                        }
                    },
                    {
                        data: 'amount',
                        render: function(data) {
                            return `<strong>₹${parseFloat(data).toLocaleString()}</strong>`;
                        }
                    },
                    {
                        data: 'status',
                        render: function(data) {
                            const statusClass = data === 'completed' ? 'success' : 
                                              data === 'pending' ? 'warning' : 'danger';
                            return `<span class="badge badge-${statusClass}">${data}</span>`;
                        }
                    },
                    {
                        data: 'created_at',
                        render: function(data) {
                            return `<small>${formatDate(data)}</small>`;
                        }
                    }
                ],
                pageLength: 5,
                lengthChange: false,
                searching: true,
                ordering: true,
                info: false,
                paging: true,
                language: {
                    emptyTable: '<div class="text-center text-muted p-3"><i class="fas fa-money-bill-wave fa-3x mb-3"></i><br><strong>No transactions found</strong><br><small>No financial transactions recorded yet</small></div>',
                    zeroRecords: '<div class="text-center text-muted p-3"><i class="fas fa-search fa-2x mb-2"></i><br><strong>No matching transactions</strong><br><small>Try adjusting your filter</small></div>',
                    loadingRecords: '<div class="text-center p-3"><i class="fas fa-spinner fa-spin"></i> Loading transactions...</div>'
                }
            });

            // Filter event handlers
            $('#memberStatusFilter').on('change', function() {
                const filterValue = this.value;
                membersTable.column(2).search(filterValue ? '^' + filterValue + '$' : '', true, false).draw();
            });

            $('#eventFilter').on('change', function() {
                eventsTable.ajax.reload();
            });

            $('#transactionFilter').on('change', function() {
                transactionsTable.ajax.reload();
            });
        }

        function initializeMemberChart() {
            const chartCanvas = document.getElementById('membershipChart');
            if (!chartCanvas) {
                console.warn('Membership chart canvas not found');
                return;
            }

            $.ajax({
                url: 'api/dashboard/fetch_dashboard_stats.php?chart=members_growth',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data && response.data.chart_data) {
                        const chartData = response.data.chart_data;
                        
                        const ctx = chartCanvas.getContext('2d');
                        new Chart(ctx, {
                            type: 'line',
                            data: {
                                labels: chartData.labels,
                                datasets: [{
                                    label: 'New Members',
                                    data: chartData.values,
                                    borderColor: '#007bff',
                                    backgroundColor: 'rgba(0, 123, 255, 0.1)',
                                    borderWidth: 2,
                                    fill: true,
                                    tension: 0.3
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                interaction: {
                                    intersect: false,
                                    mode: 'index'
                                },
                                layout: {
                                    padding: {
                                        top: 10,
                                        bottom: 10
                                    }
                                },
                                scales: {
                                    y: {
                                        beginAtZero: true,
                                        ticks: {
                                            precision: 0,
                                            maxTicksLimit: 6
                                        },
                                        grid: {
                                            display: true,
                                            color: 'rgba(0,0,0,0.1)'
                                        }
                                    },
                                    x: {
                                        grid: {
                                            display: false
                                        }
                                    }
                                },
                                plugins: {
                                    legend: {
                                        display: true,
                                        position: 'top',
                                        labels: {
                                            boxWidth: 12,
                                            padding: 15
                                        }
                                    },
                                    tooltip: {
                                        mode: 'index',
                                        intersect: false,
                                        backgroundColor: 'rgba(0,0,0,0.8)',
                                        titleColor: 'white',
                                        bodyColor: 'white'
                                    }
                                }
                            }
                        });
                    } else {
                        console.error('Error loading chart data:', response.message || 'No chart data available');
                        $('#membershipChart').parent().html('<div class="alert alert-warning">Chart data not available</div>');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading chart data:', error);
                    $('#membershipChart').parent().html('<div class="alert alert-danger">Failed to load chart data</div>');
                }
            });
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('en-IN', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        }
        
        // Helper function to format currency consistently
        function formatCurrency(amount) {
            // Convert to number, handle null or undefined
            const numAmount = parseFloat(amount) || 0;
            
            // Format with Indian numbering system (lakhs, crores)
            return numAmount.toLocaleString('en-IN', {
                maximumFractionDigits: 2,
                minimumFractionDigits: 0
            });
        }

        // Initialize notification system if admin is logged in
        <?php if (isset($_SESSION['admin_id'])): ?>
        // Get settings from server or use defaults
        const notificationSettings = {
            userId: <?php echo $_SESSION['admin_id']; ?>,
            userType: 'admin',
            soundEnabled: <?php echo (isset($_SESSION['notification_sound']) && $_SESSION['notification_sound'] == 0) ? 'false' : 'true'; ?>,
            browserNotificationsEnabled: <?php echo (isset($_SESSION['browser_notifications']) && $_SESSION['browser_notifications'] == 0) ? 'false' : 'true'; ?>,
            websocketEnabled: <?php echo (isset($_SESSION['websocket_enabled']) && $_SESSION['websocket_enabled'] == 0) ? 'false' : 'true'; ?>
        };
        
        if (typeof initNotificationSystem === 'function') {
            initNotificationSystem(notificationSettings);
        }
        <?php endif; ?>
    });
</script>
</div>

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