<?php

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

date_default_timezone_set('Africa/Lagos');

$userId = (int)$_SESSION['user_id'];

$today = new DateTime('today');


/*
|--------------------------------------------------------------------------
| GET MEMBER SUBSCRIPTIONS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        s.id AS subscription_id,
        s.user_id,
        s.plan_id,
        s.hands,
        s.total_amount,
        s.status AS subscription_status,
        s.created_at AS subscription_created_at,

        p.plan_name,
        p.amount AS plan_amount,
        p.frequency,
        p.duration,
        p.start_month,
        p.start_year,
        p.plan_image,

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

    FROM subscriptions s

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

    LEFT JOIN scheme_clearances sc
        ON sc.subscription_id = s.id

    WHERE s.user_id = ?

    ORDER BY s.created_at DESC
");

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

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


/*
|--------------------------------------------------------------------------
| BUILD CLEARANCE DATA
|--------------------------------------------------------------------------
*/

$clearanceItems = [];

foreach ($subscriptions as $subscription) {

    $subscriptionId =
        (int)$subscription['subscription_id'];


    /*
    |--------------------------------------------------------------------------
    | Determine Official Scheme Period
    |--------------------------------------------------------------------------
    */

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

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

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

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


    /*
    |--------------------------------------------------------------------------
    | Scheme Start
    |--------------------------------------------------------------------------
    */

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

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

    } else {

        /*
        | Safety fallback for old plans
        | without configured start month/year.
        */

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

    }


    /*
    |--------------------------------------------------------------------------
    | Scheme End Boundary
    |--------------------------------------------------------------------------
    |
    | Example:
    |
    | Start: Dec 1, 2025
    | Duration: 12 months
    |
    | Last active month: November 2026
    | Clearance becomes available: Dec 1, 2026
    |
    */

    $schemeEndExclusive =
        clone $schemeStart;

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


    $schemeLastDay =
        clone $schemeEndExclusive;

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


    $schemeEnded =
        ($today >= $schemeEndExclusive);


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

    $stmt = $pdo->prepare("
        SELECT

            COUNT(*) AS total_contributions,

            SUM(
                CASE
                    WHEN status = 'paid'
                    THEN 1
                    ELSE 0
                END
            ) AS paid_contributions,

            SUM(
                CASE
                    WHEN status != 'paid'
                    THEN 1
                    ELSE 0
                END
            ) AS outstanding_contributions,

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

        FROM contributions

        WHERE subscription_id = ?
    ");

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

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


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

    $stmt = $pdo->prepare("
        SELECT

            COUNT(*) AS total_defaults,

            SUM(
                CASE
                    WHEN status = 'unpaid'
                    THEN 1
                    ELSE 0
                END
            ) AS unpaid_default_count,

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

        FROM subscription_defaults

        WHERE subscription_id = ?
    ");

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

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


    /*
    |--------------------------------------------------------------------------
    | Final Status
    |--------------------------------------------------------------------------
    */

    $outstandingContributions =
        (int)($contributionData['outstanding_contributions'] ?? 0);

    $outstandingContributionAmount =
        (float)($contributionData['outstanding_contribution_amount'] ?? 0);

    $unpaidDefaultCount =
        (int)($defaultData['unpaid_default_count'] ?? 0);

    $unpaidDefaultAmount =
        (float)($defaultData['unpaid_default_amount'] ?? 0);


    /*
    |--------------------------------------------------------------------------
    | Determine Clearance State
    |--------------------------------------------------------------------------
    */

    if (!empty($subscription['clearance_id'])) {

        $clearanceState =
            'completed';

    } elseif (!$schemeEnded) {

        $clearanceState =
            'not_available';

    } elseif ($outstandingContributions > 0) {

        $clearanceState =
            'contributions_outstanding';

    } elseif ($unpaidDefaultAmount > 0) {

        $clearanceState =
            'defaults_outstanding';

    } else {

        $clearanceState =
            'ready';

    }


    $clearanceItems[] = [

        'subscription' =>
            $subscription,

        'scheme_start' =>
            $schemeStart,

        'scheme_last_day' =>
            $schemeLastDay,

        'scheme_ended' =>
            $schemeEnded,

        'contribution_data' =>
            $contributionData,

        'default_data' =>
            $defaultData,

        'outstanding_contributions' =>
            $outstandingContributions,

        'outstanding_contribution_amount' =>
            $outstandingContributionAmount,

        'unpaid_default_count' =>
            $unpaidDefaultCount,

        'unpaid_default_amount' =>
            $unpaidDefaultAmount,

        'clearance_state' =>
            $clearanceState

    ];

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Scheme Clearance - Complete Bliss</title>

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

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

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

<link
    rel="stylesheet"
    href="../assets/css/member-clearance.css"
>

<link
    rel="stylesheet"
    href="../assets/css/member-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/member_sidebar.php"; ?>


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


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


<div class="main-content">


<main class="member-clearance-page">


    <!-- HEADER -->

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

        <div>

            <h1>

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

                Scheme Clearance

            </h1>

            <p>
                Complete your end-of-scheme clearance
                and obtain your clearance evidence.
            </p>

        </div>

    </div>


    <!-- INFORMATION -->

    <div class="clearance-info-box">

        <div class="clearance-info-icon">

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

        </div>

        <div>

            <strong>
                How clearance works
            </strong>

            <p>
                Clearance becomes available after a scheme ends.
                All contributions and outstanding defaults must be
                settled before clearance can be completed.
            </p>

        </div>

    </div>


    <!-- SCHEMES -->

    <div class="clearance-schemes">


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


        <?php foreach ($clearanceItems as $item): ?>


        <?php

        $scheme =
            $item['subscription'];

        $state =
            $item['clearance_state'];

        ?>


        <div class="clearance-card">


            <!-- CARD HEADER -->

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


                <div class="clearance-scheme-info">

                    <div class="clearance-scheme-icon">

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

                    </div>

                    <div>

                        <h2>

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

                        </h2>

                        <p>

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

                            <?= ((int)$scheme['hands'] === 1)
                                ? 'Hand'
                                : 'Hands'; ?>

                            &nbsp;•&nbsp;

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

                        </p>

                    </div>

                </div>


                <!-- STATE BADGE -->

                <?php if ($state === 'completed'): ?>

                    <span class="clearance-badge completed">

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

                        Completed

                    </span>

                <?php elseif ($state === 'ready'): ?>

                    <span class="clearance-badge ready">

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

                        Ready

                    </span>

                <?php elseif ($state === 'not_available'): ?>

                    <span class="clearance-badge waiting">

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

                        Ongoing

                    </span>

                <?php else: ?>

                    <span class="clearance-badge action">

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

                        Action Required

                    </span>

                <?php endif; ?>


            </div>


            <!-- PERIOD -->

            <div class="clearance-period">

                <div>

                    <span>
                        Scheme Period
                    </span>

                    <strong>

                        <?= $item['scheme_start']->format('M Y'); ?>

                        →

                        <?= $item['scheme_last_day']->format('M Y'); ?>

                    </strong>

                </div>

                <div>

                    <span>
                        Scheme End Date
                    </span>

                    <strong>

                        <?= $item['scheme_last_day']->format(
                            'd M Y'
                        ); ?>

                    </strong>

                </div>

            </div>


            <!-- CHECKS -->

            <div class="clearance-check-grid">


                <!-- CONTRIBUTIONS -->

                <div class="clearance-check-item">

                    <div class="clearance-check-top">

                        <span>
                            Contributions
                        </span>


                        <?php if (
                            $item['outstanding_contributions'] === 0
                        ): ?>

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

                        <?php else: ?>

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

                        <?php endif; ?>

                    </div>


                    <?php if (
                        $item['outstanding_contributions'] === 0
                    ): ?>

                        <strong class="check-good-text">

                            Fully Settled

                        </strong>

                    <?php else: ?>

                        <strong class="check-bad-text">

                            <?= $item['outstanding_contributions']; ?>
                            Outstanding

                        </strong>

                        <small>

                            ₦<?= number_format(
                                $item['outstanding_contribution_amount'],
                                2
                            ); ?>
                            still unpaid

                        </small>

                    <?php endif; ?>


                </div>


                <!-- DEFAULTS -->

                <div class="clearance-check-item">

                    <div class="clearance-check-top">

                        <span>
                            Defaults
                        </span>


                        <?php if (
                            $item['unpaid_default_amount'] <= 0
                        ): ?>

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

                        <?php else: ?>

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

                        <?php endif; ?>

                    </div>


                    <?php if (
                        $item['unpaid_default_amount'] <= 0
                    ): ?>

                        <strong class="check-good-text">

                            Fully Settled

                        </strong>

                    <?php else: ?>

                        <strong class="check-bad-text">

                            ₦<?= number_format(
                                $item['unpaid_default_amount'],
                                2
                            ); ?>

                        </strong>

                        <small>

                            <?= $item['unpaid_default_count']; ?>

                            unpaid
                            <?= ($item['unpaid_default_count'] === 1)
                                ? 'default'
                                : 'defaults'; ?>

                        </small>

                    <?php endif; ?>


                </div>


            </div>


            <!-- ACTION AREA -->

            <div class="clearance-action-area">


                <?php if ($state === 'completed'): ?>


                    <div class="clearance-completed-info">

                        <div>

                            <span>
                                Clearance Code
                            </span>

                            <strong>

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

                            </strong>

                        </div>

                        <div>

                            <span>
                                Clearance Date
                            </span>

                            <strong>

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

                            </strong>

                        </div>

                    </div>


                    <button
                        type="button"
                        class="clearance-btn completed-btn"
                        disabled
                    >

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

                        Clearance Completed

                    </button>


                    <a
    href="clearance_certificate.php?subscription_id=<?= (int)$scheme['subscription_id']; ?>"
    class="clearance-btn certificate-btn"
    target="_blank"
>

    <i class="fas fa-file-arrow-down"></i>

    View / Save Clearance Image

</a>


                <?php elseif ($state === 'not_available'): ?>


                    <p class="clearance-message neutral">

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

                        Clearance will become available after
                        <?= $item['scheme_last_day']->format(
                            'd M Y'
                        ); ?>.

                    </p>


                    <button
                        type="button"
                        class="clearance-btn disabled-btn"
                        disabled
                    >

                        Clearance Not Yet Available

                    </button>


                <?php elseif (
                    $state === 'contributions_outstanding'
                ): ?>


                    <p class="clearance-message danger">

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

                        You must settle all outstanding contributions
                        before you can proceed with clearance.

                    </p>


                    <button
                        type="button"
                        class="clearance-btn disabled-btn"
                        disabled
                    >

                        Outstanding Contributions

                    </button>


                <?php elseif (
                    $state === 'defaults_outstanding'
                ): ?>


                    <p class="clearance-message warning">

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

                        Your contributions are complete, but you have
                        outstanding defaults of
                        <strong>
                            ₦<?= number_format(
                                $item['unpaid_default_amount'],
                                2
                            ); ?>
                        </strong>.
                        These must be settled to complete clearance.

                    </p>


                    <form
    action="process_clearance.php"
    method="POST"
    class="clearance-process-form"
>

    <input
        type="hidden"
        name="subscription_id"
        value="<?= (int)$scheme['subscription_id']; ?>"
    >

    <button
        type="submit"
        class="clearance-btn settle-btn"
    >

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

        Settle Defaults & Complete Clearance

    </button>

</form>

                <?php elseif ($state === 'ready'): ?>


                    <p class="clearance-message success">

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

                        Your contributions and defaults are fully settled.
                        You are ready to complete clearance.

                    </p>


                    <form
    action="process_clearance.php"
    method="POST"
    class="clearance-process-form"
>

    <input
        type="hidden"
        name="subscription_id"
        value="<?= (int)$scheme['subscription_id']; ?>"
    >

    <button
        type="submit"
        class="clearance-btn ready-btn"
    >

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

        Complete Clearance

    </button>

</form>


                <?php endif; ?>


            </div>


        </div>


        <?php endforeach; ?>


    <?php else: ?>


        <div class="clearance-empty">

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

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

            </div>

            <h3>
                No Schemes Yet
            </h3>

            <p>
                You have not joined any schemes.
            </p>

        </div>


    <?php endif; ?>


    </div>


</main>


</div>


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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


<?php if (isset($_SESSION['success'])): ?>

<script>

document.addEventListener("DOMContentLoaded", function () {

    Swal.fire({

        icon: "success",

        title: "Clearance Successful",

        text: <?= json_encode($_SESSION['success']); ?>,

        confirmButtonColor: "#16a34a"

    });

});

</script>

<?php
unset($_SESSION['success']);
endif;
?>


<?php if (isset($_SESSION['error'])): ?>

<script>

document.addEventListener("DOMContentLoaded", function () {

    Swal.fire({

        icon: "error",

        title: "Clearance Not Completed",

        text: <?= json_encode($_SESSION['error']); ?>,

        confirmButtonColor: "#dc3545"

    });

});

</script>

<?php
unset($_SESSION['error']);
endif;
?>


</body>

</html>