<?php

date_default_timezone_set('Africa/Lagos');

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


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

$subscriptionId =
    (int)($_GET['subscription_id'] ?? 0);


if ($subscriptionId <= 0) {

    header("Location: clearance.php");
    exit();

}


/*
|--------------------------------------------------------------------------
| GET CLEARANCE RECORD
|--------------------------------------------------------------------------
*/

$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.fullname,
        u.phone,
        u.email,

        p.plan_name,
        p.frequency,
        p.amount AS plan_amount,
        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.subscription_id = ?
    AND sc.user_id = ?
    AND sc.status = 'completed'

    LIMIT 1
");

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

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


if (!$clearance) {

    die("Clearance record not found.");

}


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

$stmt = $pdo->prepare("
    SELECT

        COUNT(*) AS total_contributions,

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

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

    FROM contributions

    WHERE subscription_id = ?
");

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

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


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

$stmt = $pdo->prepare("
    SELECT

        COUNT(*) AS total_defaults,

        COALESCE(
            SUM(amount),
            0
        ) AS total_default_amount

    FROM subscription_defaults

    WHERE subscription_id = ?
");

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

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


/*
|--------------------------------------------------------------------------
| 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');


/*
|--------------------------------------------------------------------------
| COMPANY SETTINGS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT company_name
    FROM settings
    ORDER BY id ASC
    LIMIT 1
");

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


$companyName =
    !empty($settings['company_name'])
        ? $settings['company_name']
        : 'Complete Bliss';


/*
|--------------------------------------------------------------------------
| SAFE IMAGE FILE NAME
|--------------------------------------------------------------------------
*/

$imageFileName =
    'Complete-Bliss-Clearance-'
    . preg_replace(
        '/[^A-Za-z0-9\-]/',
        '',
        $clearance['clearance_code']
    )
    . '.png';

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Clearance Evidence -
    <?= htmlspecialchars($clearance['clearance_code']); ?>
</title>


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


<style>

* {
    box-sizing: border-box;
}

body {
    margin: 0;
    padding: 30px 15px;
    background: #eef2f7;
    font-family: Arial, Helvetica, sans-serif;
    color: #1f2937;
}


/* ==========================================
   TOOLBAR
========================================== */

.certificate-toolbar {
    max-width: 850px;
    margin: 0 auto 18px;
    display: flex;
    justify-content: space-between;
    gap: 10px;
}

.certificate-toolbar a,
.certificate-toolbar button {
    min-height: 45px;
    padding: 0 18px;
    border: none;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;

    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.back-btn {
    background: #ffffff;
    color: #374151;
}

.image-btn {
    background: #2563eb;
    color: #ffffff;
}

.image-btn:disabled {
    opacity: .7;
    cursor: wait;
}


/* ==========================================
   CERTIFICATE
========================================== */

.clearance-certificate {
    width: 100%;
    max-width: 850px;
    margin: 0 auto;

    background: #ffffff;

    border-radius: 18px;

    overflow: hidden;

    border: 1px solid #e5e7eb;

    box-shadow:
        0 10px 40px
        rgba(15, 23, 42, 0.12);
}


/* ==========================================
   DECORATIVE TOP LINE
========================================== */

.certificate-accent {
    height: 8px;
    background: #2563eb;
}


/* ==========================================
   COMPANY
========================================== */

.certificate-top {
    padding: 34px 40px 27px;

    text-align: center;

    border-bottom: 1px solid #e5e7eb;
}

.certificate-logo {
    width: 78px;
    height: 78px;

    object-fit: contain;

    margin-bottom: 12px;
}

.certificate-company {
    margin: 0 0 5px;

    font-size: 24px;
    font-weight: 800;

    color: #111827;
}

.certificate-subtitle {
    margin: 0;

    font-size: 11px;

    color: #6b7280;

    text-transform: uppercase;

    letter-spacing: 1.8px;
}


/* ==========================================
   TITLE
========================================== */

.certificate-title-section {
    padding: 27px 40px;

    text-align: center;

    background: #f8fafc;
}

.certificate-title-section h1 {
    margin: 0 0 8px;

    font-size: 28px;

    color: #111827;
}

.certificate-title-section p {
    max-width: 650px;

    margin: 0 auto;

    font-size: 13px;

    line-height: 1.7;

    color: #6b7280;
}


/* ==========================================
   MEMBER
========================================== */

.certificate-member {
    padding: 26px 40px;

    text-align: center;
}

.certificate-member span {
    display: block;

    margin-bottom: 7px;

    font-size: 10px;

    text-transform: uppercase;

    letter-spacing: 1.2px;

    color: #9ca3af;
}

.certificate-member h2 {
    margin: 0;

    font-size: 27px;

    color: #2563eb;
}


/* ==========================================
   DETAILS
========================================== */

.certificate-details {
    padding: 0 40px 25px;

    display: grid;

    grid-template-columns:
        repeat(2, minmax(0, 1fr));

    gap: 13px;
}

.certificate-detail {
    padding: 15px;

    border-radius: 11px;

    background: #f8fafc;

    border: 1px solid #edf0f3;
}

.certificate-detail span {
    display: block;

    margin-bottom: 5px;

    font-size: 10px;

    text-transform: uppercase;

    letter-spacing: .4px;

    color: #6b7280;
}

.certificate-detail strong {
    font-size: 14px;

    color: #111827;
}


/* ==========================================
   STATUS CHECKS
========================================== */

.certificate-checks {
    padding: 0 40px 25px;

    display: grid;

    grid-template-columns:
        repeat(3, minmax(0, 1fr));

    gap: 13px;
}

.certificate-check {
    text-align: center;

    padding: 18px 12px;

    border: 1px solid #d1fae5;

    border-radius: 12px;

    background: #ecfdf5;
}

.certificate-check i {
    display: block;

    margin-bottom: 8px;

    color: #16a34a;

    font-size: 21px;
}

.certificate-check span {
    display: block;

    margin-bottom: 4px;

    font-size: 10px;

    text-transform: uppercase;

    color: #6b7280;
}

.certificate-check strong {
    color: #15803d;

    font-size: 13px;
}


/* ==========================================
   CLEARANCE CODE
========================================== */

.clearance-code-box {
    margin: 0 40px 25px;

    padding: 21px;

    text-align: center;

    border: 2px dashed #2563eb;

    border-radius: 13px;

    background: #eff6ff;
}

.clearance-code-box span {
    display: block;

    margin-bottom: 8px;

    font-size: 10px;

    color: #64748b;

    text-transform: uppercase;

    letter-spacing: 1px;
}

.clearance-code-box strong {
    font-size: 23px;

    letter-spacing: 2px;

    color: #1d4ed8;
}


/* ==========================================
   FOOTER
========================================== */

.certificate-footer {
    padding: 22px 40px 30px;

    text-align: center;

    border-top: 1px solid #e5e7eb;
}

.certificate-completed {
    display: inline-flex;

    align-items: center;

    gap: 7px;

    padding: 9px 15px;

    margin-bottom: 12px;

    border-radius: 999px;

    background: #dcfce7;

    color: #15803d;

    font-size: 12px;

    font-weight: 700;
}

.certificate-footer p {
    max-width: 650px;

    margin: 0 auto;

    color: #6b7280;

    font-size: 10px;

    line-height: 1.7;
}


/* ==========================================
   MOBILE DISPLAY
========================================== */

@media (max-width: 600px) {

    body {
        padding: 15px 10px;
    }

    .certificate-toolbar {
        flex-direction: column;
    }

    .certificate-toolbar a,
    .certificate-toolbar button {
        width: 100%;
    }

    .certificate-top,
    .certificate-title-section,
    .certificate-member,
    .certificate-footer {
        padding-left: 20px;
        padding-right: 20px;
    }

    .certificate-details {
        padding-left: 20px;
        padding-right: 20px;

        grid-template-columns: 1fr;
    }

    .certificate-checks {
        padding-left: 20px;
        padding-right: 20px;

        grid-template-columns: 1fr;
    }

    .clearance-code-box {
        margin-left: 20px;
        margin-right: 20px;
    }

    .certificate-title-section h1 {
        font-size: 21px;
    }

    .certificate-member h2 {
        font-size: 20px;
    }

    .clearance-code-box strong {
        font-size: 18px;

        word-break: break-word;
    }

    .clearance-verification-area {
    margin-left: 20px;
    margin-right: 20px;
    flex-direction: column;
}

.clearance-qr-box {
    width: 100%;
}

#clearanceQrCode {
    margin: 0 auto;
}

}


/* ==========================================
   EXPORT MODE
==========================================

   This forces the generated PNG to use the
   proper certificate desktop layout even when
   downloaded from a small phone.
========================================== */

body.exporting-certificate
.clearance-certificate {

    width: 850px !important;
    max-width: 850px !important;

    border-radius: 18px !important;
}


body.exporting-certificate
.certificate-top,

body.exporting-certificate
.certificate-title-section,

body.exporting-certificate
.certificate-member,

body.exporting-certificate
.certificate-footer {

    padding-left: 40px !important;
    padding-right: 40px !important;
}


body.exporting-certificate
.certificate-details {

    padding-left: 40px !important;
    padding-right: 40px !important;

    grid-template-columns:
        repeat(2, minmax(0, 1fr))
        !important;
}


body.exporting-certificate
.certificate-checks {

    padding-left: 40px !important;
    padding-right: 40px !important;

    grid-template-columns:
        repeat(3, minmax(0, 1fr))
        !important;
}


body.exporting-certificate
.clearance-code-box {

    margin-left: 40px !important;
    margin-right: 40px !important;
}


body.exporting-certificate
.certificate-title-section h1 {

    font-size: 28px !important;
}


body.exporting-certificate
.certificate-member h2 {

    font-size: 27px !important;
}


body.exporting-certificate
.clearance-code-box strong {

    font-size: 23px !important;

    word-break: normal !important;
}

body.exporting-certificate
.clearance-verification-area {

    margin-left: 40px !important;
    margin-right: 40px !important;

    flex-direction: row !important;
}


body.exporting-certificate
.clearance-qr-box {

    width: 145px !important;
    min-width: 145px !important;
}


/* ==========================================
   QR VERIFICATION
========================================== */

.clearance-verification-area {
    margin: 0 40px 25px;
    display: flex;
    align-items: stretch;
    gap: 15px;
}

.clearance-verification-area .clearance-code-box {
    flex: 1;
    margin: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.clearance-qr-box {
    width: 145px;
    min-width: 145px;
    padding: 12px;
    border-radius: 13px;
    border: 1px solid #dbe3ed;
    background: #ffffff;
    text-align: center;
}

#clearanceQrCode {
    display: flex;
    justify-content: center;
    align-items: center;
}

#clearanceQrCode img,
#clearanceQrCode canvas {
    display: block;
    width: 105px !important;
    height: 105px !important;
}

.clearance-qr-box small {
    display: block;
    margin-top: 8px;
    color: #64748b;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .5px;
}

</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

</head>


<body>


<!-- ==========================================
     TOOLBAR
========================================== -->

<div class="certificate-toolbar">

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

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

        Back to Clearance

    </a>


    <button
        type="button"
        class="image-btn"
        id="saveImageBtn"
    >

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

        Save Clearance Image

    </button>

</div>



<!-- ==========================================
     CERTIFICATE
========================================== -->

<div
    class="clearance-certificate"
    id="clearanceCertificate"
>


    <div class="certificate-accent"></div>


    <!-- COMPANY -->

    <div class="certificate-top">

        <img
            src="../assets/images/logo.png"
            alt="Complete Bliss Logo"
            class="certificate-logo"
        >

        <h2 class="certificate-company">

            <?= htmlspecialchars(
                $companyName
            ); ?>

        </h2>

        <p class="certificate-subtitle">

            Scheme Clearance Confirmation

        </p>

    </div>



    <!-- TITLE -->

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

        <h1>
            Clearance Certificate
        </h1>

        <p>

            This certifies that the member named below
            has successfully completed all required
            clearance obligations for the stated scheme.

        </p>

    </div>



    <!-- MEMBER -->

    <div class="certificate-member">

        <span>
            This certificate is awarded to
        </span>

        <h2>

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

        </h2>

    </div>



    <!-- DETAILS -->

    <div class="certificate-details">


        <div class="certificate-detail">

            <span>
                Scheme
            </span>

            <strong>

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

            </strong>

        </div>


        <div class="certificate-detail">

            <span>
                Number of Hands
            </span>

            <strong>

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

            </strong>

        </div>


        <div class="certificate-detail">

            <span>
                Frequency
            </span>

            <strong>

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

            </strong>

        </div>


        <div class="certificate-detail">

            <span>
                Scheme Period
            </span>

            <strong>

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

                –

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

            </strong>

        </div>


        <div class="certificate-detail">

            <span>
                Clearance Date
            </span>

            <strong>

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

            </strong>

        </div>


        <div class="certificate-detail">

            <span>
                Defaults Settled During Clearance
            </span>

            <strong>

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

            </strong>

        </div>


    </div>



    <!-- STATUS -->

    <div class="certificate-checks">


        <div class="certificate-check">

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

            <span>
                Contributions
            </span>

            <strong>
                Fully Settled
            </strong>

        </div>


        <div class="certificate-check">

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

            <span>
                Defaults
            </span>

            <strong>
                Fully Settled
            </strong>

        </div>


        <div class="certificate-check">

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

            <span>
                Clearance
            </span>

            <strong>
                Completed
            </strong>

        </div>


    </div>



    <!-- CLEARANCE CODE -->

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


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

        <span>
            Unique Clearance Code
        </span>

        <strong>

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

        </strong>

    </div>


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

        <div id="clearanceQrCode"></div>

        <small>
            Scan to Verify
        </small>

    </div>


</div>



    <!-- FOOTER -->

    <div class="certificate-footer">


        <div class="certificate-completed">

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

            VERIFIED CLEARANCE

        </div>


        <p>

            This is a system-generated clearance
            confirmation issued by
            <?= htmlspecialchars($companyName); ?>.
            The unique clearance code above can be
            used to verify this clearance record.

        </p>


    </div>


</div>



<!-- ==========================================
     HTML2CANVAS
========================================== -->

<script
src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js">
</script>

<script>

const clearanceVerificationUrl =
    <?= json_encode(
        (
            (!empty($_SERVER['HTTPS']) &&
             $_SERVER['HTTPS'] !== 'off')
                ? 'https'
                : 'http'
        )
        . '://'
        . ($_SERVER['HTTP_HOST'] ?? 'localhost')
        . rtrim(
            dirname(
                dirname(
                    $_SERVER['SCRIPT_NAME']
                )
            ),
            '/'
        )
        . '/verify_clearance.php?code='
        . rawurlencode(
            $clearance['clearance_code']
        )
    ); ?>;


new QRCode(
    document.getElementById(
        "clearanceQrCode"
    ),
    {
        text: clearanceVerificationUrl,
        width: 105,
        height: 105,
        correctLevel: QRCode.CorrectLevel.H
    }
);

</script>


<script>

const saveImageButton =
    document.getElementById(
        "saveImageBtn"
    );

const certificate =
    document.getElementById(
        "clearanceCertificate"
    );


saveImageButton.addEventListener(
    "click",
    async function () {


        /*
        |--------------------------------------------------------------------------
        | Disable Button While Creating Image
        |--------------------------------------------------------------------------
        */

        saveImageButton.disabled = true;

        const originalButtonContent =
            saveImageButton.innerHTML;


        saveImageButton.innerHTML =
            '<i class="fas fa-spinner fa-spin"></i> Creating Image...';


        /*
        |--------------------------------------------------------------------------
        | Force Full Certificate Layout
        |--------------------------------------------------------------------------
        */

        document.body.classList.add(
            "exporting-certificate"
        );


        try {


            /*
            |--------------------------------------------------------------------------
            | Wait For Images
            |--------------------------------------------------------------------------
            */

            const images =
                certificate.querySelectorAll(
                    "img"
                );


            await Promise.all(

                Array.from(images).map(
                    function (image) {

                        if (image.complete) {

                            return Promise.resolve();

                        }

                        return new Promise(
                            function (resolve) {

                                image.onload =
                                    resolve;

                                image.onerror =
                                    resolve;

                            }
                        );

                    }
                )

            );


            /*
            |--------------------------------------------------------------------------
            | Generate High Quality PNG
            |--------------------------------------------------------------------------
            */

            const canvas =
                await html2canvas(
                    certificate,
                    {

                        scale: 3,

                        backgroundColor:
                            "#ffffff",

                        useCORS: true,

                        allowTaint: false,

                        logging: false

                    }
                );


            /*
            |--------------------------------------------------------------------------
            | Convert To PNG & Download
            |--------------------------------------------------------------------------
            */

            canvas.toBlob(
                function (blob) {

                    if (!blob) {

                        alert(
                            "Unable to create clearance image."
                        );

                        return;

                    }


                    const imageUrl =
                        URL.createObjectURL(
                            blob
                        );


                    const downloadLink =
                        document.createElement(
                            "a"
                        );


                    downloadLink.href =
                        imageUrl;


                    downloadLink.download =
                        <?= json_encode(
                            $imageFileName
                        ); ?>;


                    document.body.appendChild(
                        downloadLink
                    );


                    downloadLink.click();


                    document.body.removeChild(
                        downloadLink
                    );


                    setTimeout(
                        function () {

                            URL.revokeObjectURL(
                                imageUrl
                            );

                        },
                        1000
                    );

                },
                "image/png",
                1
            );


        } catch (error) {

            console.error(error);

            alert(
                "Unable to create clearance image. Please try again."
            );

        } finally {


            /*
            |--------------------------------------------------------------------------
            | Restore Normal Page
            |--------------------------------------------------------------------------
            */

            document.body.classList.remove(
                "exporting-certificate"
            );


            saveImageButton.disabled =
                false;


            saveImageButton.innerHTML =
                originalButtonContent;

        }

    }
);

</script>


</body>

</html>