<?php
session_start();

include("../../config/db.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");


/* =========================================================
FILTER
========================================================= */

$keyword = trim($_GET['keyword'] ?? '');

$year = $_GET['year'] ?? $current_year;

$month = $_GET['month'] ?? '';

$status = $_GET['status'] ?? '';

$page = max(1, intval($_GET['page'] ?? 1));

$limit = 5;

$offset = ($page - 1) * $limit;


/* =========================================================
WHERE CLAUSE
========================================================= */

$where = [];

$where[] = "e.organizer_id = $org_id";


/* YEAR */
if($year != ''){

    $where[] = "YEAR(e.event_date)=".intval($year);

}


/* MONTH */
if($month != ''){

    $where[] = "MONTH(e.event_date)=".intval($month);

}


/* STATUS */
if($status != ''){

    $status_safe = mysqli_real_escape_string(
        $conn,
        $status
    );

    $where[] = "e.status='$status_safe'";

}


/* KEYWORD */
if($keyword != ''){

    $keyword_safe = mysqli_real_escape_string(
        $conn,
        $keyword
    );

    $where[] = "(
        e.title LIKE '%$keyword_safe%' OR
        e.description LIKE '%$keyword_safe%' OR
        e.location LIKE '%$keyword_safe%'
    )";

}


$where_sql = implode(" AND ", $where);


/* =========================================================
COUNT TOTAL
========================================================= */

$count_query = mysqli_query($conn,"
SELECT COUNT(*) as total
FROM events e
WHERE $where_sql
");

$total_rows = mysqli_fetch_assoc(
    $count_query
)['total'];

$total_pages = ceil($total_rows / $limit);


/* =========================================================
EVENT QUERY
========================================================= */

$events = mysqli_query($conn,"
SELECT

e.*,

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

COUNT(DISTINCT a.id) as total_attend,

(
    e.fee_amount *
    COUNT(
        DISTINCT CASE
        WHEN er.status != 'cancelled'
        THEN er.id
        END
    )
) as revenue

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 $where_sql

GROUP BY e.id

ORDER BY
MONTH(e.event_date) ASC,
e.event_date ASC

LIMIT $limit OFFSET $offset
");

if(!$events){

    die(
        "Events Query Error : ".
        mysqli_error($conn)
    );

}

?>





    <!-- =====================================================
    TOP HEADER + FILTER
    ===================================================== -->

    <div class="performanceTop">

        <!-- TITLE -->
        <div>

            <h3 class="sectionTitle">
                Event Performance
            </h3>

            <p class="sectionSub">
                Showing <?= $total_rows ?> event(s)
            </p>

        </div>



        <!-- FILTER -->
        <form
        id="filterForm"
        class="filterBar"
        onsubmit="return false;"
        >

            <!-- SEARCH -->
            <div class="searchBox">

                <i class="fa fa-search"></i>

                <input
                type="text"
                name="keyword"
                placeholder="Search event..."
                value="<?= htmlspecialchars($keyword) ?>"
                >

            </div>



            <!-- YEAR -->
            <select name="year">

                <?php for($y = date("Y")+1; $y >= 2023; $y--): ?>

                <option
                value="<?= $y ?>"
                <?= $year == $y ? 'selected' : '' ?>
                >
                    <?= $y ?>
                </option>

                <?php endfor; ?>

            </select>



            <!-- MONTH -->
            <select name="month">

                <option value="">
                    All Months
                </option>

                <?php

                $months = [
                    1  => 'Jan',
                    2  => 'Feb',
                    3  => 'Mar',
                    4  => 'Apr',
                    5  => 'May',
                    6  => 'Jun',
                    7  => 'Jul',
                    8  => 'Aug',
                    9  => 'Sep',
                    10 => 'Oct',
                    11 => 'Nov',
                    12 => 'Dec'
                ];

                foreach($months as $num => $name):

                ?>

                <option
                value="<?= $num ?>"
                <?= $month == $num ? 'selected' : '' ?>
                >
                    <?= $name ?>
                </option>

                <?php endforeach; ?>

            </select>



            <!-- STATUS -->
            <select name="status">

                <option value="">
                    All Status
                </option>

                <?php

                $statuses = [
                    'upcoming',
                    'ongoing',
                    'completed',
                    'cancelled'
                ];

                foreach($statuses as $s):

                ?>

                <option
                value="<?= $s ?>"
                <?= $status == $s ? 'selected' : '' ?>
                >
                    <?= ucfirst($s) ?>
                </option>

                <?php endforeach; ?>

            </select>



            <!-- FILTER BUTTON -->
            <button
            type="submit"
            class="filterBtn"
            >
                Filter
            </button>



            <!-- RESET -->
            <button
            type="button"
            class="resetBtn"
            id="resetBtn"
            >
                Reset
            </button>

        </form>

    </div>



    <!-- =====================================================
    EVENT LIST WRAP
    ===================================================== -->

    <div class="eventListWrap">

        <?php if(mysqli_num_rows($events) > 0): ?>



        <!-- =================================================
        EVENT LOOP
        ================================================== -->

        <?php while($e = mysqli_fetch_assoc($events)):

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


        $reg_rate = $e['max_participant'] > 0
        ? round(
            ($e['total_reg'] / $e['max_participant']) * 100,
            1
        )
        : 0;


        $fee_text = $e['fee_type'] == 'Free'
        ? 'Free'
        : 'RM '.number_format($e['fee_amount'],2);



        /* ================================================
        BADGE COLOR
        ================================================= */

        switch($e['status']){

            case 'completed':
                $badgeClass = 'badgeGreen';
                break;

            case 'ongoing':
                $badgeClass = 'badgeBlue';
                break;

            case 'upcoming':
                $badgeClass = 'badgeOrange';
                break;

            case 'cancelled':
                $badgeClass = 'badgeRed';
                break;

            default:
                $badgeClass = 'badgeGray';

        }

        ?>



        <!-- EVENT CARD -->

        <div class="eventRow">

            <!-- HEADER -->
            <div class="eventHeader">

                <div class="eventInfo">

                    <h4>
                        <?= htmlspecialchars($e['title']) ?>
                    </h4>

                    <p class="date">

                        <?= date(
                            "d M Y",
                            strtotime($e['event_date'])
                        ) ?>

                        •

                        <span class="fee">
                            <?= $fee_text ?>
                        </span>

                    </p>

                </div>



                <!-- ACTION -->
                <div class="eventActions">

                    <span class="badge <?= $badgeClass ?>">
                        <?= ucfirst($e['status']) ?>
                    </span>

                    <a
                    href="viewReport.php?event_id=<?= $e['id'] ?>"
                    class="viewBtn"
                    >
                        View Details
                    </a>

                </div>

            </div>



            <!-- DIVIDER -->
            <div class="divider"></div>



            <!-- STATS -->
            <div class="eventStats">

                <!-- REGISTRATION -->
                <div class="statCardMini">

                    <span>
                        Registrations
                    </span>

                    <h3>

                        <?= $e['total_reg'] ?>

                        <span class="max">
                            / <?= $e['max_participant'] ?>
                        </span>

                    </h3>

                    <div class="progressWrap">

                        <div class="progressBar reg">

                            <div
                            style="width:<?= $reg_rate ?>%"
                            ></div>

                        </div>

                    </div>

                    <p class="subStat">
                        <?= $reg_rate ?>% registered
                    </p>

                </div>



                <!-- ATTENDANCE -->
                <div class="statCardMini">

                    <span>
                        Attendance
                    </span>

                    <h3>
                        <?= $e['total_attend'] ?>
                    </h3>

                    <div class="progressWrap">

                        <div class="progressBar att">

                            <div
                            style="width:<?= $att_rate ?>%"
                            ></div>

                        </div>

                    </div>

                    <p class="subStat">
                        <?= $att_rate ?>% attended
                    </p>

                </div>



                <!-- REVENUE -->
                <div class="statCardMini">

                    <span>
                        Revenue
                    </span>

                    <h3>
                        RM <?= number_format($e['revenue'],2) ?>
                    </h3>

                </div>

            </div>

        </div>

        <?php endwhile; ?>



        <!-- =================================================
        PAGINATION
        ================================================== -->

        <?php if($total_pages > 1): ?>

        <div class="pagination">

            <!-- PREV -->
            <?php if($page > 1): ?>

            <a
            href="#"
            onclick="event.preventDefault(); loadEventList(<?= $page-1 ?>)"
            >
                Prev
            </a>

            <?php endif; ?>



            <!-- PAGE -->
            <?php for($i=1; $i <= $total_pages; $i++): ?>

            <a
            href="#"
            class="<?= $page == $i ? 'active' : '' ?>"
            onclick="event.preventDefault(); loadEventList(<?= $i ?>)"
            >
                <?= $i ?>
            </a>

            <?php endfor; ?>



            <!-- NEXT -->
            <?php if($page < $total_pages): ?>

            <a
            href="#"
            onclick="event.preventDefault(); loadEventList(<?= $page+1 ?>)"
            >
                Next
            </a>

            <?php endif; ?>

        </div>

        <?php endif; ?>



        <?php else: ?>



        <!-- =================================================
        EMPTY STATE
        ================================================== -->

        <div class="emptyState">

            <i class="fa fa-calendar-xmark"></i>

            <h4>
                No Events Found
            </h4>

            <p>
                No events matched your current filters.
            </p>

        </div>

        <?php endif; ?>



</div>