<?php

namespace Booktics\Module\Stripe_Addon\Handler;

use Booktics\Module\Stripe_Addon\Service\Stripe_Payment_Method;
use Booktics\Settings\Settings;

class Stripe_Handler {
    /**
     * Get the redirect URI for Stripe OAuth callback.
     *
     * @return string The redirect URI
     */
    private function get_redirect_uri( $type = 'test' ) {
        $nonce = wp_create_nonce( 'booktics_stripe_callback' );

        return admin_url( 'admin-ajax.php?action=booktics_stripe_callback&type=' . $type . '&_wpnonce=' . $nonce );
    }

    /**
     * Get the Stripe secret key.
     *
     * @return string The Stripe secret key
     */
    public static function get_stripe_secret_key() {
        return booktics_get_option('stripe_secret_key', '');
    }

    /**
     * Get the Stripe Publishable key.
     *
     * @return string The Stripe publishable key
     */
    public static function get_stripe_publishable_key() {
        return booktics_get_option('stripe_publishable_key', '');
    }

    /**
     * Handle the OAuth callback from Stripe.
     *
     * @param array $request The request data
     *
     * @return \WP_REST_Response The response object
     */
    public static function handle_callback( $request ) {
        if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'booktics_stripe_callback' ) ) {
            return rest_ensure_response( [
                'status'  => 'error',
                'message' => __( 'Invalid security token', 'booktics' )
            ] );
        }

        $account_id = isset( $_GET['account_id'] ) ? sanitize_text_field( wp_unslash( $_GET['account_id'] ) ) : '';
        $type       = isset( $_GET['type'] ) ? sanitize_text_field( wp_unslash( $_GET['type'] ) ) : 'test';

        if ( ! $account_id ) {
            return rest_ensure_response( [
                'status'  => 'error',
                'message' => __( 'Missing account_id parameter', 'booktics' )
            ] );
        }

        if ( ! empty( $account_id ) ) {
            Settings::update( 'stripe_account_id', $account_id );
            Settings::update( 'stripe_account_type', $type );

            wp_safe_redirect( admin_url( 'admin.php?page=booktics#/settings?tab=payment' ) );
            exit;
        }

        return rest_ensure_response( [
            'status'  => 'error',
            'message' => __( 'Stripe connection failed', 'booktics' )
        ] );
    }

    /**
     * Get the Stripe Connect authorization URL.
     *
     * @return string The authorization URL
     */
    public function get_connect_url( $type = 'test' ) {
        return BOOKTICS_STRIPE_CONNECT_DOMAIN . '/stripe/connect?type=' . $type . '&redirect_uri=' . base64_encode( $this->get_redirect_uri( $type ) );
    }
}