<?php
session_start();

include("../../config/db.php");
include("../../templates/header.php");
include("../../templates/sidebar.php");

if(!isset($_SESSION['role']) || $_SESSION['role'] != "organizer"){
    die("No access");
}

$user_id = $_SESSION['id'];

/* =========================================================
GET ORGANIZER
========================================================= */
$org_query = mysqli_query($conn, "
    SELECT id 
    FROM organizers 
    WHERE user_id = $user_id
");

$org = mysqli_fetch_assoc($org_query);

if(!$org){
    die("Organizer not found");
}

$org_id = $org['id'];

$current_year = date("Y");

/* =========================================================
GENERAL ANALYTICS
========================================================= */
$analytics = mysqli_query($conn, "

SELECT 

SUM(
    CASE 
        WHEN e.status != 'cancelled'
        THEN e.fee_amount *
        (
            SELECT COUNT(*)
            FROM event_registrations er
            WHERE er.event_id = e.id
            AND er.status != 'cancelled'
        )
        ELSE 0
    END
) as net_revenue,

SUM(
    CASE 
        WHEN e.status = 'cancelled'
        THEN e.fee_amount *
        (
            SELECT COUNT(*)
            FROM event_registrations er
            WHERE er.event_id = e.id
            AND er.status != 'cancelled'
        )
        ELSE 0
    END
) as refund_amount,

SUM(
    e.fee_amount *
    (
        SELECT COUNT(*)
        FROM event_registrations er
        WHERE er.event_id = e.id
        AND er.status != 'cancelled'
    )
) as total_revenue,

(
    SELECT COUNT(*)
    FROM event_registrations er
    JOIN events ev ON ev.id = er.event_id
    WHERE ev.organizer_id = $org_id
    AND er.status != 'cancelled'
) as total_reg,

(
    SELECT COUNT(a.id)
    FROM attendances a
    JOIN event_registrations er ON er.id = a.registration_id
    JOIN events ev ON ev.id = er.event_id
    WHERE ev.organizer_id = $org_id
) as total_attend,

(
    SELECT COUNT(*)
    FROM events
    WHERE organizer_id = $org_id
    AND status IN ('ongoing','upcoming')
) as active_events

FROM events e
WHERE e.organizer_id = $org_id

");

$gen = mysqli_fetch_assoc($analytics);

$overall_rate = $gen['total_reg'] > 0
? round(($gen['total_attend'] / $gen['total_reg']) * 100, 1)
: 0;

/* =========================================================
MONTH CHART DATA
========================================================= */
$month_labels = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

$month_counts = array_fill(0,12,0);

$month_query = mysqli_query($conn, "

SELECT 
    MONTH(event_date) as month_num,
    COUNT(*) as total

FROM events

WHERE organizer_id = $org_id
AND YEAR(event_date) = $current_year

GROUP BY MONTH(event_date)

");

while($row = mysqli_fetch_assoc($month_query)){

    $month_counts[$row['month_num'] - 1] = (int)$row['total'];

}

/* =========================================================
COMPLETED EVENT RATE
========================================================= */
$comp_names = [];
$comp_rates = [];

$completed_query = mysqli_query($conn, "

SELECT 

e.title,
e.status,

COUNT(
    DISTINCT CASE
    WHEN er.status != 'cancelled'
    THEN er.id
    END
) as total_reg,

COUNT(DISTINCT a.id) as total_attend

FROM events e

LEFT JOIN event_registrations er
ON er.event_id = e.id

LEFT JOIN attendances a
ON a.registration_id = er.id

WHERE e.organizer_id = $org_id

GROUP BY e.id

");

while($row = mysqli_fetch_assoc($completed_query)){

    if($row['status'] != 'completed'){
        continue;
    }

    $rate = $row['total_reg'] > 0
    ? round(($row['total_attend'] / $row['total_reg']) * 100, 1)
    : 0;

    $comp_names[] = $row['title']." ($rate%)";

    $comp_rates[] = $rate;
}
?>

<link rel="stylesheet" href="/SEAT/assets/css/organizer/analytics.css">


    
    
    <link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    
    <div class="main">
    
    <h2>Analytics Dashboard</h2>
    
    <p class="sub">
    Track event performance and engagement metrics
    </p>
    
    
    
    <!-- TOP SUMMARY -->
    
    <div class="topGrid">
    
    <div class="topCard statusRevenue">
    
    <div>
    
    <p class="label">Net Revenue</p>
    
    <h2>
    RM <?= number_format($gen['net_revenue'] ?? 0,2) ?>
    </h2>
    
    <p class="subStat">
    Excluding cancelled events
    </p>
    
    </div>
    
    <div class="iconBox greenBg">
    <i class="fa fa-dollar-sign"></i>
    </div>
    
    <div class="revenueTooltip">
    
    <div class="tooltipRow">
    <span>Total Revenue</span>
    
    <b>
    RM <?= number_format($gen['total_revenue'] ?? 0,2) ?>
    </b>
    </div>
    
    <div class="tooltipRow refund">
    
    <span>Refund</span>
    
    <b>
    - RM <?= number_format($gen['refund_amount'] ?? 0,2) ?>
    </b>
    
    </div>
    
    </div>
    
    </div>



<div class="topCard">

<div>

<p class="label">Total Registrations</p>

<h2><?= $gen['total_reg'] ?? 0 ?></h2>

</div>

<div class="iconBox blueBg">
<i class="fa fa-users"></i>
</div>

</div>



<div class="topCard">

<div>

<p class="label">Total Attendance</p>

<h2><?= $gen['total_attend'] ?? 0 ?></h2>

<p class="growth orange">
<i class="fa fa-circle-check"></i>
<?= $overall_rate ?>% avg rate
</p>

</div>

<div class="iconBox orangeBg">
<i class="fa fa-check"></i>
</div>

</div>



<div class="topCard">

<div>

<p class="label">Active Events</p>

<h2><?= $gen['active_events'] ?? 0 ?></h2>

</div>

<div class="iconBox purpleBg">
<i class="fa fa-calendar-days"></i>
</div>

</div>

</div>

    <!-- =====================================================
    CHARTS
    ====================================================== -->
    <div class="chartGrid">

        <div class="chartCard">

            <h4>Events per Month</h4>

            <canvas id="monthChart"></canvas>

        </div>

        <div class="chartCard">

            <h4>Attendance Rate</h4>

            <canvas id="completedChart"></canvas>

        </div>

    </div>

    <!-- =====================================================
    EVENT PERFORMANCE
    ====================================================== -->
    <div class="performanceCard">

        <div id="eventListContainer">

            <div class="loadingBox">

                <i class="fa fa-spinner fa-spin"></i>

                Loading events...

            </div>

        </div>

    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>

/* =========================================================
CONFIG
========================================================= */
const EVENT_LIST_URL = 'event_list.php';

let currentPage = 1;

/* =========================================================
CHART INSTANCES
========================================================= */
let monthChartInstance = null;

let completedChartInstance = null;





/* =========================================================
LOAD EVENT LIST
ONLY REFRESH EVENT SECTION
========================================================= */
function loadEventList(page = 1){

    currentPage = page;

    const form = document.getElementById('filterForm');

    const params = new URLSearchParams();

    const container = document.getElementById('eventListContainer');

    /* =====================================
    GET FILTER VALUES
    ===================================== */
    if(form){

        const formData = new FormData(form);

        for(const [key, value] of formData.entries()){

            params.append(key, value);

        }

    }

    params.append('page', page);

    /* =====================================
    SMOOTH LOADING
    DO NOT REPLACE CONTENT
    ===================================== */
    container.style.opacity = "0.5";

    container.style.pointerEvents = "none";

    container.style.transition = "0.2s ease";

    /* =====================================
    AJAX FETCH
    ===================================== */
    fetch(`${EVENT_LIST_URL}?${params.toString()}`)

    .then(response => response.text())

    .then(html => {

        /* ONLY UPDATE EVENT SECTION */
        container.innerHTML = html;

        /* RESTORE */
        container.style.opacity = "1";

        container.style.pointerEvents = "auto";

        /* RE-BIND EVENTS */
        bindFilterEvents();

    })

    .catch(error => {

        console.log(error);

        /* RESTORE */
        container.style.opacity = "1";

        container.style.pointerEvents = "auto";

    });

}



/* =========================================================
BIND FILTER EVENTS
========================================================= */
function bindFilterEvents(){

    const form = document.getElementById('filterForm');

    if(!form) return;

    /* PREVENT DUPLICATE */
    if(form.dataset.bound === "1"){
        return;
    }

    form.dataset.bound = "1";

    /* =====================================
    FORM SUBMIT
    ===================================== */
    form.addEventListener('submit', function(e){

        e.preventDefault();

        loadEventList(1);

    });

    /* =====================================
    SELECT CHANGE
    ===================================== */
    form.querySelectorAll('select').forEach(select => {

        select.addEventListener('change', function(){

            loadEventList(1);

        });

    });

    /* =====================================
    SEARCH INPUT
    ===================================== */
    const keywordInput = form.querySelector('input[name="keyword"]');

    if(keywordInput){

        let typingTimer;

        keywordInput.addEventListener('input', function(){

            clearTimeout(typingTimer);

            typingTimer = setTimeout(() => {

                loadEventList(1);

            }, 400);

        });

    }

    /* =====================================
    RESET BUTTON
    ===================================== */
    const resetBtn = document.getElementById('resetBtn');

    if(resetBtn){

        /* REMOVE OLD EVENT */
        resetBtn.replaceWith(resetBtn.cloneNode(true));

        /* GET NEW BUTTON */
        const newResetBtn = document.getElementById('resetBtn');

        newResetBtn.addEventListener('click', function(e){

            e.preventDefault();

            /* RESET FORM */
            form.reset();

            /* RESET VALUES MANUALLY */
            const yearSelect = form.querySelector('select[name="year"]');
            const monthSelect = form.querySelector('select[name="month"]');
            const statusSelect = form.querySelector('select[name="status"]');
            const keywordInput = form.querySelector('input[name="keyword"]');

            if(yearSelect){
                yearSelect.value = "<?= $current_year ?>";
            }

            if(monthSelect){
                monthSelect.value = "";
            }

            if(statusSelect){
                statusSelect.value = "";
            }

            if(keywordInput){
                keywordInput.value = "";
            }

            /* LOAD CLEAN DATA */
            loadEventList(1);

        });

    }

}


/* =========================================================
PAGINATION
========================================================= */
function goToPage(page){

    loadEventList(page);

}

/* =========================================================
INIT CHARTS
========================================================= */
function initCharts(){

    /* DESTROY OLD */
    if(monthChartInstance){
        monthChartInstance.destroy();
    }

    if(completedChartInstance){
        completedChartInstance.destroy();
    }

    /* =====================================
    MONTH CHART
    ===================================== */
    const monthCanvas = document.getElementById('monthChart');

    if(monthCanvas){

        monthChartInstance = new Chart(monthCanvas, {

            type: 'line',

            data: {

                labels: <?= json_encode($month_labels) ?>,

                datasets: [{

                    data: <?= json_encode($month_counts) ?>,

                    borderColor: '#7c3aed',

                    backgroundColor: 'rgba(124,58,237,0.1)',

                    fill: true,

                    tension: 0.3

                }]

            },

            options: {

                responsive: true,

                maintainAspectRatio: false,

                plugins: {

                    legend: {
                        display: false
                    }

                }

            }

        });

    }

    /* =====================================
    COMPLETED CHART
    ===================================== */
    const completedCanvas = document.getElementById('completedChart');

    if(completedCanvas){

        completedChartInstance = new Chart(completedCanvas, {

            type: 'bar',

            data: {

                labels: <?= json_encode($comp_names) ?>,

                datasets: [{

                    data: <?= json_encode($comp_rates) ?>,

                    backgroundColor: '#22c55e'

                }]

            },

            options: {

                responsive: true,

                maintainAspectRatio: false,

                plugins: {

                    legend: {
                        display: false
                    }

                },

                scales: {

                    y: {

                        beginAtZero: true,

                        max: 100

                    }

                }

            }

        });

    }

}

/* =========================================================
INIT
========================================================= */
document.addEventListener('DOMContentLoaded', function(){

    /* LOAD EVENT SECTION */
    loadEventList(1);

    /* LOAD CHARTS */
    initCharts();

});

</script>

