<?php

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


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


/*
|--------------------------------------------------------------------------
| Disable Form Caching
|--------------------------------------------------------------------------
*/

header(
    "Cache-Control: no-store, no-cache, must-revalidate, max-age=0"
);

header("Pragma: no-cache");
header("Expires: 0");


/*
|--------------------------------------------------------------------------
| CSRF Token
|--------------------------------------------------------------------------
*/

if (
    empty(
        $_SESSION[
            'funding_account_csrf'
        ]
    )
) {

    $_SESSION[
        'funding_account_csrf'
    ] =
        bin2hex(
            random_bytes(32)
        );

}


/*
|--------------------------------------------------------------------------
| Get Member
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        id,
        fullname,
        email,
        phone,
        status
    FROM users
    WHERE id = ?
    LIMIT 1
");

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

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


if (!$user) {

    header(
        "Location: dashboard.php"
    );

    exit();

}


/*
|--------------------------------------------------------------------------
| Check Existing Live Virtual Account
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        bank_name,
        account_name,
        account_number
    FROM member_virtual_accounts
    WHERE
        user_id = ?
        AND provider = 'paystack'
        AND environment = 'live'
        AND assigned = 1
        AND active = 1
    LIMIT 1
");

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

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


/*
|--------------------------------------------------------------------------
| Existing Funding Request
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        id,
        email,
        consent_given,
        consent_at,
        status,
        failure_reason,
        requested_at,
        updated_at
    FROM funding_account_requests
    WHERE
        user_id = ?
        AND provider = 'paystack'
    LIMIT 1
");

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

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


/*
|--------------------------------------------------------------------------
| Handle Activation Request
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD']
    === 'POST'
) {


    /*
    |--------------------------------------------------------------------------
    | CSRF
    |--------------------------------------------------------------------------
    */

    $csrfToken =
        $_POST['csrf_token']
        ?? '';


    if (
        !hash_equals(
            $_SESSION[
                'funding_account_csrf'
            ],
            $csrfToken
        )
    ) {

        $_SESSION[
            'funding_account_error'
        ] =
            "Your session has expired. Please try again.";

        header(
            "Location: activate-funding-account.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Already Activated
    |--------------------------------------------------------------------------
    */

    if ($virtualAccount) {

        $_SESSION[
            'funding_account_error'
        ] =
            "Your personal funding account is already active.";

        header(
            "Location: wallet.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Prevent Duplicate Pending Request
    |--------------------------------------------------------------------------
    */

    if (
        $fundingRequest
        &&
        in_array(
            $fundingRequest['status'],
            [
                'pending',
                'processing',
                'activated'
            ],
            true
        )
    ) {

        $_SESSION[
            'funding_account_error'
        ] =
            "You already have an active funding account request.";

        header(
            "Location: activate-funding-account.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Receive Form Data
    |--------------------------------------------------------------------------
    */

    $email =
        strtolower(
            trim(
                $_POST['email']
                ?? ''
            )
        );


    $consent =
        isset(
            $_POST['consent']
        );


    /*
    |--------------------------------------------------------------------------
    | Validate Email
    |--------------------------------------------------------------------------
    */

    if (
        $email === ''
        ||
        !filter_var(
            $email,
            FILTER_VALIDATE_EMAIL
        )
    ) {

        $_SESSION[
            'funding_account_error'
        ] =
            "Please provide a valid email address.";

        $_SESSION[
            'funding_account_old_email'
        ] =
            $email;

        header(
            "Location: activate-funding-account.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Check Email Is Not Used By Another Member
    |--------------------------------------------------------------------------
    */

    $emailCheck =
        $pdo->prepare("
            SELECT id
            FROM users
            WHERE
                email = ?
                AND id != ?
            LIMIT 1
        ");


    $emailCheck->execute([

        $email,

        $user_id

    ]);


    if (
        $emailCheck->fetchColumn()
    ) {

        $_SESSION[
            'funding_account_error'
        ] =
            "This email address is already connected to another Complete Bliss account.";

        $_SESSION[
            'funding_account_old_email'
        ] =
            $email;

        header(
            "Location: activate-funding-account.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Consent Required
    |--------------------------------------------------------------------------
    */

    if (!$consent) {

        $_SESSION[
            'funding_account_error'
        ] =
            "Please confirm your consent before requesting a funding account.";

        $_SESSION[
            'funding_account_old_email'
        ] =
            $email;

        header(
            "Location: activate-funding-account.php"
        );

        exit();

    }


    try {


        /*
        |--------------------------------------------------------------------------
        | Begin Transaction
        |--------------------------------------------------------------------------
        */

        $pdo->beginTransaction();


        /*
        |--------------------------------------------------------------------------
        | Save / Update Member Email
        |--------------------------------------------------------------------------
        */

        $updateUser =
            $pdo->prepare("
                UPDATE users

                SET email = ?

                WHERE id = ?
            ");


        $updateUser->execute([

            $email,

            $user_id

        ]);


        /*
        |--------------------------------------------------------------------------
        | Create Or Reopen Funding Request
        |--------------------------------------------------------------------------
        */

        if ($fundingRequest) {


            $requestStmt =
                $pdo->prepare("
                    UPDATE funding_account_requests

                    SET
                        email = ?,
                        consent_given = 1,
                        consent_at = NOW(),
                        status = 'pending',
                        failure_reason = NULL,
                        requested_at = CURRENT_TIMESTAMP

                    WHERE
                        id = ?
                        AND user_id = ?
                ");


            $requestStmt->execute([

                $email,

                $fundingRequest['id'],

                $user_id

            ]);


        } else {


            $requestStmt =
                $pdo->prepare("
                    INSERT INTO funding_account_requests
                    (
                        user_id,
                        provider,
                        email,
                        consent_given,
                        consent_at,
                        status
                    )

                    VALUES
                    (
                        ?,
                        'paystack',
                        ?,
                        1,
                        NOW(),
                        'pending'
                    )
                ");


            $requestStmt->execute([

                $user_id,

                $email

            ]);

        }


        /*
        |--------------------------------------------------------------------------
        | Commit
        |--------------------------------------------------------------------------
        */

        $pdo->commit();


        unset(
            $_SESSION[
                'funding_account_old_email'
            ]
        );


        $_SESSION[
            'funding_account_success'
        ] =
            "Your funding account activation request has been submitted successfully.";


        header(
            "Location: activate-funding-account.php"
        );

        exit();


    } catch (Exception $e) {


        if (
            $pdo->inTransaction()
        ) {

            $pdo->rollBack();

        }


        $_SESSION[
            'funding_account_error'
        ] =
            "Unable to submit your funding account request right now. Please try again.";


        header(
            "Location: activate-funding-account.php"
        );

        exit();

    }

}


/*
|--------------------------------------------------------------------------
| Reload Funding Request After Possible POST
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        id,
        email,
        consent_given,
        consent_at,
        status,
        failure_reason,
        requested_at,
        updated_at
    FROM funding_account_requests
    WHERE
        user_id = ?
        AND provider = 'paystack'
    LIMIT 1
");

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

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


/*
|--------------------------------------------------------------------------
| Form Email
|--------------------------------------------------------------------------
*/

$formEmail =
    $_SESSION[
        'funding_account_old_email'
    ]
    ??
    $user['email']
    ??
    '';


unset(
    $_SESSION[
        'funding_account_old_email'
    ]
);


/*
|--------------------------------------------------------------------------
| Flash Messages
|--------------------------------------------------------------------------
*/

$successMessage =
    $_SESSION[
        'funding_account_success'
    ]
    ?? null;


$errorMessage =
    $_SESSION[
        'funding_account_error'
    ]
    ?? null;


unset(
    $_SESSION[
        'funding_account_success'
    ],
    $_SESSION[
        'funding_account_error'
    ]
);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Activate Funding Account
</title>


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


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


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


<link
    rel="stylesheet"
    href="../assets/css/member-funding-account.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-funding-page">


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

    <div class="member-funding-header">


        <div>


            <a
                href="wallet.php"
                class="member-funding-back"
            >

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

                Back to Wallet

            </a>


            <h1>

                <i class="fas fa-building-columns"></i>

                Personal Funding Account

            </h1>


            <p>
                Request a personal bank account that
                can be used to fund your Complete Bliss wallet.
            </p>


        </div>


        <div class="member-funding-header-icon">

            <i class="fas fa-building-columns"></i>

        </div>


    </div>



    <!-- =====================================================
         EXISTING LIVE ACCOUNT
    ====================================================== -->

    <?php if ($virtualAccount): ?>


        <section class="member-funding-card">


            <div class="member-funding-success-icon">

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

            </div>


            <span class="member-funding-label success">
                ACCOUNT ACTIVE
            </span>


            <h2>
                Your funding account is ready
            </h2>


            <p>
                Transfer funds to this account to fund
                your Complete Bliss wallet.
            </p>


            <div class="member-funding-bank-card">


                <span>
                    BANK
                </span>


                <strong>

                    <?= htmlspecialchars(
                        $virtualAccount[
                            'bank_name'
                        ]
                    ); ?>

                </strong>


                <span>
                    ACCOUNT NUMBER
                </span>


                <h3>

                    <?= htmlspecialchars(
                        $virtualAccount[
                            'account_number'
                        ]
                    ); ?>

                </h3>


                <span>
                    ACCOUNT NAME
                </span>


                <strong>

                    <?= htmlspecialchars(
                        $virtualAccount[
                            'account_name'
                        ]
                    ); ?>

                </strong>


            </div>


        </section>



    <!-- =====================================================
         PENDING / PROCESSING REQUEST
    ====================================================== -->

    <?php elseif (
        $fundingRequest
        &&
        in_array(
            $fundingRequest['status'],
            [
                'pending',
                'processing'
            ],
            true
        )
    ): ?>


        <section class="member-funding-card">


            <div class="member-funding-pending-icon">

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

            </div>


            <span class="member-funding-label pending">
                ACTIVATION PENDING
            </span>


            <h2>
                Your request has been received
            </h2>


            <p>
                Complete Bliss is preparing your personal
                funding account. You will be able to view
                the account details here once activation
                is completed.
            </p>


            <div class="member-funding-request-details">


                <div>

                    <span>
                        Email
                    </span>

                    <strong>

                        <?= htmlspecialchars(
                            $fundingRequest[
                                'email'
                            ]
                        ); ?>

                    </strong>

                </div>


                <div>

                    <span>
                        Requested
                    </span>

                    <strong>

                        <?= date(
                            'd M Y, h:i A',
                            strtotime(
                                $fundingRequest[
                                    'requested_at'
                                ]
                            )
                        ); ?>

                    </strong>

                </div>


                <div>

                    <span>
                        Status
                    </span>

                    <strong class="pending-text">

                        <?= ucfirst(
                            htmlspecialchars(
                                $fundingRequest[
                                    'status'
                                ]
                            )
                        ); ?>

                    </strong>

                </div>


            </div>


            <div class="member-funding-notice">

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

                <p>
                    No payment is required to submit this
                    activation request.
                </p>

            </div>


        </section>



    <!-- =====================================================
         ACTIVATION FORM
    ====================================================== -->

    <?php else: ?>


        <div class="member-funding-layout">


            <!-- FORM -->

            <section class="member-funding-card">


                <span class="member-funding-label">
                    ACCOUNT ACTIVATION
                </span>


                <h2>
                    Activate your funding account
                </h2>


                <p>
                    Confirm your email address and provide
                    consent for Complete Bliss to prepare
                    your personal funding account.
                </p>



                <?php if (
                    $fundingRequest
                    &&
                    $fundingRequest[
                        'status'
                    ] === 'failed'
                ): ?>


                    <div class="member-funding-error-note">

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


                        <div>

                            <strong>
                                Previous activation was incomplete
                            </strong>


                            <p>

                                <?= htmlspecialchars(
                                    $fundingRequest[
                                        'failure_reason'
                                    ]
                                    ??
                                    'Please review your details and try again.'
                                ); ?>

                            </p>

                        </div>


                    </div>


                <?php endif; ?>



                <form
                    method="POST"
                    class="member-funding-form"
                >


                    <input
                        type="hidden"
                        name="csrf_token"
                        value="<?= htmlspecialchars(
                            $_SESSION[
                                'funding_account_csrf'
                            ]
                        ); ?>"
                    >



                    <!-- EMAIL -->

                    <div class="member-funding-field">


                        <label for="email">

                            Email Address

                        </label>


                        <div class="member-funding-input">


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


                            <input
                                type="email"
                                id="email"
                                name="email"
                                value="<?= htmlspecialchars(
                                    $formEmail
                                ); ?>"
                                placeholder="Enter your active email address"
                                autocomplete="email"
                                required
                            >


                        </div>


                        <small>
                            This email will be used for your
                            funding-account setup and payment
                            identification.
                        </small>


                    </div>



                    <!-- CONSENT -->

                    <label class="member-funding-consent">


                        <input
                            type="checkbox"
                            name="consent"
                            value="1"
                            required
                        >


                        <span>

                            <strong>
                                I consent to funding account setup
                            </strong>

                            <small>
                                I authorize Complete Bliss Solutions
                                to use my name, phone number and email
                                address with its approved payment
                                service provider for the purpose of
                                creating and managing my personal
                                funding account. I understand that
                                additional identity verification may
                                be required before activation.
                            </small>

                        </span>


                    </label>



                    <button
                        type="submit"
                        class="member-funding-submit"
                    >

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

                        Submit Activation Request

                    </button>


                </form>


            </section>



            <!-- HOW IT WORKS -->

            <aside class="member-funding-side-card">


                <div class="member-funding-side-icon">

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

                </div>


                <h3>
                    How it works
                </h3>


                <div class="member-funding-step">


                    <span>
                        1
                    </span>


                    <div>

                        <strong>
                            Request activation
                        </strong>

                        <p>
                            Confirm your email and consent
                            to account setup.
                        </p>

                    </div>


                </div>


                <div class="member-funding-step">


                    <span>
                        2
                    </span>


                    <div>

                        <strong>
                            Account verification
                        </strong>

                        <p>
                            Additional verification may be
                            requested when required.
                        </p>

                    </div>


                </div>


                <div class="member-funding-step">


                    <span>
                        3
                    </span>


                    <div>

                        <strong>
                            Receive account details
                        </strong>

                        <p>
                            Your personal account will appear
                            in your wallet after activation.
                        </p>

                    </div>


                </div>


                <div class="member-funding-step">


                    <span>
                        4
                    </span>


                    <div>

                        <strong>
                            Fund your wallet
                        </strong>

                        <p>
                            Transfers to your funding account
                            can then be credited to your
                            Complete Bliss wallet after
                            payment confirmation.
                        </p>

                    </div>


                </div>


                <div class="member-funding-security">

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

                    <p>
                        Complete Bliss will never ask for
                        your ATM PIN, card PIN, banking
                        password or OTP.
                    </p>

                </div>


            </aside>


        </div>


    <?php endif; ?>


</main>


</div>



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


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



<?php if ($successMessage): ?>

<script>

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

        Swal.fire({

            icon:
                "success",

            title:
                "Request Submitted",

            text:
                <?= json_encode(
                    $successMessage
                ); ?>,

            confirmButtonColor:
                "#2563eb"

        });

    }
);

</script>

<?php endif; ?>



<?php if ($errorMessage): ?>

<script>

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

        Swal.fire({

            icon:
                "error",

            title:
                "Unable to Continue",

            text:
                <?= json_encode(
                    $errorMessage
                ); ?>,

            confirmButtonColor:
                "#dc3545"

        });

    }
);

</script>

<?php endif; ?>


</body>

</html>