<?php

date_default_timezone_set('Africa/Lagos');

include "../includes/admin_auth.php";
include "../config/database.php";


/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

$search =
    trim($_GET['q'] ?? '');

$statusFilter =
    trim($_GET['status'] ?? 'all');

$typeFilter =
    trim($_GET['type'] ?? 'all');


/*
|--------------------------------------------------------------------------
| SUMMARY
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT

        COUNT(*) AS total_notifications,

        COALESCE(
            SUM(
                CASE
                    WHEN is_read = 0
                    THEN 1
                    ELSE 0
                END
            ),
            0
        ) AS unread_count,

        COALESCE(
            SUM(
                CASE
                    WHEN is_read = 1
                    THEN 1
                    ELSE 0
                END
            ),
            0
        ) AS read_count,

        COALESCE(
            SUM(
                CASE
                    WHEN DATE(created_at) = CURDATE()
                    THEN 1
                    ELSE 0
                END
            ),
            0
        ) AS today_count

    FROM notifications
");

$summary =
    $stmt->fetch(PDO::FETCH_ASSOC);


$totalNotifications =
    (int)($summary['total_notifications'] ?? 0);

$unreadCount =
    (int)($summary['unread_count'] ?? 0);

$readCount =
    (int)($summary['read_count'] ?? 0);

$todayCount =
    (int)($summary['today_count'] ?? 0);


/*
|--------------------------------------------------------------------------
| AVAILABLE NOTIFICATION TYPES
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT DISTINCT type
    FROM notifications
    WHERE type IS NOT NULL
    AND type != ''
    ORDER BY type ASC
");

$notificationTypes =
    $stmt->fetchAll(PDO::FETCH_COLUMN);


/*
|--------------------------------------------------------------------------
| NOTIFICATION RECORDS
|--------------------------------------------------------------------------
*/

$sql = "
    SELECT

        n.id,
        n.user_id,
        n.title,
        n.message,
        n.type,
        n.is_read,
        n.created_at,

        u.fullname,
        u.phone

    FROM notifications n

    INNER JOIN users u
        ON n.user_id = u.id

    WHERE 1 = 1
";


$params = [];


/*
|--------------------------------------------------------------------------
| SEARCH
|--------------------------------------------------------------------------
*/

if ($search !== '') {

    $sql .= "
        AND (
            u.fullname LIKE ?
            OR u.phone LIKE ?
            OR n.title LIKE ?
            OR n.message LIKE ?
        )
    ";

    $searchValue =
        '%' . $search . '%';

    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;

}


/*
|--------------------------------------------------------------------------
| READ STATUS
|--------------------------------------------------------------------------
*/

if ($statusFilter === 'unread') {

    $sql .= "
        AND n.is_read = 0
    ";

}

elseif ($statusFilter === 'read') {

    $sql .= "
        AND n.is_read = 1
    ";

}


/*
|--------------------------------------------------------------------------
| TYPE
|--------------------------------------------------------------------------
*/

if ($typeFilter !== 'all') {

    $sql .= "
        AND n.type = ?
    ";

    $params[] =
        $typeFilter;

}


$sql .= "
    ORDER BY
        n.created_at DESC,
        n.id DESC
";


$stmt = $pdo->prepare($sql);

$stmt->execute($params);

$notifications =
    $stmt->fetchAll(PDO::FETCH_ASSOC);


    /*
|--------------------------------------------------------------------------
| NOTIFICATION PAGINATION
|--------------------------------------------------------------------------
*/

$recordsPerPage = 20;

$totalNotificationRecords =
    count($notifications);


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


$totalNotificationPages =
    max(
        1,
        (int)ceil(
            $totalNotificationRecords /
            $recordsPerPage
        )
    );


if (
    $notificationPage >
    $totalNotificationPages
) {

    $notificationPage =
        $totalNotificationPages;

}


$notificationOffset =
    ($notificationPage - 1)
    * $recordsPerPage;


$paginatedNotifications =
    array_slice(
        $notifications,
        $notificationOffset,
        $recordsPerPage
    );


$showingFrom =
    $totalNotificationRecords > 0
        ? $notificationOffset + 1
        : 0;


$showingTo =
    min(
        $notificationOffset
        + $recordsPerPage,
        $totalNotificationRecords
    );


$notificationPaginationParams = [

    'q' =>
        $search,

    'status' =>
        $statusFilter,

    'type' =>
        $typeFilter

];

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
>

<title>Notifications - Complete Bliss</title>


<link
    rel="stylesheet"
    href="../assets/css/admin.css"
>

<link
    rel="stylesheet"
    href="../assets/css/responsive.css"
>

<link
    rel="stylesheet"
    href="../assets/css/admin-notifications.css"
>

<link
    rel="stylesheet"
    href="../assets/css/admin-notifications-responsive.css"
>

<link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
>

</head>


<body>


<?php include "../includes/admin_sidebar.php"; ?>


<div class="sidebar-overlay"></div>


<?php include "../includes/admin_topbar.php"; ?>


<div class="main-content">


<main class="admin-notifications-page">


    <!-- ==========================================
         HEADER
    =========================================== -->

    <div class="admin-notifications-header">


        <div>

            <h1>

                <i class="fas fa-bell"></i>

                Notifications

            </h1>

            <p>
                Monitor notifications sent to Complete Bliss members.
            </p>

        </div>


    </div>



    <!-- ==========================================
         SUMMARY
    =========================================== -->

    <div class="notification-summary-grid">


        <!-- TOTAL -->

        <div class="notification-summary-card">

            <div class="notification-summary-icon total">

                <i class="fas fa-bell"></i>

            </div>

            <div>

                <span>
                    Total Notifications
                </span>

                <h2>
                    <?= number_format($totalNotifications); ?>
                </h2>

                <small>
                    All generated notifications
                </small>

            </div>

        </div>



        <!-- UNREAD -->

        <div class="notification-summary-card">

            <div class="notification-summary-icon unread">

                <i class="fas fa-envelope"></i>

            </div>

            <div>

                <span>
                    Unread
                </span>

                <h2>
                    <?= number_format($unreadCount); ?>
                </h2>

                <small>
                    Not yet opened by members
                </small>

            </div>

        </div>



        <!-- READ -->

        <div class="notification-summary-card">

            <div class="notification-summary-icon read">

                <i class="fas fa-envelope-open"></i>

            </div>

            <div>

                <span>
                    Read
                </span>

                <h2>
                    <?= number_format($readCount); ?>
                </h2>

                <small>
                    Already viewed by members
                </small>

            </div>

        </div>



        <!-- TODAY -->

        <div class="notification-summary-card">

            <div class="notification-summary-icon today">

                <i class="fas fa-calendar-day"></i>

            </div>

            <div>

                <span>
                    Generated Today
                </span>

                <h2>
                    <?= number_format($todayCount); ?>
                </h2>

                <small>
                    Notifications created today
                </small>

            </div>

        </div>


    </div>



    <!-- ==========================================
         FILTERS
    =========================================== -->

    <section class="notification-filter-card">


        <form
            method="GET"
            action="notifications.php"
            class="notification-filter-form"
        >


            <!-- SEARCH -->

            <div class="notification-search-box">

                <i class="fas fa-magnifying-glass"></i>

                <input
                    type="text"
                    name="q"
                    placeholder="Search member, title or message..."
                    value="<?= htmlspecialchars($search); ?>"
                >

            </div>



            <!-- STATUS -->

            <select name="status">

                <option
                    value="all"
                    <?= $statusFilter === 'all'
                        ? 'selected'
                        : ''; ?>
                >
                    All Statuses
                </option>

                <option
                    value="unread"
                    <?= $statusFilter === 'unread'
                        ? 'selected'
                        : ''; ?>
                >
                    Unread
                </option>

                <option
                    value="read"
                    <?= $statusFilter === 'read'
                        ? 'selected'
                        : ''; ?>
                >
                    Read
                </option>

            </select>



            <!-- TYPE -->

            <select name="type">

                <option value="all">
                    All Types
                </option>

                <?php foreach ($notificationTypes as $type): ?>

                    <option
                        value="<?= htmlspecialchars($type); ?>"
                        <?= $typeFilter === $type
                            ? 'selected'
                            : ''; ?>
                    >

                        <?= htmlspecialchars(
                            ucwords(
                                str_replace(
                                    '_',
                                    ' ',
                                    $type
                                )
                            )
                        ); ?>

                    </option>

                <?php endforeach; ?>

            </select>



            <!-- APPLY -->

            <button type="submit">

                <i class="fas fa-filter"></i>

                Apply

            </button>



            <!-- RESET -->

            <a
                href="notifications.php"
                class="notification-reset-btn"
            >

                Reset

            </a>


        </form>


    </section>



    <!-- ==========================================
         RECORDS
    =========================================== -->

    <section class="notification-record-card">


        <div class="notification-record-header">

            <div>

                <h2>
                    Notification Records
                </h2>

<p>

    <?php if (
        $totalNotificationRecords > 0
    ): ?>

        Showing

        <strong>
            <?= $showingFrom; ?>
        </strong>

        –

        <strong>
            <?= $showingTo; ?>
        </strong>

        of

        <strong>
            <?= $totalNotificationRecords; ?>
        </strong>

        notifications

    <?php else: ?>

        0 notifications

    <?php endif; ?>

</p>

            </div>

        </div>



        <?php if (count($notifications) > 0): ?>


            <div class="notification-table-wrap">


                <table class="notification-table">


                    <thead>

                        <tr>

                            <th>Date</th>

                            <th>Member</th>

                            <th>Notification</th>

                            <th>Type</th>

                            <th>Status</th>

                        </tr>

                    </thead>


                    <tbody>


                    <?php foreach ($paginatedNotifications as $notification): ?>


                        <?php

                        $typeClass =
                            strtolower(
                                preg_replace(
                                    '/[^a-zA-Z0-9_-]/',
                                    '',
                                    $notification['type'] ?? 'info'
                                )
                            );

                        ?>


                        <tr>


                            <!-- DATE -->

                            <td>

                                <strong class="notification-date">

                                    <?= date(
                                        'd M Y',
                                        strtotime(
                                            $notification['created_at']
                                        )
                                    ); ?>

                                </strong>

                                <small>

                                    <?= date(
                                        'h:i A',
                                        strtotime(
                                            $notification['created_at']
                                        )
                                    ); ?>

                                </small>

                            </td>



                            <!-- MEMBER -->

                            <td>

                                <div class="notification-member">


                                    <div class="notification-member-icon">

                                        <i class="fas fa-user"></i>

                                    </div>


                                    <div>

                                        <strong>

                                            <?= htmlspecialchars(
                                                $notification['fullname']
                                            ); ?>

                                        </strong>

                                        <small>

                                            <?= htmlspecialchars(
                                                $notification['phone'] ?? ''
                                            ); ?>

                                        </small>

                                    </div>


                                </div>

                            </td>



                            <!-- MESSAGE -->

                            <td>

                                <div class="notification-content">

                                    <strong>

                                        <?= htmlspecialchars(
                                            $notification['title']
                                        ); ?>

                                    </strong>

                                    <p>

                                        <?= htmlspecialchars(
                                            $notification['message']
                                        ); ?>

                                    </p>

                                </div>

                            </td>



                            <!-- TYPE -->

                            <td>

                                <span
                                    class="notification-type <?= htmlspecialchars($typeClass); ?>"
                                >

                                    <?= htmlspecialchars(
                                        ucwords(
                                            str_replace(
                                                '_',
                                                ' ',
                                                $notification['type']
                                                ?? 'info'
                                            )
                                        )
                                    ); ?>

                                </span>

                            </td>



                            <!-- STATUS -->

                            <td>

                                <?php if (
                                    (int)$notification['is_read'] === 1
                                ): ?>

                                    <span class="notification-status read">

                                        <i class="fas fa-check"></i>

                                        Read

                                    </span>

                                <?php else: ?>

                                    <span class="notification-status unread">

                                        <i class="fas fa-circle"></i>

                                        Unread

                                    </span>

                                <?php endif; ?>

                            </td>


                        </tr>


                    <?php endforeach; ?>


                    </tbody>


                </table>


            </div>

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


<div class="notification-pagination">


    <!-- PREVIOUS -->

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

        <a
            href="?<?= htmlspecialchars(
                http_build_query(
                    array_merge(
                        $notificationPaginationParams,
                        [
                            'page' =>
                                $notificationPage - 1
                        ]
                    )
                )
            ); ?>"
            class="notification-page-nav"
        >

            <i class="fas fa-chevron-left"></i>

            Previous

        </a>

    <?php else: ?>

        <span
            class="notification-page-nav disabled"
        >

            <i class="fas fa-chevron-left"></i>

            Previous

        </span>

    <?php endif; ?>



    <!-- PAGE NUMBERS -->

    <div class="notification-page-numbers">


        <?php for (
            $pageNumber = 1;
            $pageNumber <=
                $totalNotificationPages;
            $pageNumber++
        ): ?>


            <?php if (
                $pageNumber ===
                $notificationPage
            ): ?>

                <span
                    class="notification-page-number active"
                >

                    <?= $pageNumber; ?>

                </span>

            <?php else: ?>

                <a
                    href="?<?= htmlspecialchars(
                        http_build_query(
                            array_merge(
                                $notificationPaginationParams,
                                [
                                    'page' =>
                                        $pageNumber
                                ]
                            )
                        )
                    ); ?>"
                    class="notification-page-number"
                >

                    <?= $pageNumber; ?>

                </a>

            <?php endif; ?>


        <?php endfor; ?>


    </div>



    <!-- NEXT -->

    <?php if (
        $notificationPage <
        $totalNotificationPages
    ): ?>

        <a
            href="?<?= htmlspecialchars(
                http_build_query(
                    array_merge(
                        $notificationPaginationParams,
                        [
                            'page' =>
                                $notificationPage + 1
                        ]
                    )
                )
            ); ?>"
            class="notification-page-nav"
        >

            Next

            <i class="fas fa-chevron-right"></i>

        </a>

    <?php else: ?>

        <span
            class="notification-page-nav disabled"
        >

            Next

            <i class="fas fa-chevron-right"></i>

        </span>

    <?php endif; ?>


</div>


<?php endif; ?>


        <?php else: ?>


            <div class="notification-empty">


                <div class="notification-empty-icon">

                    <i class="fas fa-bell-slash"></i>

                </div>


                <h3>
                    No Notifications Found
                </h3>


                <p>

                    No notification records match
                    your selected filters.

                </p>


            </div>


        <?php endif; ?>


    </section>


</main>


</div>


<script src="../assets/js/admin.js"></script>


</body>

</html>