<?php
define('SECURE_ACCESS', true);

$pageTitle = "Dashboard";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

$user = getCurrentUser();
if ($user && $pdo) {
    try {
        $stmt_u = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt_u->execute([$user['id']]);
        $db_user = $stmt_u->fetch(PDO::FETCH_ASSOC);
        if ($db_user) {
            $user = array_merge($user, $db_user);
        }
    } catch (PDOException $e) {
        // Ignore
    }
}

// Fetch User In-App Notifications
$user_notifications = [];
try {
    $stmt_notif = $pdo->prepare("
        SELECT * FROM notifications 
        WHERE user_id = ? AND channels_sent LIKE '%in_app%' 
        ORDER BY created_at DESC 
        LIMIT 10
    ");
    $stmt_notif->execute([$user['id']]);
    $user_notifications = $stmt_notif->fetchAll();
} catch (PDOException $e) {
    // Ignore
}

// Handle Mark all as read action
if (isset($_GET['action']) && $_GET['action'] === 'read_all_notifications') {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: dashboard");
        exit();
    }
    try {
        $stmt_read = $pdo->prepare("UPDATE notifications SET is_read = TRUE WHERE user_id = ? AND channels_sent LIKE '%in_app%'");
        $stmt_read->execute([$user['id']]);
        $_SESSION['flash_success'] = "All notifications marked as read.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to mark notifications as read.";
    }
    header("Location: dashboard");
    exit();
}

// Common variables
$total_users = 0;
$total_events = 0;
$upcoming_events = [];
$employee_code = 'N/A';
$designation_title = 'Associate / Standard Rank';

// Admin KPIs
$admin_total_revenue = 0.00;
$admin_total_gst = 0.00;
$admin_pending_kyc = 0;
$admin_pending_payouts = 0;
$total_registrations = 0;
$admin_total_commissions = 0.00;
$admin_total_signup_bonus = 0.00;
$admin_total_referral_bonus = 0.00;

// Organizer KPIs
$organizer_events_count = 0;
$organizer_registrations_count = 0;
$organizer_total_capacity = 0;
$organizer_estimated_revenue = 0.00;
$organizer_recent_registrants = [];

// Speaker KPIs
$speaker_sessions_scheduled = 0;
$speaker_audience_reach = 0;
$speaker_upcoming_sessions = 0;
$speaker_past_sessions = 0;
$speaker_profile = null;
$speaker_agenda_sessions = [];

// Sponsor KPIs
$sponsor_events_count = 0;
$sponsor_audience_reach = 0;
$sponsor_gold_tier = 0;
$sponsor_silver_tier = 0;
$sponsor_bronze_tier = 0;
$sponsor_profile = null;
$sponsor_portfolio = [];

// User MLM KPIs
$my_registrations = 0;
$my_designation = null;
$my_referrer = null;
$my_parent = null;
$total_earnings = 0.00;
$total_withdrawn = 0.00;
$total_pending = 0.00;
$available_balance = 0.00;
$earnings_logs = [];
$my_referrals_count = 0;
$mlm_level_earnings = []; // Level breakdown
$user_commissions = 0.00;
$user_signup_bonus = 0.00;
$user_referral_bonus = 0.00;

try {
    // 1. Fetch upcoming events (common widget on dashboard for general reference)
    $sql = "SELECT e.id, e.title, e.description, e.start_date, e.end_date, e.location, e.capacity, 
                   u.username as creator_name, COUNT(r.id) as attendee_count 
            FROM events e 
            LEFT JOIN users u ON e.created_by = u.id 
            LEFT JOIN registrations r ON e.id = r.event_id 
            WHERE e.end_date >= NOW()";
    if ($user['role'] !== 'admin' && $user['role'] !== 'organizer') {
        $sql .= " AND e.status = 'published'";
    }
    $sql .= " GROUP BY e.id, u.username 
            ORDER BY e.start_date ASC 
            LIMIT 3";
    $stmt = $pdo->query($sql);
    $upcoming_events = $stmt->fetchAll();

    // 2. Fetch overall basic counts
    $total_users = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    if ($user['role'] !== 'admin' && $user['role'] !== 'organizer') {
        $total_events = $pdo->query("SELECT COUNT(*) FROM events WHERE status = 'published'")->fetchColumn();
    } else {
        $total_events = $pdo->query("SELECT COUNT(*) FROM events")->fetchColumn();
    }

    // Fetch full user details from database including employee code and designation
    $stmt_user_info = $pdo->prepare("
        SELECT u.employee_code, d.title as designation_title 
        FROM users u 
        LEFT JOIN designations d ON u.designation_id = d.id 
        WHERE u.id = ?
    ");
    $stmt_user_info->execute([$user['id']]);
    $db_user = $stmt_user_info->fetch(PDO::FETCH_ASSOC);
    $employee_code = $db_user['employee_code'] ?? 'N/A';
    $designation_title = $db_user['designation_title'] ?? 'Associate / Standard Rank';

    // Date Range Formatter Helper
    if (!function_exists('formatEventDateRange')) {
        function formatEventDateRange($start, $end) {
            $startDate = strtotime($start);
            $endDate = strtotime($end);
            
            if (date('Y-m-d', $startDate) === date('Y-m-d', $endDate)) {
                return date('F d, Y \a\t g:i A', $startDate) . ' - ' . date('g:i A', $endDate);
            } else {
                return date('F d, Y \a\t g:i A', $startDate) . ' to ' . date('F d, Y \a\t g:i A', $endDate);
            }
        }
    }

    // 3. Populate statistics conditionally by User Role
    if ($user['role'] === 'admin') {
        // Admin Financials
        $stmt_rev = $pdo->query("SELECT COALESCE(SUM(base_price), 0.00) FROM registrations");
        $admin_total_revenue = (float)$stmt_rev->fetchColumn();

        $stmt_gst = $pdo->query("SELECT COALESCE(SUM(gst_amount), 0.00) FROM registrations");
        $admin_total_gst = (float)$stmt_gst->fetchColumn();

        // KYC Backlog
        $stmt_kyc = $pdo->query("SELECT COUNT(*) FROM kyc_records WHERE doc1_status = 'pending' OR doc2_status = 'pending'");
        $admin_pending_kyc = (int)$stmt_kyc->fetchColumn();

        // Payout Backlog
        $stmt_pay = $pdo->query("SELECT COUNT(*) FROM payouts WHERE status = 'pending'");
        $admin_pending_payouts = (int)$stmt_pay->fetchColumn();

        $total_registrations = $pdo->query("SELECT COUNT(*) FROM registrations")->fetchColumn();

        // Platform-wide Bonus Distribution Details
        $admin_total_commissions = (float)$pdo->query("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE type = 'commission'")->fetchColumn();
        $admin_total_signup_bonus = (float)$pdo->query("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE type = 'signup_bonus'")->fetchColumn();
        $admin_total_referral_bonus = (float)$pdo->query("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE type = 'referral_bonus'")->fetchColumn();

        // Advanced Admin KPIs
        $admin_kyc_stats = $pdo->query("
            SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN doc1_status = 'approved' AND doc2_status = 'approved' AND bank_status = 'verified' THEN 1 ELSE 0 END) as approved
            FROM kyc_records
        ")->fetch();
        $admin_kyc_rate = ($admin_kyc_stats && $admin_kyc_stats['total'] > 0) ? round(($admin_kyc_stats['approved'] / $admin_kyc_stats['total']) * 100, 1) : 0.0;

        $admin_payout_stats = $pdo->query("
            SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid
            FROM payouts
        ")->fetch();
        $admin_payout_rate = ($admin_payout_stats && $admin_payout_stats['total'] > 0) ? round(($admin_payout_stats['paid'] / $admin_payout_stats['total']) * 100, 1) : 0.0;

        $admin_roles_data = $pdo->query("SELECT role, COUNT(*) as count FROM users GROUP BY role")->fetchAll(PDO::FETCH_KEY_PAIR);

        $admin_reg_trend = $pdo->query("
            SELECT DATE(registered_at) as date, COUNT(*) as count, SUM(total_payable) as revenue 
            FROM registrations 
            WHERE registered_at >= NOW() - INTERVAL '15 days' 
            GROUP BY DATE(registered_at) 
            ORDER BY DATE(registered_at) ASC
        ")->fetchAll();

        // Format for Chart.js
        $admin_reg_dates = [];
        $admin_reg_counts = [];
        $admin_reg_revs = [];
        foreach ($admin_reg_trend as $row) {
            $admin_reg_dates[] = date('M d', strtotime($row['date']));
            $admin_reg_counts[] = (int)$row['count'];
            $admin_reg_revs[] = (float)$row['revenue'];
        }

        $admin_roles_labels = [];
        $admin_roles_counts = [];
        foreach ($admin_roles_data as $role_key => $count) {
            $admin_roles_labels[] = ucfirst($role_key);
            $admin_roles_counts[] = (int)$count;
        }

    } elseif ($user['role'] === 'organizer') {
        // Events Hosted
        $stmt_org = $pdo->prepare("SELECT COUNT(*) FROM events WHERE created_by = ?");
        $stmt_org->execute([$user['id']]);
        $organizer_events_count = (int)$stmt_org->fetchColumn();

        // Total registrations and revenue for organizer's events
        $stmt_org_stats = $pdo->prepare("
            SELECT COUNT(r.id) as registrations, COALESCE(SUM(r.base_price), 0.00) as revenue, COALESCE(SUM(e.capacity), 0) as capacity
            FROM events e
            LEFT JOIN registrations r ON e.id = r.event_id
            WHERE e.created_by = ?
        ");
        $stmt_org_stats->execute([$user['id']]);
        $org_stats = $stmt_org_stats->fetch();
        $organizer_registrations_count = (int)($org_stats['registrations'] ?? 0);
        $organizer_estimated_revenue = (float)($org_stats['revenue'] ?? 0.00);
        $organizer_total_capacity = (int)($org_stats['capacity'] ?? 0);

        // Recent registrations list for their events
        $stmt_org_recent = $pdo->prepare("
            SELECT r.registered_at, u.username, u.email, e.title as event_title, r.total_payable
            FROM registrations r
            JOIN events e ON r.event_id = e.id
            JOIN users u ON r.user_id = u.id
            WHERE e.created_by = ?
            ORDER BY r.registered_at DESC
            LIMIT 5
        ");
        $stmt_org_recent->execute([$user['id']]);
        $organizer_recent_registrants = $stmt_org_recent->fetchAll(PDO::FETCH_ASSOC);

        // Advanced Organizer KPIs & Chart data
        $stmt_org_trend = $pdo->prepare("
            SELECT DATE(r.registered_at) as date, COUNT(r.id) as count, SUM(r.total_payable) as revenue 
            FROM registrations r 
            JOIN events e ON r.event_id = e.id 
            WHERE e.created_by = ? AND r.registered_at >= NOW() - INTERVAL '15 days' 
            GROUP BY DATE(r.registered_at) 
            ORDER BY DATE(r.registered_at) ASC
        ");
        $stmt_org_trend->execute([$user['id']]);
        $organizer_reg_trend = $stmt_org_trend->fetchAll();

        $stmt_org_events = $pdo->prepare("
            SELECT e.title, e.capacity, COUNT(r.id) as registered_count, COALESCE(SUM(r.total_payable), 0.00) as revenue 
            FROM events e 
            LEFT JOIN registrations r ON e.id = r.event_id AND r.status = 'registered'
            WHERE e.created_by = ? 
            GROUP BY e.id, e.title, e.capacity 
            ORDER BY registered_count DESC 
            LIMIT 5
        ");
        $stmt_org_events->execute([$user['id']]);
        $organizer_events_data = $stmt_org_events->fetchAll();

        $stmt_org_avg_price = $pdo->prepare("SELECT COALESCE(AVG(price), 0.00) FROM events WHERE created_by = ?");
        $stmt_org_avg_price->execute([$user['id']]);
        $organizer_avg_ticket_price = (float)$stmt_org_avg_price->fetchColumn();

        // Format for Chart.js
        $organizer_reg_dates = [];
        $organizer_reg_counts = [];
        $organizer_reg_revs = [];
        foreach ($organizer_reg_trend as $row) {
            $organizer_reg_dates[] = date('M d', strtotime($row['date']));
            $organizer_reg_counts[] = (int)$row['count'];
            $organizer_reg_revs[] = (float)$row['revenue'];
        }

        $organizer_event_titles = [];
        $organizer_event_registrations = [];
        $organizer_event_capacities = [];
        foreach ($organizer_events_data as $row) {
            $organizer_event_titles[] = strlen($row['title']) > 15 ? substr($row['title'], 0, 15) . '...' : $row['title'];
            $organizer_event_registrations[] = (int)$row['registered_count'];
            $organizer_event_capacities[] = (int)$row['capacity'];
        }

    } elseif ($user['role'] === 'speaker') {
        // Fetch speaker profile
        $stmt_sp = $pdo->prepare("SELECT * FROM speaker_profiles WHERE user_id = ?");
        $stmt_sp->execute([$user['id']]);
        $speaker_profile = $stmt_sp->fetch(PDO::FETCH_ASSOC);

        if ($speaker_profile) {
            // Sessions Assigned
            $stmt_ag = $pdo->prepare("SELECT COUNT(*) FROM event_agendas WHERE speaker_profile_id = ?");
            $stmt_ag->execute([$speaker_profile['id']]);
            $speaker_sessions_scheduled = (int)$stmt_ag->fetchColumn();

            // Total Audience Exposure (Registrations sum across events they speak at)
            $stmt_aud = $pdo->prepare("
                SELECT COUNT(r.id) 
                FROM registrations r 
                WHERE r.event_id IN (
                    SELECT event_id FROM event_agendas WHERE speaker_profile_id = ?
                )
            ");
            $stmt_aud->execute([$speaker_profile['id']]);
            $speaker_audience_reach = (int)$stmt_aud->fetchColumn();

            // Scheduled Sessions list
            $stmt_sessions = $pdo->prepare("
                SELECT ea.*, e.title as event_title 
                FROM event_agendas ea
                JOIN events e ON ea.event_id = e.id
                WHERE ea.speaker_profile_id = ?
                ORDER BY ea.agenda_date ASC, ea.start_time ASC
                LIMIT 5
            ");
            $stmt_sessions->execute([$speaker_profile['id']]);
            $speaker_agenda_sessions = $stmt_sessions->fetchAll(PDO::FETCH_ASSOC);

            // Upcoming vs Past count
            $speaker_upcoming_sessions = 0;
            $speaker_past_sessions = 0;
            foreach ($speaker_agenda_sessions as $sess) {
                $sess_time = strtotime($sess['agenda_date'] . ' ' . $sess['start_time']);
                if ($sess_time >= time()) {
                    $speaker_upcoming_sessions++;
                } else {
                    $speaker_past_sessions++;
                }
            }

            // Advanced Speaker KPIs
            $stmt_sp_sessions = $pdo->prepare("
                SELECT ea.title as session_title, e.title as event_title, COUNT(r.id) as audience_count 
                FROM event_agendas ea 
                JOIN events e ON ea.event_id = e.id 
                LEFT JOIN registrations r ON e.id = r.event_id AND r.status = 'registered' 
                WHERE ea.speaker_profile_id = ? 
                GROUP BY ea.id, ea.title, e.title 
                ORDER BY audience_count DESC
                LIMIT 5
            ");
            $stmt_sp_sessions->execute([$speaker_profile['id']]);
            $speaker_audience_data = $stmt_sp_sessions->fetchAll();

            $stmt_sp_types = $pdo->prepare("
                SELECT e.payment_type, COUNT(ea.id) as session_count 
                FROM event_agendas ea 
                JOIN events e ON ea.event_id = e.id 
                WHERE ea.speaker_profile_id = ? 
                GROUP BY e.payment_type
            ");
            $stmt_sp_types->execute([$speaker_profile['id']]);
            $speaker_session_types = $stmt_sp_types->fetchAll(PDO::FETCH_KEY_PAIR);

            // Format for Chart.js
            $speaker_session_titles = [];
            $speaker_session_audience = [];
            foreach ($speaker_audience_data as $row) {
                $speaker_session_titles[] = strlen($row['session_title']) > 15 ? substr($row['session_title'], 0, 15) . '...' : $row['session_title'];
                $speaker_session_audience[] = (int)$row['audience_count'];
            }
        }

    } elseif ($user['role'] === 'sponsor') {
        // Fetch Sponsor Profile
        $stmt_spon = $pdo->prepare("SELECT * FROM sponsor_profiles WHERE user_id = ?");
        $stmt_spon->execute([$user['id']]);
        $sponsor_profile = $stmt_spon->fetch(PDO::FETCH_ASSOC);

        if ($sponsor_profile) {
            // Sponsored events count
            $stmt_spon_count = $pdo->prepare("SELECT COUNT(*) FROM event_sponsors WHERE sponsor_profile_id = ?");
            $stmt_spon_count->execute([$sponsor_profile['id']]);
            $sponsor_events_count = (int)$stmt_spon_count->fetchColumn();

            // Tiers breakdown
            $stmt_tiers = $pdo->prepare("SELECT tier, COUNT(*) as count FROM event_sponsors WHERE sponsor_profile_id = ? GROUP BY tier");
            $stmt_tiers->execute([$sponsor_profile['id']]);
            $tiers = $stmt_tiers->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
            $sponsor_gold_tier = (int)($tiers['Gold'] ?? 0);
            $sponsor_silver_tier = (int)($tiers['Silver'] ?? 0);
            $sponsor_bronze_tier = (int)($tiers['Bronze'] ?? 0);

            // Exposure Reach (Registrations sum on sponsored events)
            $stmt_exp = $pdo->prepare("
                SELECT COUNT(r.id)
                FROM registrations r
                WHERE r.event_id IN (
                    SELECT event_id FROM event_sponsors WHERE sponsor_profile_id = ?
                )
            ");
            $stmt_exp->execute([$sponsor_profile['id']]);
            $sponsor_audience_reach = (int)$stmt_exp->fetchColumn();

            // List of sponsored events
            $stmt_port = $pdo->prepare("
                SELECT e.*, es.tier
                FROM event_sponsors es
                JOIN events e ON es.event_id = e.id
                WHERE es.sponsor_profile_id = ?
                ORDER BY e.start_date ASC
                LIMIT 5
            ");
            $stmt_port->execute([$sponsor_profile['id']]);
            $sponsor_portfolio = $stmt_port->fetchAll(PDO::FETCH_ASSOC);

            // Advanced Sponsor KPIs
            $stmt_spon_events = $pdo->prepare("
                SELECT e.title, es.tier, COUNT(r.id) as attendee_count 
                FROM event_sponsors es 
                JOIN events e ON es.event_id = e.id 
                LEFT JOIN registrations r ON e.id = r.event_id AND r.status = 'registered' 
                WHERE es.sponsor_profile_id = ? 
                GROUP BY e.id, e.title, es.tier 
                ORDER BY attendee_count DESC
                LIMIT 5
            ");
            $stmt_spon_events->execute([$sponsor_profile['id']]);
            $sponsor_exposure_data = $stmt_spon_events->fetchAll();

            $sponsor_roi_index = 0;
            foreach ($sponsor_exposure_data as $exp) {
                $mult = 1.0;
                if ($exp['tier'] === 'Gold') $mult = 3.0;
                elseif ($exp['tier'] === 'Silver') $mult = 2.0;
                $sponsor_roi_index += $exp['attendee_count'] * $mult;
            }

            // Format for Chart.js
            $sponsor_event_titles = [];
            $sponsor_event_reach = [];
            foreach ($sponsor_exposure_data as $row) {
                $sponsor_event_titles[] = strlen($row['title']) > 15 ? substr($row['title'], 0, 15) . '...' : $row['title'];
                $sponsor_event_reach[] = (int)$row['attendee_count'];
            }
        }

    } else { // Standard Member ('user')
        // Matrix Information
        $stmt_matrix = $pdo->prepare("
            SELECT u.id, d.title as designation_title, ref.username as referrer_username, par.username as parent_username 
            FROM users u 
            LEFT JOIN designations d ON u.designation_id = d.id 
            LEFT JOIN users ref ON u.referrer_id = ref.id 
            LEFT JOIN users par ON u.parent_id = par.id 
            WHERE u.id = ?
        ");
        $stmt_matrix->execute([$user['id']]);
        $matrix_info = $stmt_matrix->fetch(PDO::FETCH_ASSOC);

        if ($matrix_info) {
            $my_designation = $matrix_info['designation_title'];
            $my_referrer = $matrix_info['referrer_username'];
            $my_parent = $matrix_info['parent_username'];
        }

        // Direct Referrals Count
        $stmt_ref_count = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ?");
        $stmt_ref_count->execute([$user['id']]);
        $my_referrals_count = (int)$stmt_ref_count->fetchColumn();

        // MLM Wallet stats
        $stmt_earn_sum = $pdo->prepare("SELECT SUM(amount) FROM earnings WHERE user_id = ?");
        $stmt_earn_sum->execute([$user['id']]);
        $total_earnings = (float)$stmt_earn_sum->fetchColumn();

        $stmt_pay_withdrawn = $pdo->prepare("SELECT SUM(amount) FROM payouts WHERE user_id = ? AND status = 'paid'");
        $stmt_pay_withdrawn->execute([$user['id']]);
        $total_withdrawn = (float)$stmt_pay_withdrawn->fetchColumn();

        $stmt_pay_pending = $pdo->prepare("SELECT SUM(amount) FROM payouts WHERE user_id = ? AND status = 'pending'");
        $stmt_pay_pending->execute([$user['id']]);
        $total_pending = (float)$stmt_pay_pending->fetchColumn();

        $available_balance = max(0.00, $total_earnings - ($total_withdrawn + $total_pending));

        // Earnings velocity: commission by level
        $stmt_levels = $pdo->prepare("
            SELECT level, SUM(amount) as level_sum, COUNT(*) as txn_count 
            FROM earnings 
            WHERE user_id = ? 
            GROUP BY level 
            ORDER BY level ASC
        ");
        $stmt_levels->execute([$user['id']]);
        $mlm_level_earnings = $stmt_levels->fetchAll(PDO::FETCH_ASSOC);

        // Earnings logs
        $stmt_earn_logs = $pdo->prepare("
            SELECT e.*, ev.title as event_title, b.username as buyer_name 
            FROM earnings e 
            LEFT JOIN events ev ON e.event_id = ev.id 
            LEFT JOIN users b ON e.buyer_id = b.id 
            WHERE e.user_id = ? 
            ORDER BY e.id DESC 
            LIMIT 10
        ");
        $stmt_earn_logs->execute([$user['id']]);
        $earnings_logs = $stmt_earn_logs->fetchAll(PDO::FETCH_ASSOC);

        // My registrations count
        $stmt_reg = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE user_id = ?");
        $stmt_reg->execute([$user['id']]);
        $my_registrations = (int)$stmt_reg->fetchColumn();

        // Separate User Bonus Distribution Details
        $stmt_comm = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ? AND type = 'commission'");
        $stmt_comm->execute([$user['id']]);
        $user_commissions = (float)$stmt_comm->fetchColumn();

        $stmt_signup = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ? AND type = 'signup_bonus'");
        $stmt_signup->execute([$user['id']]);
        $user_signup_bonus = (float)$stmt_signup->fetchColumn();

        $stmt_ref = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ? AND type = 'referral_bonus'");
        $stmt_ref->execute([$user['id']]);
        $user_referral_bonus = (float)$stmt_ref->fetchColumn();

        // Advanced MLM Associate KPIs
        $stmt_user_refs = $pdo->prepare("
            SELECT u.username, u.email, u.created_at, COUNT(r.id) as rsvp_count 
            FROM users u 
            LEFT JOIN registrations r ON u.id = r.user_id 
            WHERE u.referrer_id = ? 
            GROUP BY u.id, u.username, u.email, u.created_at 
            ORDER BY u.created_at DESC 
            LIMIT 5
        ");
        $stmt_user_refs->execute([$user['id']]);
        $my_referrals_detail = $stmt_user_refs->fetchAll();

        $stmt_user_earn_trend = $pdo->prepare("
            SELECT DATE(created_at) as date, SUM(amount) as daily_earnings 
            FROM earnings 
            WHERE user_id = ? AND created_at >= NOW() - INTERVAL '15 days' 
            GROUP BY DATE(created_at) 
            ORDER BY DATE(created_at) ASC
        ");
        $stmt_user_earn_trend->execute([$user['id']]);
        $user_earnings_trend = $stmt_user_earn_trend->fetchAll();

        // Format for Chart.js
        $user_earn_dates = [];
        $user_earn_values = [];
        foreach ($user_earnings_trend as $row) {
            $user_earn_dates[] = date('M d', strtotime($row['date']));
            $user_earn_values[] = (float)$row['daily_earnings'];
        }

        $user_level_labels = [];
        $user_level_values = [];
        foreach ($mlm_level_earnings as $row) {
            $user_level_labels[] = 'Level ' . $row['level'];
            $user_level_values[] = (float)$row['level_sum'];
        }
    }
} catch (PDOException $e) {
    $_SESSION['flash_error'] = "Error loading dashboard metrics: " . $e->getMessage();
}

include __DIR__ . '/../includes/header.php';
?>

<div class="row g-4 mb-4">
    <!-- Welcome card -->
    <div class="col-12">
        <div class="card border-0 shadow-sm bg-primary bg-opacity-10 text-primary-emphasis p-4 rounded-3 h-100">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-start gap-3">
                <div>
                    <h1 class="h2 fw-bold mb-1">Welcome, <?php echo htmlspecialchars(!empty($user['first_name']) ? $user['first_name'] : $user['username']); ?>!</h1>
                </div>
                <div>
                    <span class="text-muted font-monospace small"><i class="bi bi-clock-fill me-1"></i> Date: <?php echo date('Y-m-d'); ?></span>
                </div>
            </div>
        </div>
    </div>
    <!-- Employee ID & Designation Card -->
    <div class="col-12">
        <div class="card border-0 shadow-sm bg-light p-4 rounded-3">
            <?php
            $ref_url_raw = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/register/ref/" . urlencode($employee_code);
            ?>
            <div class="row g-4 align-items-center">
                <div class="col-12 col-md-4">
                    <div class="d-flex align-items-center">
                        <div class="p-2 bg-primary bg-opacity-10 text-primary rounded-circle me-3">
                            <i class="bi bi-person-badge fs-4"></i>
                        </div>
                        <div>
                            <small class="text-muted font-monospace text-uppercase d-block" style="font-size: 0.7rem;">Employee ID</small>
                            <strong class="text-dark font-monospace"><?php echo htmlspecialchars($employee_code); ?></strong>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-md-4 border-start-md border-top-sm pt-3 pt-md-0">
                    <small class="text-muted font-monospace text-uppercase d-block" style="font-size: 0.7rem;">Share Referral Link</small>
                    <div class="d-flex flex-wrap gap-1 mt-2">
                        <button type="button" class="btn btn-outline-success btn-xs" data-bs-toggle="modal" data-bs-target="#whatsappShareModal" title="Share via WhatsApp API"><i class="bi bi-whatsapp"></i></button>
                        <a href="https://t.me/share/url?url=<?php echo urlencode($ref_url_raw); ?>&text=<?php echo urlencode("Join EventPortal using my Employee Referral Code \"{$employee_code}\"!"); ?>" target="_blank" class="btn btn-outline-info btn-xs" title="Share via Telegram"><i class="bi bi-telegram"></i></a>
                        <a href="mailto:?subject=<?php echo urlencode("Invitation to Join EventPortal"); ?>&body=<?php echo urlencode("Join EventPortal using my Employee Referral Code \"{$employee_code}\"!\nLink: " . $ref_url_raw); ?>" class="btn btn-outline-secondary btn-xs" title="Share via Email"><i class="bi bi-envelope-fill"></i></a>
                        <a href="sms:?body=<?php echo urlencode("Join EventPortal using my Employee Referral Code \"{$employee_code}\"! Link: " . $ref_url_raw); ?>" class="btn btn-outline-primary btn-xs" title="Share via SMS"><i class="bi bi-chat-text-fill"></i></a>
                        <button type="button" class="btn btn-outline-dark btn-xs btn-copy-sponsor" data-username="<?php echo htmlspecialchars($employee_code); ?>" title="Copy Referral Link"><i class="bi bi-clipboard"></i></button>
                    </div>
                </div>
                <div class="col-12 col-md-4 border-start-md border-top-sm pt-3 pt-md-0">
                    <small class="text-muted font-monospace text-uppercase d-block" style="font-size: 0.7rem;">Official Designation</small>
                    <strong class="text-primary-emphasis fw-bold"><?php echo htmlspecialchars($designation_title); ?></strong>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Load Chart.js for data visualization -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- ==================== ROLE CONDITIONAL METRICS & CHARTS GRID ==================== -->

<?php if ($user['role'] === 'admin'): ?>
    <!-- ADMIN KPI COUNTERS -->
    <div class="row g-4 mb-4">
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-primary border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Total Members</h6>
                            <h3 class="mb-0 fw-bold text-dark"><?php echo $total_users; ?></h3>
                        </div>
                        <div class="p-3 bg-primary bg-opacity-10 text-primary rounded-circle">
                            <i class="bi bi-people-fill fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Active portal account registrations
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-success border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Platform Revenue</h6>
                            <h3 class="mb-0 fw-bold text-success">₹<?php echo number_format($admin_total_revenue, 2); ?></h3>
                        </div>
                        <div class="p-3 bg-success bg-opacity-10 text-success rounded-circle">
                            <i class="bi bi-wallet2 fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted d-flex justify-content-between align-items-center">
                        <span>GST: ₹<?php echo number_format($admin_total_gst, 2); ?></span>
                        <span class="badge bg-success-subtle text-success border border-success-subtle px-2 py-1">₹ Paid</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-warning border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">KYC Compliance</h6>
                            <h3 class="mb-0 fw-bold text-warning-emphasis"><?php echo $admin_kyc_rate; ?>%</h3>
                        </div>
                        <div class="p-3 bg-warning bg-opacity-10 text-warning rounded-circle">
                            <i class="bi bi-shield-check fs-4"></i>
                        </div>
                    </div>
                    <div class="progress mb-2" style="height: 6px;">
                        <div class="progress-bar bg-warning" role="progressbar" style="width: <?php echo $admin_kyc_rate; ?>%;" aria-valuenow="<?php echo $admin_kyc_rate; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <div class="small text-muted d-flex justify-content-between">
                        <span>Backlog: <strong><?php echo $admin_pending_kyc; ?></strong> audits</span>
                        <span>Goal: 100%</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-danger border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Payout Clearance</h6>
                            <h3 class="mb-0 fw-bold text-danger"><?php echo $admin_payout_rate; ?>%</h3>
                        </div>
                        <div class="p-3 bg-danger bg-opacity-10 text-danger rounded-circle">
                            <i class="bi bi-cash-coin fs-4"></i>
                        </div>
                    </div>
                    <div class="progress mb-2" style="height: 6px;">
                        <div class="progress-bar bg-danger" role="progressbar" style="width: <?php echo $admin_payout_rate; ?>%;" aria-valuenow="<?php echo $admin_payout_rate; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <div class="small text-muted d-flex justify-content-between">
                        <span>Backlog: <strong><?php echo $admin_pending_payouts; ?></strong> files</span>
                        <span>Rate of approval</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ADMIN SECONDARY ADVANCED COUNTERS -->
    <div class="row g-4 mb-5">
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 bg-light-subtle rounded-3">
                <div class="card-body p-4">
                    <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.7rem;">Signup Bonuses</h6>
                    <h4 class="fw-bold mb-0 text-dark">₹<?php echo number_format($admin_total_signup_bonus, 2); ?></h4>
                    <small class="text-muted">Distributed welcome pool</small>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 bg-light-subtle rounded-3">
                <div class="card-body p-4">
                    <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.7rem;">Referral Incentives</h6>
                    <h4 class="fw-bold mb-0 text-dark">₹<?php echo number_format($admin_total_referral_bonus, 2); ?></h4>
                    <small class="text-muted">Multi-level referral payouts</small>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 bg-light-subtle rounded-3">
                <div class="card-body p-4">
                    <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.7rem;">Direct + Referral</h6>
                    <h4 class="fw-bold mb-0 text-success">₹<?php echo number_format($admin_total_signup_bonus + $admin_total_referral_bonus, 2); ?></h4>
                    <small class="text-muted">Total marketing budget spent</small>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 bg-light-subtle rounded-3">
                <div class="card-body p-4">
                    <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.7rem;">Matrix Commissions</h6>
                    <h4 class="fw-bold mb-0 text-dark">₹<?php echo number_format($admin_total_commissions, 2); ?></h4>
                    <small class="text-muted">Total hierarchy payout</small>
                </div>
            </div>
        </div>
    </div>

    <!-- ADMIN CHARTS VISUALIZATIONS -->
    <div class="row g-4 mb-5">
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-graph-up text-primary me-2"></i>Platform Registration & Revenue Trends</h5>
                    <span class="badge bg-primary-subtle text-primary px-2 py-1 font-monospace">Last 15 Days</span>
                </div>
                <div class="card-body p-4">
                    <div style="position: relative; height: 320px; width: 100%;">
                        <canvas id="adminTrendChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-pie-chart text-success me-2"></i>User Roles Distribution</h5>
                </div>
                <div class="card-body p-4 d-flex align-items-center justify-content-center">
                    <div style="position: relative; height: 260px; width: 100%;">
                        <canvas id="adminRolesChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php elseif ($user['role'] === 'organizer'): ?>
    <!-- ORGANIZER KPI COUNTERS -->
    <div class="row g-4 mb-4">
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-primary border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Events Created</h6>
                            <h3 class="mb-0 fw-bold text-dark"><?php echo $organizer_events_count; ?></h3>
                        </div>
                        <div class="p-3 bg-primary bg-opacity-10 text-primary rounded-circle">
                            <i class="bi bi-calendar-check fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted d-flex justify-content-between">
                        <span>Avg Price: ₹<?php echo number_format($organizer_avg_ticket_price, 2); ?></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-success border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Ticket Earnings</h6>
                            <h3 class="mb-0 fw-bold text-success">₹<?php echo number_format($organizer_estimated_revenue, 2); ?></h3>
                        </div>
                        <div class="p-3 bg-success bg-opacity-10 text-success rounded-circle">
                            <i class="bi bi-cash-coin fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Accumulated net ticket sales
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-info border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Tickets Sold</h6>
                            <h3 class="mb-0 fw-bold text-info"><?php echo $organizer_registrations_count; ?></h3>
                        </div>
                        <div class="p-3 bg-info bg-opacity-10 text-info rounded-circle">
                            <i class="bi bi-ticket-perforated fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Total tickets purchased by attendees
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-purple border-4 rounded-3" style="border-left-color: #6f42c1 !important;">
                <div class="card-body p-4">
                    <?php 
                    $util_rate = $organizer_total_capacity > 0 ? round(($organizer_registrations_count / $organizer_total_capacity) * 100, 1) : 0;
                    ?>
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Capacity Utilisation</h6>
                            <h3 class="mb-0 fw-bold" style="color: #6f42c1;"><?php echo $util_rate; ?>%</h3>
                        </div>
                        <div class="p-3 bg-purple bg-opacity-10 rounded-circle" style="color: #6f42c1; background-color: rgba(111, 66, 193, 0.1);">
                            <i class="bi bi-percent fs-4"></i>
                        </div>
                    </div>
                    <div class="progress mb-2" style="height: 6px;">
                        <div class="progress-bar" role="progressbar" style="width: <?php echo $util_rate; ?>%; background-color: #6f42c1;" aria-valuenow="<?php echo $util_rate; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <div class="small text-muted d-flex justify-content-between">
                        <span>Limit: <strong><?php echo $organizer_total_capacity; ?></strong> seats</span>
                        <span>Filled: <strong><?php echo $organizer_registrations_count; ?></strong></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ORGANIZER CHARTS VISUALIZATIONS -->
    <div class="row g-4 mb-5">
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-calendar-check text-primary me-2"></i>Daily Registration Sales Volume</h5>
                </div>
                <div class="card-body p-4">
                    <div style="position: relative; height: 320px; width: 100%;">
                        <canvas id="organizerTrendChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-bar-chart text-purple me-2"></i>Events Sales & Capacity</h5>
                </div>
                <div class="card-body p-4">
                    <div style="position: relative; height: 320px; width: 100%;">
                        <canvas id="organizerEventsChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php elseif ($user['role'] === 'speaker'): ?>
    <!-- SPEAKER KPI COUNTERS -->
    <div class="row g-4 mb-4">
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-primary border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Sessions Assigned</h6>
                            <h3 class="mb-0 fw-bold text-dark"><?php echo $speaker_sessions_scheduled; ?></h3>
                        </div>
                        <div class="p-3 bg-primary bg-opacity-10 text-primary rounded-circle">
                            <i class="bi bi-mic fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Total speaking slots in schedule
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-success border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Audience Exposure</h6>
                            <h3 class="mb-0 fw-bold text-success"><?php echo $speaker_audience_reach; ?></h3>
                        </div>
                        <div class="p-3 bg-success bg-opacity-10 text-success rounded-circle">
                            <i class="bi bi-people-fill fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Total reach across speaking events
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-info border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Upcoming Sessions</h6>
                            <h3 class="mb-0 fw-bold text-info"><?php echo $speaker_upcoming_sessions; ?></h3>
                        </div>
                        <div class="p-3 bg-info bg-opacity-10 text-info rounded-circle">
                            <i class="bi bi-clock-history fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Scheduled slots still to speak
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-secondary border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Completed Sessions</h6>
                            <h3 class="mb-0 fw-bold text-secondary"><?php echo $speaker_past_sessions; ?></h3>
                        </div>
                        <div class="p-3 bg-secondary bg-opacity-10 text-secondary rounded-circle">
                            <i class="bi bi-check-circle-fill fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Finished events timeline
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- SPEAKER CHARTS VISUALIZATIONS -->
    <div class="row g-4 mb-5">
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-bar-chart text-primary me-2"></i>Audience Exposure by Session</h5>
                </div>
                <div class="card-body p-4">
                    <div style="position: relative; height: 320px; width: 100%;">
                        <canvas id="speakerAudienceChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-pie-chart text-success me-2"></i>Session Revenue Types</h5>
                </div>
                <div class="card-body p-4 d-flex align-items-center justify-content-center">
                    <div style="position: relative; height: 260px; width: 100%;">
                        <canvas id="speakerSessionsChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php elseif ($user['role'] === 'sponsor'): ?>
    <!-- SPONSOR KPI COUNTERS -->
    <div class="row g-4 mb-4">
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-primary border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Sponsored Events</h6>
                            <h3 class="mb-0 fw-bold text-dark"><?php echo $sponsor_events_count; ?></h3>
                        </div>
                        <div class="p-3 bg-primary bg-opacity-10 text-primary rounded-circle">
                            <i class="bi bi-award fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Total linkages to corporate brand
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-success border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Exposure Reach</h6>
                            <h3 class="mb-0 fw-bold text-success"><?php echo $sponsor_audience_reach; ?></h3>
                        </div>
                        <div class="p-3 bg-success bg-opacity-10 text-success rounded-circle">
                            <i class="bi bi-eye fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Total attendees across campaigns
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-warning border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Sponsorship ROI Index</h6>
                            <h3 class="mb-0 fw-bold text-warning-emphasis"><?php echo number_format($sponsor_roi_index); ?></h3>
                        </div>
                        <div class="p-3 bg-warning bg-opacity-10 text-warning rounded-circle">
                            <i class="bi bi-graph-up-arrow fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted">
                        Weighted brand impression value
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-info border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <div>
                            <h6 class="text-muted mb-1 text-uppercase fw-semibold font-monospace" style="font-size: 0.75rem;">Gold Sponsorships</h6>
                            <h3 class="mb-0 fw-bold text-info"><?php echo $sponsor_gold_tier; ?></h3>
                        </div>
                        <div class="p-3 bg-info bg-opacity-10 text-info rounded-circle">
                            <i class="bi bi-gem fs-4"></i>
                        </div>
                    </div>
                    <div class="small text-muted d-flex justify-content-between">
                        <span>Silver: <?php echo $sponsor_silver_tier; ?></span>
                        <span>Bronze: <?php echo $sponsor_bronze_tier; ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- SPONSOR CHARTS VISUALIZATIONS -->
    <div class="row g-4 mb-5">
        <div class="col-12 col-lg-8">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-bar-chart text-primary me-2"></i>Exposure Reach by Sponsored Event</h5>
                </div>
                <div class="card-body p-4">
                    <div style="position: relative; height: 320px; width: 100%;">
                        <canvas id="sponsorExposureChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-12 col-lg-4">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-pie-chart text-warning me-2"></i>Sponsorship Tiers Breakdown</h5>
                </div>
                <div class="card-body p-4 d-flex align-items-center justify-content-center">
                    <div style="position: relative; height: 260px; width: 100%;">
                        <canvas id="sponsorTiersChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php else: ?>
    <!-- ASSOCIATE KPI WALLET (Light Premium design) -->
    <div class="row g-4 mb-4">
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 bg-primary text-white border-4 border-start border-primary-emphasis rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <small class="text-white-50 font-monospace text-uppercase" style="font-size: 0.7rem;">Wallet Balance Available</small>
                            <h2 class="fw-bold my-1 text-white">₹<?php echo number_format($available_balance, 2); ?></h2>
                        </div>
                        <div class="p-2 bg-white bg-opacity-20 rounded">
                            <i class="bi bi-wallet2 fs-4 text-white"></i>
                        </div>
                    </div>
                    <p class="small text-white-50 mb-0">Funds ready for payout withdrawal.</p>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-success border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <small class="text-muted font-monospace text-uppercase" style="font-size: 0.7rem;">Total Earnings Generated</small>
                            <h2 class="fw-bold my-1 text-dark">₹<?php echo number_format($total_earnings, 2); ?></h2>
                        </div>
                        <div class="p-2 bg-success bg-opacity-10 rounded text-success">
                            <i class="bi bi-graph-up-arrow fs-4"></i>
                        </div>
                    </div>
                    <p class="small text-muted mb-0">Cumulative incentives earned.</p>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-info border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <small class="text-muted font-monospace text-uppercase" style="font-size: 0.7rem;">Funds Withdrawn</small>
                            <h2 class="fw-bold my-1 text-success">₹<?php echo number_format($total_withdrawn, 2); ?></h2>
                        </div>
                        <div class="p-2 bg-info bg-opacity-10 rounded text-info">
                            <i class="bi bi-check-circle-fill fs-4"></i>
                        </div>
                    </div>
                    <p class="small text-muted mb-0">Withdrawn and paid payouts.</p>
                </div>
            </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100 border-start border-warning border-4 rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <small class="text-muted font-monospace text-uppercase" style="font-size: 0.7rem;">Pending Payout Review</small>
                            <h2 class="fw-bold my-1 text-warning-emphasis">₹<?php echo number_format($total_pending, 2); ?></h2>
                        </div>
                        <div class="p-2 bg-warning bg-opacity-10 rounded text-warning">
                            <i class="bi bi-clock-history fs-4"></i>
                        </div>
                    </div>
                    <p class="small text-muted mb-0">Processing payout requests.</p>
                </div>
            </div>
        </div>
    </div>



    <!-- ASSOCIATE CHARTS VISUALIZATIONS -->
    <div class="row g-4 mb-5">
        <div class="col-12">
            <div class="card border-0 shadow-sm rounded-3 h-100">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-graph-up text-primary me-2"></i>My Daily Earnings Trend</h5>
                </div>
                <div class="card-body p-4">
                    <div style="position: relative; height: 320px; width: 100%;">
                        <canvas id="userEarningsChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- ==================== SUBSECTION TABLES AND DETAIL WIDGETS ==================== -->

<div class="row g-4 mb-5">
    
    <!-- LEFT PANEL CONTENT (Role Specific Data Logs / Lists) -->
    <div class="col-12 col-lg-8">
        
        <?php if ($user['role'] === 'admin'): ?>
            <!-- Admin Backlog & Platform Details -->
            <div class="card border-0 shadow-sm mb-4 rounded-3">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-shield-check me-2 text-danger"></i>KYC Verification Pipeline</h5>
                    <a href="admin/users?tab=kyc_approvals" class="btn btn-sm btn-outline-danger">Audit KYC Pipeline</a>
                </div>
                <div class="card-body">
                    <p class="text-muted small">Admins must audit pending document verification requests to ensure corporate KYC compliance before payout withdrawals are unlocked.</p>
                    <div class="d-flex justify-content-around bg-light p-3 rounded">
                        <div class="text-center">
                            <h4 class="fw-bold mb-0 text-warning"><?php echo $admin_pending_kyc; ?></h4>
                            <span class="text-muted small">Pending Audit</span>
                        </div>
                        <div class="vr"></div>
                        <div class="text-center">
                            <?php
                            $approved_kyc = $pdo->query("SELECT COUNT(*) FROM kyc_records WHERE doc1_status = 'approved' AND doc2_status = 'approved'")->fetchColumn();
                            ?>
                            <h4 class="fw-bold mb-0 text-success"><?php echo $approved_kyc; ?></h4>
                            <span class="text-muted small">Total Verified</span>
                        </div>
                    </div>
                </div>
            </div>
        <?php elseif ($user['role'] === 'organizer'): ?>
            <!-- Organizer Recent Ticket Signups -->
            <div class="card border-0 shadow-sm mb-4 rounded-3">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-people-fill me-2 text-primary"></i>Recent Event Registrations</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size: 0.85rem;">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Attendee</th>
                                    <th>Event Title</th>
                                    <th>Paid Total</th>
                                    <th class="text-end pe-4">Registered Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($organizer_recent_registrants)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center py-4 text-muted">No recent registrations for your events.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($organizer_recent_registrants as $reg): ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark d-block"><?php echo htmlspecialchars($reg['username']); ?></strong>
                                                <span class="text-muted small"><?php echo htmlspecialchars($reg['email']); ?></span>
                                            </td>
                                            <td><?php echo htmlspecialchars($reg['event_title']); ?></td>
                                            <td><strong class="text-dark">₹<?php echo number_format($reg['total_payable'], 2); ?></strong></td>
                                            <td class="text-end pe-4 text-muted"><?php echo date('Y-m-d H:i', strtotime($reg['registered_at'])); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php elseif ($user['role'] === 'speaker'): ?>
            <!-- Speaker Assigned Sessions list -->
            <div class="card border-0 shadow-sm mb-4 rounded-3">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-clock-history me-2 text-primary"></i>My Assigned Speaker Agenda Sessions</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size: 0.85rem;">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Session Title</th>
                                    <th>Event Location</th>
                                    <th>Date & Time</th>
                                    <th class="text-end pe-4">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($speaker_agenda_sessions)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center py-4 text-muted">No speaking agenda items found.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($speaker_agenda_sessions as $sess): ?>
                                        <?php 
                                        $sess_time = strtotime($sess['agenda_date'] . ' ' . $sess['start_time']);
                                        $upcoming = $sess_time >= time();
                                        ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark d-block"><?php echo htmlspecialchars($sess['title']); ?></strong>
                                                <span class="text-muted small"><?php echo htmlspecialchars($sess['event_title']); ?></span>
                                            </td>
                                            <td>Online/Physical</td>
                                            <td><?php echo date('M d, Y', strtotime($sess['agenda_date'])); ?> @ <?php echo date('g:i A', strtotime($sess['start_time'])); ?></td>
                                            <td class="text-end pe-4">
                                                <span class="badge <?php echo $upcoming ? 'bg-primary' : 'bg-secondary'; ?>">
                                                    <?php echo $upcoming ? 'Upcoming' : 'Completed'; ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php elseif ($user['role'] === 'sponsor'): ?>
            <!-- Sponsor Portfolio lists -->
            <div class="card border-0 shadow-sm mb-4 rounded-3">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-award me-2 text-primary"></i>My Event Sponsorship Portfolio</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size: 0.85rem;">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Event Title</th>
                                    <th>Location</th>
                                    <th>Tier Assigned</th>
                                    <th class="text-end pe-4">Dates</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($sponsor_portfolio)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center py-4 text-muted">No sponsored events linked to your company profile.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($sponsor_portfolio as $port): ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark"><?php echo htmlspecialchars($port['title']); ?></strong>
                                            </td>
                                            <td><?php echo htmlspecialchars($port['location']); ?></td>
                                            <td>
                                                <span class="badge <?php 
                                                    if ($port['tier'] === 'Gold') echo 'bg-warning text-dark';
                                                    elseif ($port['tier'] === 'Silver') echo 'bg-secondary text-white';
                                                    else echo 'bg-light text-dark border';
                                                ?>"><?php echo htmlspecialchars($port['tier']); ?> Tier</span>
                                            </td>
                                            <td class="text-end pe-4 text-muted"><?php echo date('Y-m-d', strtotime($port['start_date'])); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <!-- Standard User: Referrals Details Table -->
            <div class="card border-0 shadow-sm mb-4 rounded-3">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-person-lines-fill me-2 text-primary"></i>My Team Status</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size: 0.85rem;">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Username</th>
                                    <th>Email</th>
                                    <th>Registered Date</th>
                                    <th class="text-end pe-4">Event RSVPs</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($my_referrals_detail)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center py-4 text-muted">No direct referrals under your sponsor code yet.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($my_referrals_detail as $ref_row): ?>
                                        <tr>
                                            <td class="ps-4">
                                                <strong class="text-dark"><?php echo htmlspecialchars($ref_row['username']); ?></strong>
                                            </td>
                                            <td><?php echo htmlspecialchars($ref_row['email']); ?></td>
                                            <td class="text-muted"><?php echo date('Y-m-d', strtotime($ref_row['created_at'])); ?></td>
                                            <td class="text-end pe-4 fw-bold text-primary"><?php echo $ref_row['rsvp_count']; ?> RSVPs</td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Upcoming Platform Events (General Widget for All Roles) -->
        <div class="card border-0 shadow-sm rounded-3">
            <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-calendar-event me-2 text-primary"></i>Upcoming Events</h5>
                <a href="events" class="btn btn-sm btn-outline-primary">Browse All Listings</a>
            </div>
            <div class="card-body p-0">
                <?php if (empty($upcoming_events)): ?>
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-calendar-x fs-1 mb-2"></i>
                        <p class="mb-0">No upcoming events scheduled.</p>
                    </div>
                <?php else: ?>
                    <div class="list-group list-group-flush">
                        <?php foreach ($upcoming_events as $event): ?>
                            <div class="list-group-item p-4 border-bottom" style="cursor: pointer; transition: background-color 0.2s;" onmouseover="this.style.backgroundColor='#f8f9fa';" onmouseout="this.style.backgroundColor='transparent';" onclick="if(!event.target.closest('a') && !event.target.closest('button')) { window.location.href='event/<?php echo $event['id']; ?>'; }">
                                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-start gap-2 mb-2">
                                    <div>
                                        <h6 class="fw-bold mb-1"><a href="event/<?php echo $event['id']; ?>" class="text-decoration-none text-dark hover-primary"><?php echo htmlspecialchars($event['title']); ?></a></h6>
                                        <div class="d-flex flex-wrap gap-3 text-muted small mt-1">
                                            <span><i class="bi bi-calendar-event me-1"></i><?php echo formatEventDateRange($event['start_date'], $event['end_date']); ?></span>
                                            <span><i class="bi bi-geo-alt me-1"></i><?php echo htmlspecialchars($event['location']); ?></span>
                                        </div>
                                    </div>
                                    <?php if ($user['role'] !== 'user'): ?>
                                        <span class="badge bg-light text-dark border p-2">
                                            <i class="bi bi-people-fill me-1 text-primary"></i>
                                            <?php echo $event['attendee_count']; ?> Registered
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <p class="text-secondary mb-0 text-truncate-3" style="font-size: 0.9rem;">
                                    <?php echo htmlspecialchars(substr($event['description'], 0, 180)) . (strlen($event['description']) > 180 ? '...' : ''); ?>
                                </p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <!-- RIGHT PANEL CONTENT -->
    <div class="col-12 col-lg-4">

        <!-- Role Custom Profile Quickcard -->
        <?php if ($user['role'] === 'speaker' && $speaker_profile): ?>
            <div class="card border-0 shadow-sm mb-4 rounded-3">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-person-bounding-box me-2 text-primary"></i>Speaker Profile</h5>
                </div>
                <div class="card-body">
                    <h5 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars($speaker_profile['full_name']); ?></h5>
                    <span class="text-muted small d-block mb-3"><?php echo htmlspecialchars($speaker_profile['organization'] ?? 'Independent Speaker'); ?></span>
                    <span class="badge bg-primary bg-opacity-10 text-primary small d-inline-block mb-3"><?php echo htmlspecialchars($speaker_profile['expertise']); ?></span>
                    <p class="text-secondary small mb-0"><?php echo htmlspecialchars($speaker_profile['bio']); ?></p>
                </div>
            </div>
        <?php elseif ($user['role'] === 'sponsor' && $sponsor_profile): ?>
            <div class="card border-0 shadow-sm mb-4 rounded-3">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-briefcase-fill me-2 text-primary"></i>Corporate Sponsor Profile</h5>
                </div>
                <div class="card-body">
                    <h5 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars($sponsor_profile['company_name']); ?></h5>
                    <?php if ($sponsor_profile['website_url']): ?>
                        <a href="<?php echo htmlspecialchars($sponsor_profile['website_url']); ?>" target="_blank" class="small text-decoration-none d-block mb-3"><?php echo htmlspecialchars($sponsor_profile['website_url']); ?></a>
                    <?php endif; ?>
                    <p class="text-secondary small mb-0"><?php echo htmlspecialchars($sponsor_profile['description']); ?></p>
                </div>
        <?php endif; ?>

        <!-- Quick actions -->
        <div class="card border-0 shadow-sm rounded-3">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-grid-fill me-2 text-primary"></i>Dashboard Quick Tools</h5>
            </div>
            <div class="card-body d-grid gap-2">
                <a href="events" class="btn btn-outline-primary btn-sm text-start">
                    <i class="bi bi-calendar-range me-2"></i> Browse Events List
                </a>
                <a href="profile" class="btn btn-outline-secondary btn-sm text-start">
                    <i class="bi bi-person-bounding-box me-2"></i> My Profile Page
                </a>
                <a href="documents" class="btn btn-outline-primary btn-sm text-start">
                    <i class="bi bi-file-earmark-person me-2"></i> My Credentials & Docs
                </a>
                <?php if ($user['role'] === 'admin'): ?>
                    <a href="admin/users" class="btn btn-outline-danger btn-sm text-start">
                        <i class="bi bi-people me-2"></i> Admin User Control Panel
                    </a>
                <?php endif; ?>
                <?php if ($user['role'] === 'user'): ?>
                    <a href="kyc" class="btn btn-outline-success btn-sm text-start">
                        <i class="bi bi-shield-check me-2"></i> Submit KYC Verification
                    </a>
                    <a href="payouts" class="btn btn-outline-info btn-sm text-start">
                        <i class="bi bi-wallet me-2"></i> Withdrawal Requests
                    </a>
                <?php endif; ?>
                <a href="logout" class="btn btn-danger btn-sm text-start text-white">
                    <i class="bi bi-box-arrow-right me-2"></i> Log Out Account
                </a>
            </div>
        </div>

    </div>

</div>

<!-- ==================== CHART RENDERING SCRIPTS ==================== -->
<script>
document.addEventListener("DOMContentLoaded", function () {
    // Config Chart Font options
    Chart.defaults.font.family = "'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif";
    Chart.defaults.font.size = 12;

    <?php if ($user['role'] === 'admin'): ?>
        // Admin Trend Chart
        const adminDates = <?php echo json_encode($admin_reg_dates); ?>;
        const adminCounts = <?php echo json_encode($admin_reg_counts); ?>;
        const adminRevs = <?php echo json_encode($admin_reg_revs); ?>;

        const ctxAdminTrend = document.getElementById('adminTrendChart').getContext('2d');
        new Chart(ctxAdminTrend, {
            type: 'line',
            data: {
                labels: adminDates,
                datasets: [
                    {
                        label: 'Registrations (Tickets Count)',
                        data: adminCounts,
                        borderColor: '#0d6efd',
                        backgroundColor: 'rgba(13, 110, 253, 0.05)',
                        borderWidth: 2,
                        tension: 0.3,
                        yAxisID: 'y'
                    },
                    {
                        label: 'Revenue (₹)',
                        data: adminRevs,
                        borderColor: '#198754',
                        backgroundColor: 'rgba(25, 135, 84, 0.05)',
                        borderWidth: 2,
                        tension: 0.3,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: { display: true, text: 'Ticket Sales Count' },
                        grid: { drawOnChartArea: true }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: { display: true, text: 'Revenue (₹)' },
                        grid: { drawOnChartArea: false }
                    }
                }
            }
        });

        // Admin Roles Chart
        const adminRolesLabels = <?php echo json_encode($admin_roles_labels); ?>;
        const adminRolesCounts = <?php echo json_encode($admin_roles_counts); ?>;

        const ctxAdminRoles = document.getElementById('adminRolesChart').getContext('2d');
        new Chart(ctxAdminRoles, {
            type: 'doughnut',
            data: {
                labels: adminRolesLabels,
                datasets: [{
                    data: adminRolesCounts,
                    backgroundColor: ['#0d6efd', '#198754', '#ffc107', '#6f42c1', '#0dcaf0', '#6c757d'],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });

    <?php elseif ($user['role'] === 'organizer'): ?>
        // Organizer Sales Trend Chart
        const orgDates = <?php echo json_encode($organizer_reg_dates); ?>;
        const orgCounts = <?php echo json_encode($organizer_reg_counts); ?>;
        const orgRevs = <?php echo json_encode($organizer_reg_revs); ?>;

        const ctxOrgTrend = document.getElementById('organizerTrendChart').getContext('2d');
        new Chart(ctxOrgTrend, {
            type: 'line',
            data: {
                labels: orgDates,
                datasets: [
                    {
                        label: 'Sales (Tickets Count)',
                        data: orgCounts,
                        borderColor: '#0d6efd',
                        backgroundColor: 'rgba(13, 110, 253, 0.05)',
                        borderWidth: 2,
                        tension: 0.3,
                        yAxisID: 'y'
                    },
                    {
                        label: 'Revenue (₹)',
                        data: orgRevs,
                        borderColor: '#198754',
                        backgroundColor: 'rgba(25, 135, 84, 0.05)',
                        borderWidth: 2,
                        tension: 0.3,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: { display: true, text: 'Ticket Sales Count' }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: { display: true, text: 'Revenue (₹)' },
                        grid: { drawOnChartArea: false }
                    }
                }
            }
        });

        // Organizer Events Chart
        const orgEventTitles = <?php echo json_encode($organizer_event_titles); ?>;
        const orgEventRegs = <?php echo json_encode($organizer_event_registrations); ?>;
        const orgEventCaps = <?php echo json_encode($organizer_event_capacities); ?>;

        const ctxOrgEvents = document.getElementById('organizerEventsChart').getContext('2d');
        new Chart(ctxOrgEvents, {
            type: 'bar',
            data: {
                labels: orgEventTitles,
                datasets: [
                    {
                        label: 'Registered',
                        data: orgEventRegs,
                        backgroundColor: '#6f42c1',
                        borderWidth: 0
                    },
                    {
                        label: 'Capacity',
                        data: orgEventCaps,
                        backgroundColor: '#e2d9f3',
                        borderWidth: 0
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });

    <?php elseif ($user['role'] === 'speaker' && $speaker_profile): ?>
        // Speaker Audience Chart
        const spSessionTitles = <?php echo json_encode($speaker_session_titles); ?>;
        const spAudience = <?php echo json_encode($speaker_session_audience); ?>;

        const ctxSpAudience = document.getElementById('speakerAudienceChart').getContext('2d');
        new Chart(ctxSpAudience, {
            type: 'bar',
            data: {
                labels: spSessionTitles,
                datasets: [{
                    label: 'Audience Exposure count',
                    data: spAudience,
                    backgroundColor: '#0d6efd',
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });

        // Speaker Sessions Type Chart
        const spTypes = <?php echo json_encode($speaker_session_types); ?>;
        const spTypesLabels = Object.keys(spTypes).map(t => t.toUpperCase());
        const spTypesCounts = Object.values(spTypes);

        const ctxSpSessions = document.getElementById('speakerSessionsChart').getContext('2d');
        new Chart(ctxSpSessions, {
            type: 'doughnut',
            data: {
                labels: spTypesLabels,
                datasets: [{
                    data: spTypesCounts,
                    backgroundColor: ['#198754', '#ffc107', '#0dcaf0'],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });

    <?php elseif ($user['role'] === 'sponsor' && $sponsor_profile): ?>
        // Sponsor Exposure Chart
        const sponEventTitles = <?php echo json_encode($sponsor_event_titles); ?>;
        const sponReach = <?php echo json_encode($sponsor_event_reach); ?>;

        const ctxSponExposure = document.getElementById('sponsorExposureChart').getContext('2d');
        new Chart(ctxSponExposure, {
            type: 'bar',
            data: {
                labels: sponEventTitles,
                datasets: [{
                    label: 'Attendees Reach',
                    data: sponReach,
                    backgroundColor: '#0dcaf0',
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });

        // Sponsor Tiers Chart
        const ctxSponTiers = document.getElementById('sponsorTiersChart').getContext('2d');
        new Chart(ctxSponTiers, {
            type: 'doughnut',
            data: {
                labels: ['Gold Tier', 'Silver Tier', 'Bronze Tier'],
                datasets: [{
                    data: [
                        <?php echo $sponsor_gold_tier; ?>,
                        <?php echo $sponsor_silver_tier; ?>,
                        <?php echo $sponsor_bronze_tier; ?>
                    ],
                    backgroundColor: ['#ffc107', '#6c757d', '#cd7f32'],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });

    <?php else: ?>
        // Associate User Earnings Trend Chart
        const userEarnDates = <?php echo json_encode($user_earn_dates); ?>;
        const userEarnValues = <?php echo json_encode($user_earn_values); ?>;

        const ctxUserEarn = document.getElementById('userEarningsChart').getContext('2d');
        new Chart(ctxUserEarn, {
            type: 'line',
            data: {
                labels: userEarnDates,
                datasets: [{
                    label: 'Daily Earnings (₹)',
                    data: userEarnValues,
                    borderColor: '#198754',
                    backgroundColor: 'rgba(25, 135, 84, 0.05)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });    <?php endif; ?>
});

// WhatsApp API Share Modal Logic
document.getElementById('formShareWhatsapp')?.addEventListener('submit', function(e) {
    e.preventDefault();
    const btn = document.getElementById('btnSendWhatsapp');
    const ogHtml = btn.innerHTML;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Sending...';
    btn.disabled = true;

    const formData = new FormData(this);
    fetch('api/share_whatsapp.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        btn.innerHTML = ogHtml;
        btn.disabled = false;
        
        const alertBox = document.getElementById('waShareAlert');
        alertBox.className = 'alert mt-3 mb-0 alert-' + (data.status === 'success' ? 'success' : 'danger');
        alertBox.innerHTML = data.message;
        alertBox.classList.remove('d-none');
        
        if (data.status === 'success') {
            setTimeout(() => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('whatsappShareModal'));
                if (modal) modal.hide();
                alertBox.classList.add('d-none');
                this.reset();
            }, 2000);
        }
    })
    .catch(error => {
        btn.innerHTML = ogHtml;
        btn.disabled = false;
        const alertBox = document.getElementById('waShareAlert');
        alertBox.className = 'alert mt-3 mb-0 alert-danger';
        alertBox.innerHTML = 'An unexpected error occurred.';
        alertBox.classList.remove('d-none');
    });
});
</script>

<!-- WhatsApp Share Modal -->
<div class="modal fade" id="whatsappShareModal" tabindex="-1" aria-labelledby="whatsappShareModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-0 pb-0">
        <h5 class="modal-title fw-bold" id="whatsappShareModalLabel"><i class="bi bi-whatsapp text-success me-2"></i>Share via WhatsApp</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="text-muted small mb-4">Send a rich interactive message with a <strong>Register Now</strong> button directly to their WhatsApp.</p>
        <form id="formShareWhatsapp">
          <div class="mb-3">
            <label for="waPhone" class="form-label fw-bold small">Recipient Phone Number</label>
            <input type="tel" class="form-control" id="waPhone" name="phone" placeholder="e.g. 919876543210 (include country code)" required>
            <div class="form-text text-muted" style="font-size: 0.75rem;">Enter the full phone number with country code, without '+' or spaces.</div>
          </div>
          <div id="waShareAlert" class="alert d-none" role="alert"></div>
          <div class="d-grid mt-4">
            <button type="submit" class="btn btn-success fw-bold" id="btnSendWhatsapp">
              <i class="bi bi-send me-1"></i> Send Invite
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<?php
include __DIR__ . '/../includes/footer.php';
?>
