<?php
/**
 * ManiPay Gateway
 *
 * @package ManiPay\FluentCart
 */

namespace ManiPay\FluentCart;

use FluentCart\App\Modules\PaymentMethods\Core\AbstractPaymentGateway;
use FluentCart\App\Services\Payments\PaymentInstance;

/**
 * Manual payment gateway: bKash/Nagad/Rocket, 4 banks with slip upload, and
 * RedotPay. This is a redirect-style gateway — makePaymentFromPaymentInstance()
 * sends the customer to our own on-site page rather than an external processor,
 * following the "hosted checkout" return pattern documented by FluentCart
 * (return an array with 'redirect_to').
 */
class Gateway extends AbstractPaymentGateway {

    public array $supportedFeatures = array( 'payment' );

    public function __construct() {
        parent::__construct( new Settings() );
    }

    public function boot() {
        // No webhook/IPN handlers needed — this gateway never receives external callbacks.
    }

    public function meta(): array {
        return array(
            'title'              => $this->settings->get( 'display_name' ) ?: __( 'Mobile Banking, Bank & Crypto', 'manipay-manual-payment-for-fluentcart' ),
            'route'              => 'pxelcode_pay',
            'slug'               => 'pxelcode_pay',
            'description'        => __( 'bKash, Nagad, Rocket, Bank Transfer & Crypto — manual, verified by you.', 'manipay-manual-payment-for-fluentcart' ),
            'logo'               => MANIPAY_FC_URL . 'assets/images/gateway-icon.png',
            'icon'               => MANIPAY_FC_URL . 'assets/images/gateway-icon.png',
            'brand_color'        => '#0b6e4f',
            'status'             => $this->settings->isActive(),
            'upcoming'           => false,
            'supported_features' => $this->supportedFeatures,
        );
    }

    public function has( string $feature ): bool {
        return in_array( $feature, $this->supportedFeatures, true );
    }

    /**
     * Create the "payment": since this is a manual gateway there's no external
     * processor to call. We stash a short-lived reference to the order/transaction
     * and send the customer to our own on-site payment page.
     *
     * @param PaymentInstance $paymentInstance
     * @return array
     */
    public function makePaymentFromPaymentInstance( PaymentInstance $paymentInstance ) {
        $order       = $paymentInstance->order;
        $transaction = $paymentInstance->transaction;

        $ref = wp_generate_password( 32, false, false );

        set_transient(
            PaymentPage::TRANSIENT_PREFIX . $ref,
            array(
                'order_uuid'       => $order->uuid,
                'transaction_uuid' => $transaction->uuid,
                'amount'           => $order->total,
                'currency'         => $order->currency ?? '',
                'status'           => 'awaiting',
            ),
            DAY_IN_SECONDS
        );

        $redirect_url = add_query_arg(
            array( PaymentPage::QUERY_VAR => $ref ),
            home_url( '/' )
        );

        return array(
            'redirect_to' => $redirect_url,
            'status'      => 'success',
            'message'     => __( 'Order placed — redirecting you to complete your payment.', 'manipay-manual-payment-for-fluentcart' ),
        );
    }

    /**
     * No external webhooks for a manual gateway.
     */
    public function handleIPN() {
        // Intentionally empty.
    }

    /**
     * Settings fields shown at FluentCart > Settings > Payment Methods > ManiPay.
     * Field types (text, checkbox, enable) are per FluentCart's documented
     * settings-field reference.
     *
     * Each method's detail fields (number/account/QR) are only added to the
     * returned array once that method is already enabled and saved — e.g. tick
     * "Enable bKash", save, reload, and the bKash Number/QR fields appear.
     * Leave a method off and its fields don't exist on the page at all. This
     * both implements "hide unless enabled" and avoids any risk of FluentCart's
     * settings screen treating a blank optional field as invalid.
     *
     * @return array
     */
    public function fields(): array {
        $v = function ( $key ) {
            return $this->settings->get( $key );
        };

        $yesNo = function ( $key, $label ) use ( $v ) {
            return array(
                'type'  => 'checkbox',
                'label' => $label,
                'value' => $v( $key ),
            );
        };

        $bkash_on   = 'yes' === $v( 'enable_bkash' );
        $nagad_on   = 'yes' === $v( 'enable_nagad' );
        $rocket_on  = 'yes' === $v( 'enable_rocket' );
        $ibanking_on = 'yes' === $v( 'enable_ibanking' );
        $crypto_on  = 'yes' === $v( 'enable_crypto' );

        $fields = array(
            'is_active' => array(
                'type'  => 'enable',
                'label' => __( 'Enable ManiPay', 'manipay-manual-payment-for-fluentcart' ),
                'value' => $v( 'is_active' ),
            ),
            'display_name' => array(
                'type'  => 'text',
                'label' => __( 'Display Name', 'manipay-manual-payment-for-fluentcart' ),
                'value' => $v( 'display_name' ),
            ),
            'setup_notice' => array(
                'type'  => 'notice',
                'value' => '<p>' . esc_html__( 'This is a manual gateway — customers submit a Transaction ID on a dedicated payment page, and orders stay Pending until you verify and mark them Paid. Tick a method below and Save to reveal its detail fields.', 'manipay-manual-payment-for-fluentcart' ) . '</p>',
            ),

            'intro_mob_title'    => array( 'type' => 'text', 'label' => __( 'Mobile Banking — Heading', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'intro_mob_title' ) ),
            'intro_mob_desc'     => array( 'type' => 'textarea', 'label' => __( 'Mobile Banking — Description', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'intro_mob_desc' ) ),
            'intro_bank_title'   => array( 'type' => 'text', 'label' => __( 'iBanking — Heading', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'intro_bank_title' ) ),
            'intro_bank_desc'    => array( 'type' => 'textarea', 'label' => __( 'iBanking — Description', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'intro_bank_desc' ) ),
            'intro_crypto_title' => array( 'type' => 'text', 'label' => __( 'Crypto — Heading', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'intro_crypto_title' ) ),
            'intro_crypto_desc'  => array( 'type' => 'textarea', 'label' => __( 'Crypto — Description', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'intro_crypto_desc' ) ),

            'enable_bkash' => $yesNo( 'enable_bkash', __( 'Enable bKash', 'manipay-manual-payment-for-fluentcart' ) ),
        );

        if ( $bkash_on ) {
            $fields['bkash_number'] = array( 'type' => 'text', 'label' => __( 'bKash Number', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'bkash_number' ) );
            $fields['bkash_qr']     = array( 'type' => 'text', 'label' => __( 'bKash QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'bkash_qr' ) );
        }

        $fields['enable_nagad'] = $yesNo( 'enable_nagad', __( 'Enable Nagad', 'manipay-manual-payment-for-fluentcart' ) );
        if ( $nagad_on ) {
            $fields['nagad_number'] = array( 'type' => 'text', 'label' => __( 'Nagad Number', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'nagad_number' ) );
            $fields['nagad_qr']     = array( 'type' => 'text', 'label' => __( 'Nagad QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'nagad_qr' ) );
        }

        $fields['enable_rocket'] = $yesNo( 'enable_rocket', __( 'Enable Rocket', 'manipay-manual-payment-for-fluentcart' ) );
        if ( $rocket_on ) {
            $fields['rocket_number'] = array( 'type' => 'text', 'label' => __( 'Rocket Number', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'rocket_number' ) );
            $fields['rocket_qr']     = array( 'type' => 'text', 'label' => __( 'Rocket QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'rocket_qr' ) );
        }

        $fields['enable_ibanking'] = array(
            'type'  => 'enable',
            'label' => __( 'Enable iBanking (save once, then bank fields appear below)', 'manipay-manual-payment-for-fluentcart' ),
            'value' => $v( 'enable_ibanking' ),
        );

        if ( $ibanking_on ) {
            $fields = array_merge( $fields, array(
                'aibl_name'     => array( 'type' => 'text', 'label' => __( 'AIBL Bank Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'aibl_name' ) ),
                'aibl_acc_name' => array( 'type' => 'text', 'label' => __( 'AIBL Account Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'aibl_acc_name' ) ),
                'aibl_acc_no'   => array( 'type' => 'text', 'label' => __( 'AIBL Account No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'aibl_acc_no' ) ),
                'aibl_branch'   => array( 'type' => 'text', 'label' => __( 'AIBL Branch', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'aibl_branch' ) ),
                'aibl_routing'  => array( 'type' => 'text', 'label' => __( 'AIBL Routing No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'aibl_routing' ) ),
                'aibl_swift'    => array( 'type' => 'text', 'label' => __( 'AIBL SWIFT Code', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'aibl_swift' ) ),
                'aibl_qr'       => array( 'type' => 'text', 'label' => __( 'AIBL QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'aibl_qr' ) ),

                'pubali_name'     => array( 'type' => 'text', 'label' => __( 'Pubali Bank Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'pubali_name' ) ),
                'pubali_acc_name' => array( 'type' => 'text', 'label' => __( 'Pubali Account Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'pubali_acc_name' ) ),
                'pubali_acc_no'   => array( 'type' => 'text', 'label' => __( 'Pubali Account No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'pubali_acc_no' ) ),
                'pubali_branch'   => array( 'type' => 'text', 'label' => __( 'Pubali Branch', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'pubali_branch' ) ),
                'pubali_routing'  => array( 'type' => 'text', 'label' => __( 'Pubali Routing No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'pubali_routing' ) ),
                'pubali_swift'    => array( 'type' => 'text', 'label' => __( 'Pubali SWIFT Code', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'pubali_swift' ) ),
                'pubali_qr'       => array( 'type' => 'text', 'label' => __( 'Pubali QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'pubali_qr' ) ),

                'dbbl_name'     => array( 'type' => 'text', 'label' => __( 'DBBL Bank Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'dbbl_name' ) ),
                'dbbl_acc_name' => array( 'type' => 'text', 'label' => __( 'DBBL Account Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'dbbl_acc_name' ) ),
                'dbbl_acc_no'   => array( 'type' => 'text', 'label' => __( 'DBBL Account No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'dbbl_acc_no' ) ),
                'dbbl_branch'   => array( 'type' => 'text', 'label' => __( 'DBBL Branch', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'dbbl_branch' ) ),
                'dbbl_routing'  => array( 'type' => 'text', 'label' => __( 'DBBL Routing No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'dbbl_routing' ) ),
                'dbbl_swift'    => array( 'type' => 'text', 'label' => __( 'DBBL SWIFT Code', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'dbbl_swift' ) ),
                'dbbl_qr'       => array( 'type' => 'text', 'label' => __( 'DBBL QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'dbbl_qr' ) ),

                'ibbl_name'     => array( 'type' => 'text', 'label' => __( 'IBBL Bank Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'ibbl_name' ) ),
                'ibbl_acc_name' => array( 'type' => 'text', 'label' => __( 'IBBL Account Name', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'ibbl_acc_name' ) ),
                'ibbl_acc_no'   => array( 'type' => 'text', 'label' => __( 'IBBL Account No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'ibbl_acc_no' ) ),
                'ibbl_branch'   => array( 'type' => 'text', 'label' => __( 'IBBL Branch', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'ibbl_branch' ) ),
                'ibbl_routing'  => array( 'type' => 'text', 'label' => __( 'IBBL Routing No', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'ibbl_routing' ) ),
                'ibbl_swift'    => array( 'type' => 'text', 'label' => __( 'IBBL SWIFT Code', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'ibbl_swift' ) ),
                'ibbl_qr'       => array( 'type' => 'text', 'label' => __( 'IBBL QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'ibbl_qr' ) ),
            ) );
        }

        $fields['enable_crypto'] = array(
            'type'  => 'enable',
            'label' => __( 'Enable Crypto (save once, then crypto fields appear below)', 'manipay-manual-payment-for-fluentcart' ),
            'value' => $v( 'enable_crypto' ),
        );

        if ( $crypto_on ) {
            $fields['redot_id']   = array( 'type' => 'text', 'label' => __( 'RedotPay ID / Email', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'redot_id' ) );
            $fields['redot_qr']   = array( 'type' => 'text', 'label' => __( 'RedotPay QR Code Image URL', 'manipay-manual-payment-for-fluentcart' ), 'value' => $v( 'redot_qr' ) );
        }

        return $fields;
    }

    /**
     * Not used by this gateway (we don't render an onsite JS/AJAX flow — the
     * customer is redirected to our own PHP-rendered page instead), but
     * required by the interface.
     *
     * @param array $data
     */
    public function getOrderInfo( array $data ) {
        wp_send_json(
            array(
                'status'       => 'success',
                'payment_args' => array(),
                'message'      => __( 'Order info retrieved', 'manipay-manual-payment-for-fluentcart' ),
            ),
            200
        );
    }

    /**
     * No external gateway SDK or custom checkout JS needed — this is a plain
     * server-side redirect gateway.
     *
     * @param string $hasSubscription
     * @return array
     */
    /**
     * FluentCart requires every gateway — including plain redirect-style ones
     * like this — to enqueue a script that listens for
     * "fluent_cart_load_payments_{slug}" and calls
     * paymentLoader.enableCheckoutButton() once ready. Without it, the Place
     * Order button never activates when this gateway is selected/the only
     * one available. See assets/js/manipay-checkout.js.
     *
     * @param string $hasSubscription
     * @return array
     */
    public function getEnqueueScriptSrc( $hasSubscription = 'no' ): array {
        return array(
            MANIPAY_FC_URL . 'assets/js/manipay-checkout.js',
        );
    }
}
