<?php

date_default_timezone_set('Africa/Lagos');

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


/*
|--------------------------------------------------------------------------
| Submitted Code
|--------------------------------------------------------------------------
*/

$code = strtoupper(
    trim($_GET['code'] ?? '')
);

$clearance = null;

$searched = false;


/*
|--------------------------------------------------------------------------
| Verify Clearance Code
|--------------------------------------------------------------------------
*/

if ($code !== '') {

    $searched = true;


    $stmt = $pdo->prepare("
        SELECT

            sc.id AS clearance_id,
            sc.clearance_code,
            sc.total_defaults_settled,
            sc.clearance_date,
            sc.status AS clearance_status,

            s.id AS subscription_id,
            s.hands,
            s.created_at AS subscription_created_at,

            u.id AS member_id,
            u.fullname,
            u.phone,
            u.email,

            p.id AS plan_id,
            p.plan_name,
            p.frequency,
            p.duration,
            p.start_month,
            p.start_year

        FROM scheme_clearances sc

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

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

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

        WHERE sc.clearance_code = ?
        AND sc.status = 'completed'

        LIMIT 1
    ");

    $stmt->execute([
        $code
    ]);

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

}


/*
|--------------------------------------------------------------------------
| Extra Information For Valid Clearance
|--------------------------------------------------------------------------
*/

$schemeStart = null;

$schemeEnd = null;

$contributionCount = 0;

$totalContributed = 0;

$totalDefaultRecords = 0;


if ($clearance) {


    /*
    |--------------------------------------------------------------------------
    | Scheme Period
    |--------------------------------------------------------------------------
    */

    $startMonth =
        (int)$clearance['start_month'];

    $startYear =
        (int)$clearance['start_year'];

    $durationMonths =
        (int)$clearance['duration'];


    if ($durationMonths < 1) {
        $durationMonths = 1;
    }


    if (
        $startMonth >= 1 &&
        $startMonth <= 12 &&
        $startYear >= 2000
    ) {

        $schemeStart =
            new DateTime(
                sprintf(
                    '%04d-%02d-01',
                    $startYear,
                    $startMonth
                )
            );

    } else {

        $schemeStart =
            new DateTime(
                date(
                    'Y-m-01',
                    strtotime(
                        $clearance[
                            'subscription_created_at'
                        ]
                    )
                )
            );

    }


    $schemeEndExclusive =
        clone $schemeStart;

    $schemeEndExclusive->modify(
        '+' . $durationMonths . ' months'
    );


    $schemeEnd =
        clone $schemeEndExclusive;

    $schemeEnd->modify('-1 day');


    /*
    |--------------------------------------------------------------------------
    | Contribution Summary
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT

            COUNT(*) AS contribution_count,

            COALESCE(
                SUM(amount),
                0
            ) AS total_contributed

        FROM contributions

        WHERE subscription_id = ?
        AND status = 'paid'
    ");

    $stmt->execute([
        $clearance['subscription_id']
    ]);

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


    $contributionCount =
        (int)(
            $contributionSummary[
                'contribution_count'
            ] ?? 0
        );


    $totalContributed =
        (float)(
            $contributionSummary[
                'total_contributed'
            ] ?? 0
        );


    /*
    |--------------------------------------------------------------------------
    | Default Record Count
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM subscription_defaults
        WHERE subscription_id = ?
    ");

    $stmt->execute([
        $clearance['subscription_id']
    ]);

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

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Verify Clearance - 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-verify-clearance.css"
>

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


    <!-- PAGE HEADER -->

    <div class="verify-clearance-header">

        <div>

            <h1>

                <i class="fas fa-shield-halved"></i>

                Verify Clearance Code

            </h1>

            <p>
                Check whether a Complete Bliss clearance
                code is genuine and view its clearance details.
            </p>

        </div>


        <a
            href="clearance.php"
            class="back-clearance-btn"
        >

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

            Clearance Records

        </a>

    </div>



    <!-- VERIFICATION FORM -->

    <section class="verify-search-card">


        <form
            method="GET"
            action=""
            class="verify-search-form"
        >


            <div class="verify-code-input">

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

                <input
                    type="text"
                    name="code"
                    placeholder="Enter clearance code e.g. CB-CLR-26-A7F9K2"
                    value="<?= htmlspecialchars($code); ?>"
                    autocomplete="off"
                    required
                >

            </div>


            <button type="submit">

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

                Verify Code

            </button>


        </form>


    </section>



    <?php if ($searched): ?>


        <?php if ($clearance): ?>


        <!-- ======================================
             VERIFIED
        ======================================= -->

        <section class="verification-result verified">


            <div class="verification-status-area">


                <div class="verification-main-icon">

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

                </div>


                <div>

                    <span>
                        Clearance Verification
                    </span>

                    <h2>
                        Valid Clearance
                    </h2>

                    <p>
                        This clearance code matches a completed
                        Complete Bliss clearance record.
                    </p>

                </div>


            </div>



            <!-- CLEARANCE CODE -->

            <div class="verified-code-box">

                <span>
                    Verified Clearance Code
                </span>

                <strong>

                    <?= htmlspecialchars(
                        $clearance['clearance_code']
                    ); ?>

                </strong>

            </div>



            <!-- MEMBER DETAILS -->

            <div class="verification-section">


                <div class="verification-section-title">

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

                    Member Information

                </div>


                <div class="verification-details-grid">


                    <div class="verification-detail">

                        <span>
                            Member Name
                        </span>

                        <strong>

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

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Member ID
                        </span>

                        <strong>

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

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Phone Number
                        </span>

                        <strong>

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

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Email
                        </span>

                        <strong>

                            <?= !empty($clearance['email'])
                                ? htmlspecialchars(
                                    $clearance['email']
                                )
                                : '—'; ?>

                        </strong>

                    </div>


                </div>


            </div>



            <!-- SCHEME DETAILS -->

            <div class="verification-section">


                <div class="verification-section-title">

                    <i class="fas fa-layer-group"></i>

                    Scheme Information

                </div>


                <div class="verification-details-grid">


                    <div class="verification-detail">

                        <span>
                            Scheme
                        </span>

                        <strong>

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

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Number of Hands
                        </span>

                        <strong>

                            <?= (int)$clearance['hands']; ?>

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Frequency
                        </span>

                        <strong>

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

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Scheme Period
                        </span>

                        <strong>

                            <?= $schemeStart->format('M Y'); ?>

                            –

                            <?= $schemeEnd->format('M Y'); ?>

                        </strong>

                    </div>


                </div>


            </div>



            <!-- FINANCIAL DETAILS -->

            <div class="verification-section">


                <div class="verification-section-title">

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

                    Clearance Summary

                </div>


                <div class="verification-details-grid">


                    <div class="verification-detail">

                        <span>
                            Contributions Paid
                        </span>

                        <strong>

                            <?= $contributionCount; ?>

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Total Contributions
                        </span>

                        <strong>

                            ₦<?= number_format(
                                $totalContributed,
                                2
                            ); ?>

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Default Records
                        </span>

                        <strong>

                            <?= $totalDefaultRecords; ?>

                        </strong>

                    </div>


                    <div class="verification-detail">

                        <span>
                            Defaults Settled During Clearance
                        </span>

                        <strong>

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

                        </strong>

                    </div>


                </div>


            </div>



            <!-- FINAL DETAILS -->

            <div class="verification-footer-grid">


                <div class="verification-final-card">

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

                    <div>

                        <span>
                            Clearance Date
                        </span>

                        <strong>

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

                        </strong>

                    </div>

                </div>


                <div class="verification-final-card">

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

                    <div>

                        <span>
                            Clearance Status
                        </span>

                        <strong class="verified-text">
                            COMPLETED
                        </strong>

                    </div>

                </div>


            </div>


        </section>



        <?php else: ?>


        <!-- ======================================
             INVALID
        ======================================= -->

        <section class="verification-result invalid">


            <div class="verification-invalid-icon">

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

            </div>


            <h2>
                Invalid Clearance Code
            </h2>


            <p>

                No completed Complete Bliss clearance record
                matches:

            </p>


            <strong class="invalid-code">

                <?= htmlspecialchars($code); ?>

            </strong>


            <p class="invalid-note">

                Check the code carefully and try again.

            </p>


        </section>


        <?php endif; ?>


    <?php else: ?>


    <!-- INITIAL STATE -->

    <section class="verification-welcome">


        <div class="verification-welcome-icon">

            <i class="fas fa-shield-halved"></i>

        </div>


        <h2>
            Clearance Verification
        </h2>


        <p>
            Enter the unique clearance code from a
            member's clearance evidence to verify the record.
        </p>


    </section>


    <?php endif; ?>


</main>


</div>


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


</body>

</html>