<?php

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


/*
|--------------------------------------------------------------------------
| TEST MODE ONLY
|--------------------------------------------------------------------------
*/

if (!paystackIsConfigured()) {

    die(
        "Paystack Test Mode is not configured correctly."
    );

}


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

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

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

}


/*
|--------------------------------------------------------------------------
| NORMALIZE NIGERIAN PHONE
|--------------------------------------------------------------------------
*/

function normalizeNigerianPhone($phone)
{

    $phone =
        preg_replace(
            '/[^0-9+]/',
            '',
            trim($phone)
        );


    if (
        preg_match(
            '/^0[789][01]\d{8}$/',
            $phone
        )
    ) {

        return
            '+234'
            .
            substr($phone, 1);

    }


    if (
        preg_match(
            '/^234[789][01]\d{8}$/',
            $phone
        )
    ) {

        return
            '+'
            .
            $phone;

    }


    return $phone;

}


/*
|--------------------------------------------------------------------------
| HANDLE CUSTOMER CREATION
|--------------------------------------------------------------------------
*/

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


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

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


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

        $_SESSION['error'] =
            "Invalid request. Please try again.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


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

    $userId =
        (int)($_POST['user_id'] ?? 0);


    if ($userId <= 0) {

        $_SESSION['error'] =
            "Please select a member.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    $stmt = $pdo->prepare("
        SELECT
            id,
            fullname,
            email,
            phone,
            status,
            role
        FROM users

        WHERE
            id = ?
            AND role = 'member'

        LIMIT 1
    ");


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


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


    if (!$member) {

        $_SESSION['error'] =
            "Member not found.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | ACCOUNT STATUS
    |--------------------------------------------------------------------------
    */

    if ($member['status'] !== 'active') {

        $_SESSION['error'] =
            "Only active members can be prepared for Paystack.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | EMAIL VALIDATION
    |--------------------------------------------------------------------------
    */

    $email =
        trim(
            $member['email'] ?? ''
        );


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

        $_SESSION['error'] =
            "This member needs a valid email address before a Paystack customer can be created.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | PREVENT DUPLICATE PAYSTACK CUSTOMER
    |--------------------------------------------------------------------------
    */

    $existingStmt =
        $pdo->prepare("
            SELECT
                id,
                customer_code
            FROM member_virtual_accounts

            WHERE
                user_id = ?
                AND provider = 'paystack'
                AND environment = 'test'

            LIMIT 1
        ");


    $existingStmt->execute([
        $member['id']
    ]);


    $existing =
        $existingStmt->fetch(
            PDO::FETCH_ASSOC
        );


    if ($existing) {

        $_SESSION['error'] =
            "This member already has a Paystack Test Mode customer record.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | PREPARE FIRST / LAST NAME
    |--------------------------------------------------------------------------
    */

    $fullName =
        trim(
            preg_replace(
                '/\s+/',
                ' ',
                $member['fullname']
            )
        );


    $nameParts =
        preg_split(
            '/\s+/',
            $fullName
        );


    if (count($nameParts) < 2) {

        $_SESSION['error'] =
            "The member must have at least a first name and last name before Paystack setup.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    $firstName =
        array_shift(
            $nameParts
        );


    $lastName =
        implode(
            ' ',
            $nameParts
        );


    $phone =
        normalizeNigerianPhone(
            $member['phone']
        );


    /*
    |--------------------------------------------------------------------------
    | PAYSTACK REQUEST DATA
    |--------------------------------------------------------------------------
    */

    $requestData = [

        'email' =>
            $email,

        'first_name' =>
            $firstName,

        'last_name' =>
            $lastName,

        'phone' =>
            $phone,

        'metadata' => [

            'complete_bliss_user_id' =>
                (int)$member['id']

        ]

    ];


    /*
    |--------------------------------------------------------------------------
    | CALL PAYSTACK
    |--------------------------------------------------------------------------
    */

    $curl =
        curl_init();


    curl_setopt_array(
        $curl,
        [

            CURLOPT_URL =>
                $paystackBaseUrl
                .
                '/customer',

            CURLOPT_POST =>
                true,

            CURLOPT_RETURNTRANSFER =>
                true,

            CURLOPT_HTTPHEADER => [

                'Authorization: Bearer '
                .
                $paystackSecretKey,

                'Content-Type: application/json',

                'Accept: application/json'

            ],

            CURLOPT_POSTFIELDS =>
                json_encode(
                    $requestData
                ),

            CURLOPT_TIMEOUT =>
                30

        ]
    );


    $response =
        curl_exec(
            $curl
        );


    $httpCode =
        curl_getinfo(
            $curl,
            CURLINFO_HTTP_CODE
        );


    $curlError =
        curl_error(
            $curl
        );


    curl_close(
        $curl
    );


    /*
    |--------------------------------------------------------------------------
    | CONNECTION ERROR
    |--------------------------------------------------------------------------
    */

    if ($curlError) {

        $_SESSION['error'] =
            "Unable to connect to Paystack: "
            .
            $curlError;

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    $responseData =
        json_decode(
            $response,
            true
        );


    /*
    |--------------------------------------------------------------------------
    | PAYSTACK ERROR
    |--------------------------------------------------------------------------
    */

    if (
        $httpCode !== 200
        ||
        empty(
            $responseData['status']
        )
        ||
        empty(
            $responseData['data']
        )
    ) {

        $_SESSION['error'] =
            $responseData['message']
            ??
            "Paystack could not create the customer.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | GET PAYSTACK CUSTOMER DETAILS
    |--------------------------------------------------------------------------
    */

    $paystackCustomer =
        $responseData['data'];


    $providerCustomerId =
        $paystackCustomer['id']
        ?? null;


    $customerCode =
        $paystackCustomer['customer_code']
        ?? null;


    if (
        !$providerCustomerId
        ||
        !$customerCode
    ) {

        $_SESSION['error'] =
            "Paystack created the customer but returned incomplete customer information.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | SAVE TO COMPLETE BLISS
    |--------------------------------------------------------------------------
    */

    try {


        $saveStmt =
            $pdo->prepare("
                INSERT INTO member_virtual_accounts
                (
                    user_id,
                    provider,
                    environment,
                    provider_customer_id,
                    customer_code,
                    validation_status,
                    assigned,
                    active
                )

                VALUES
                (
                    ?,
                    'paystack',
                    'test',
                    ?,
                    ?,
                    'not_started',
                    0,
                    0
                )
            ");


        $saveStmt->execute([

            $member['id'],

            $providerCustomerId,

            $customerCode

        ]);


    } catch (Exception $e) {


        $_SESSION['error'] =
            "The Paystack customer was created, but Complete Bliss could not save the customer record. Do not retry yet.";

        header(
            "Location: paystack-create-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | SUCCESS
    |--------------------------------------------------------------------------
    */

    $_SESSION['success'] =
        "Paystack Test customer created successfully for "
        .
        $member['fullname']
        .
        ".";


    $_SESSION['created_customer_code'] =
        $customerCode;


    header(
        "Location: paystack-create-customer.php"
    );

    exit();

}


/*
|--------------------------------------------------------------------------
| GET ELIGIBLE MEMBERS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT
        u.id,
        u.fullname,
        u.phone,
        u.email

    FROM users u

    LEFT JOIN member_virtual_accounts mva

        ON mva.user_id = u.id

        AND mva.provider = 'paystack'

        AND mva.environment = 'test'

    WHERE

        u.role = 'member'

        AND u.status = 'active'

        AND u.email IS NOT NULL

        AND u.email != ''

        AND mva.id IS NULL

    ORDER BY
        u.fullname ASC
");


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

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Create Paystack Test Customer
</title>


<style>

body {

    margin: 0;

    padding: 40px 20px;

    font-family: Arial, sans-serif;

    background: #f5f7fb;

    color: #101828;

}


.paystack-test-box {

    width: 100%;

    max-width: 650px;

    margin: 0 auto;

    padding: 30px;

    box-sizing: border-box;

    border-radius: 16px;

    background: #ffffff;

}


.paystack-test-badge {

    display: inline-block;

    margin-bottom: 10px;

    padding: 6px 10px;

    border-radius: 999px;

    color: #1d4ed8;

    background: #eff6ff;

    font-size: 11px;

    font-weight: 700;

}


h1 {

    margin: 0 0 8px;

    font-size: 25px;

}


.subtitle {

    margin: 0 0 25px;

    color: #667085;

    font-size: 13px;

    line-height: 1.6;

}


label {

    display: block;

    margin-bottom: 8px;

    font-size: 12px;

    font-weight: 700;

}


select {

    width: 100%;

    height: 48px;

    padding: 0 12px;

    box-sizing: border-box;

    border: 1px solid #d0d5dd;

    border-radius: 9px;

    background: #ffffff;

}


button {

    width: 100%;

    min-height: 48px;

    margin-top: 18px;

    border: 0;

    border-radius: 9px;

    color: #ffffff;

    background: #2563eb;

    cursor: pointer;

    font-weight: 700;

}


.notice {

    margin-top: 20px;

    padding: 14px;

    border-radius: 10px;

    color: #475467;

    background: #f8fafc;

    font-size: 12px;

    line-height: 1.6;

}


.success {

    margin-bottom: 20px;

    padding: 14px;

    border-radius: 10px;

    color: #15803d;

    background: #ecfdf3;

}


.error {

    margin-bottom: 20px;

    padding: 14px;

    border-radius: 10px;

    color: #b42318;

    background: #fef3f2;

}


.customer-code {

    display: block;

    margin-top: 7px;

    font-family: monospace;

    font-weight: 700;

}

</style>

</head>


<body>


<div class="paystack-test-box">


    <span class="paystack-test-badge">
        PAYSTACK TEST MODE
    </span>


    <h1>
        Create Test Customer
    </h1>


    <p class="subtitle">
        Select one Complete Bliss member to create
        as a Paystack Test Mode customer.
        No money will be moved.
    </p>



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


        <div class="success">

            <?= htmlspecialchars(
                $_SESSION['success']
            ); ?>


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

                <span class="customer-code">

                    <?= htmlspecialchars(
                        $_SESSION[
                            'created_customer_code'
                        ]
                    ); ?>

                </span>

            <?php endif; ?>


        </div>


    <?php

    unset($_SESSION['success']);
    unset($_SESSION['created_customer_code']);

    endif;

    ?>



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


        <div class="error">

            <?= htmlspecialchars(
                $_SESSION['error']
            ); ?>

        </div>


    <?php

    unset($_SESSION['error']);

    endif;

    ?>



    <?php if (!empty($members)): ?>


        <form method="POST">


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


            <label for="user_id">
                Select Test Member
            </label>


            <select
                id="user_id"
                name="user_id"
                required
            >


                <option value="">
                    -- Select Member --
                </option>


                <?php foreach (
                    $members as $member
                ): ?>


                    <option
                        value="<?= (int)$member['id']; ?>"
                    >

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

                        —

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

                    </option>


                <?php endforeach; ?>


            </select>


            <button type="submit">

                Create Paystack Test Customer

            </button>


        </form>


    <?php else: ?>


        <div class="notice">

            There are currently no eligible members
            without a Paystack Test customer.

        </div>


    <?php endif; ?>


    <div class="notice">

        <strong>Important:</strong>

        This creates only a Paystack customer profile.
        It does not create a bank account,
        credit a wallet or move real money.

    </div>


</div>


</body>

</html>