<?php

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

date_default_timezone_set('Africa/Lagos');


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

$stmt = $pdo->query("
    SELECT

        COUNT(*) AS total_records,

        COALESCE(
            SUM(
                CASE
                    WHEN status = 'unpaid'
                    THEN amount
                    ELSE 0
                END
            ),
            0
        ) AS outstanding_amount,

        COALESCE(
            SUM(
                CASE
                    WHEN status = 'paid'
                    THEN amount
                    ELSE 0
                END
            ),
            0
        ) AS cleared_amount

    FROM subscription_defaults
");

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


/*
|--------------------------------------------------------------------------
| MEMBERS WITH OUTSTANDING DEFAULTS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT COUNT(DISTINCT user_id)
    FROM subscription_defaults
    WHERE status = 'unpaid'
");

$membersWithDefaults = (int)$stmt->fetchColumn();


/*
|--------------------------------------------------------------------------
| GET ALL DEFAULT RECORDS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT

        d.id AS default_id,
        d.amount AS default_amount,
        d.default_date,
        d.reason,
        d.status AS default_status,
        d.paid_at,
        d.created_at,

        u.id AS member_id,
        u.fullname,

        s.id AS subscription_id,
        s.hands,

        p.id AS plan_id,
        p.plan_name,
        p.frequency,

        c.id AS contribution_id,
        c.contribution_no,
        c.amount AS contribution_amount,
        c.due_date,
        c.paid_date,
        c.status AS contribution_status

    FROM subscription_defaults d

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

    INNER JOIN subscriptions s
        ON d.subscription_id = s.id

    INNER JOIN plans p
        ON d.plan_id = p.id

    INNER JOIN contributions c
        ON d.contribution_id = c.id

    ORDER BY d.created_at DESC
");

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


/*
|--------------------------------------------------------------------------
| PAYMENT PERIOD HELPER
|--------------------------------------------------------------------------
*/

function getAdminDefaultPeriod($frequency, $dueDate)
{
    $frequency = strtolower(trim($frequency));

    $date = new DateTime($dueDate);


    /*
    | Monthly:
    | September 5 deadline belongs to August contribution.
    */

    if ($frequency === 'monthly') {

        $date->modify('-1 month');

        return $date->format('F Y');

    }


    /*
    | Daily
    */

    if ($frequency === 'daily') {

        return $date->format('d M Y');

    }


    /*
    | Weekly
    */

    if ($frequency === 'weekly') {

        return 'Week ending ' . $date->format('d M Y');

    }


    /*
    | Yearly
    */

    if ($frequency === 'yearly') {

        return $date->format('Y');

    }


    return $date->format('d M Y');
}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Defaults - 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-defaults.css"
>

<link
    rel="stylesheet"
    href="../assets/css/admin-defaults-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-defaults-page">


    <!-- PAGE HEADER -->

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

        <div>

            <h1>

                <i class="fas fa-triangle-exclamation"></i>

                Member Defaults

            </h1>

            <p>
                View missed contribution penalties and their current status.
            </p>

        </div>

    </div>


    <!-- SUMMARY CARDS -->

    <div class="admin-default-summary-grid">


        <!-- OUTSTANDING -->

        <div class="admin-default-summary-card">

            <div class="admin-default-summary-icon outstanding">

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

            </div>

            <div>

                <span>
                    Outstanding Defaults
                </span>

                <h2>

                    ₦<?= number_format(
                        (float)$summary['outstanding_amount'],
                        2
                    ); ?>

                </h2>

            </div>

        </div>


        <!-- MEMBERS -->

        <div class="admin-default-summary-card">

            <div class="admin-default-summary-icon members">

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

            </div>

            <div>

                <span>
                    Members With Defaults
                </span>

                <h2>
                    <?= $membersWithDefaults; ?>
                </h2>

            </div>

        </div>


        <!-- TOTAL RECORDS -->

        <div class="admin-default-summary-card">

            <div class="admin-default-summary-icon records">

                <i class="fas fa-file-invoice"></i>

            </div>

            <div>

                <span>
                    Total Default Records
                </span>

                <h2>

                    <?= (int)$summary['total_records']; ?>

                </h2>

            </div>

        </div>


        <!-- CLEARED -->

        <div class="admin-default-summary-card">

            <div class="admin-default-summary-icon cleared">

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

            </div>

            <div>

                <span>
                    Cleared Defaults
                </span>

                <h2>

                    ₦<?= number_format(
                        (float)$summary['cleared_amount'],
                        2
                    ); ?>

                </h2>

            </div>

        </div>


    </div>


    <!-- DEFAULT TABLE -->

    <section class="admin-default-history-card">


        <div class="admin-default-history-header">

            <div>

                <h2>
                    Default Records
                </h2>

                <p>
                    All contribution defaults recorded for members.
                </p>

            </div>

        </div>


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


        <div class="admin-default-table-wrap">


            <table class="admin-default-table">


                <thead>

                    <tr>

                        <th>Member</th>

                        <th>Scheme</th>

                        <th>Payment Period</th>

                        <th>Contribution</th>

                        <th>Default</th>

                        <th>Due Date</th>

                        <th>Reason</th>

                        <th>Contribution Status</th>

                        <th>Default Status</th>

                        <th>Default Date</th>

                    </tr>

                </thead>


                <tbody>


                <?php foreach ($defaults as $default): ?>


                <tr>


                    <!-- MEMBER -->

                    <td>

                        <div class="admin-default-member">

                            <div class="admin-default-member-icon">

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

                            </div>

                            <div>

                                <strong>

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

                                </strong>

                                <small>

                                    Member #<?= (int)$default['member_id']; ?>

                                </small>

                            </div>

                        </div>

                    </td>


                    <!-- SCHEME -->

                    <td>

                        <strong>

                            <?= htmlspecialchars(
                                $default['plan_name']
                            ); ?>

                        </strong>

                        <small class="admin-default-subtext">

                            <?= htmlspecialchars(
                                ucfirst($default['frequency'])
                            ); ?>

                            · <?= (int)$default['hands']; ?>
                            Hand<?= ((int)$default['hands'] === 1) ? '' : 's'; ?>

                        </small>

                    </td>


                    <!-- PAYMENT PERIOD -->

                    <td>

                        <strong>

                            <?= htmlspecialchars(
                                getAdminDefaultPeriod(
                                    $default['frequency'],
                                    $default['due_date']
                                )
                            ); ?>

                        </strong>

                        <small class="admin-default-subtext">

                            Contribution
                            #<?= (int)$default['contribution_no']; ?>

                        </small>

                    </td>


                    <!-- CONTRIBUTION -->

                    <td>

                        ₦<?= number_format(
                            (float)$default['contribution_amount'],
                            2
                        ); ?>

                    </td>


                    <!-- DEFAULT -->

                    <td>

                        <strong class="admin-default-penalty">

                            ₦<?= number_format(
                                (float)$default['default_amount'],
                                2
                            ); ?>

                        </strong>

                    </td>


                    <!-- DUE DATE -->

                    <td>

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

                    </td>


                    <!-- REASON -->

                    <td>

                        <span class="admin-default-reason">

                            <?= htmlspecialchars(
                                $default['reason']
                            ); ?>

                        </span>

                    </td>


                    <!-- CONTRIBUTION STATUS -->

                    <td>

                        <?php if (
                            $default['contribution_status'] === 'paid'
                        ): ?>

                            <span class="admin-contribution-status paid">

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

                                Paid

                            </span>

                        <?php elseif (
                            $default['contribution_status'] === 'overdue'
                        ): ?>

                            <span class="admin-contribution-status overdue">

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

                                Overdue

                            </span>

                        <?php else: ?>

                            <span class="admin-contribution-status pending">

                                Pending

                            </span>

                        <?php endif; ?>

                    </td>


                    <!-- DEFAULT STATUS -->

                    <td>

                        <?php if (
                            $default['default_status'] === 'paid'
                        ): ?>

                            <span class="admin-default-status paid">

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

                                Cleared

                            </span>

                        <?php else: ?>

                            <span class="admin-default-status unpaid">

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

                                Unpaid

                            </span>

                        <?php endif; ?>

                    </td>


                    <!-- DEFAULT DATE -->

                    <td>

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

                    </td>


                </tr>


                <?php endforeach; ?>


                </tbody>


            </table>


        </div>


        <?php else: ?>


        <div class="admin-default-empty">

            <div class="admin-default-empty-icon">

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

            </div>

            <h3>
                No Defaults Recorded
            </h3>

            <p>
                No member contribution defaults have been recorded yet.
            </p>

        </div>


        <?php endif; ?>


    </section>


</main>


</div>


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


</body>

</html>