<?php

// Ensure the file is not accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class BWD_User_Registration {

    private $google_client_id;
    private $google_client_secret;

    private $facebook_app_id;
    private $facebook_app_secret;

    private $linkedin_client_id;
    private $linkedin_client_secret;

    // Constructor
    public function __construct() {
        $this->google_client_id     = get_option( 'cv_google_client_id', '' );
        $this->google_client_secret = get_option( 'cv_google_client_secret', '' );

        $this->facebook_app_id     = get_option( 'cv_facebook_app_id', '' );
        $this->facebook_app_secret = get_option( 'cv_facebook_app_secret', '' );

        $this->linkedin_client_id     = get_option( 'cv_linkedin_client_id', '' );
        $this->linkedin_client_secret = get_option( 'cv_linkedin_client_secret', '' );

        add_shortcode( 'custom_login', [ $this, 'display_custom_login' ] );
        add_shortcode( 'custom_registration', [ $this, 'display_custom_registration' ] );
        add_shortcode( 'instantly_cv_create', [ $this, 'bwdcv_instantly_cv_create' ] );
        add_action( 'init', [ $this, 'handle_custom_registration' ] );
        add_action( 'woocommerce_created_customer', [ $this, 'assign_editor_role' ], 10, 3 );
        add_action( 'init', [ $this, 'save_custom_links_from_dashboard' ] );
        // Signature
        add_action( 'wp_ajax_bwdcv_save_signature', [ $this, 'wp_save_signature_image' ] );
        // add_action( 'wp_ajax_nopriv_bwdcv_save_signature', [ $this, 'wp_save_signature_image' ] );
        add_action( 'wp_enqueue_scripts', [ $this, 'wp_signature_enqueue_assets' ] );
        // Loss pass form
        add_action( 'woocommerce_lostpassword_form', [ $this, 'add_math_captcha' ] );
        add_action( 'woocommerce_lostpassword_process', [ $this, 'validate_math_captcha' ] );
        // Loss pass form submission alert
        add_action( 'wp_ajax_wc_lost_password_ajax', [ $this, 'wc_lost_password_ajax' ] );
        add_action( 'wp_ajax_nopriv_wc_lost_password_ajax', [ $this, 'wc_lost_password_ajax' ] );
        add_action( 'template_redirect', [ $this, 'cv_restrict_page_view_with_token' ] );
        add_action( 'init', [ $this, 'user_social_oauth_response' ] );
    }

    // Instantly CV registration form
    public function bwdcv_instantly_cv_create($atts) {
        ob_start();

        // Shortcode attributes
        $atts = shortcode_atts(
            array(
                'text' => 'Create CV',
            ), $atts, 'instantly_cv_create'
        );
        
        // After register 2
        if (isset($_POST['cv_auto_register'])) {

            // Turnstile verification
            $token = sanitize_text_field($_POST['cf-turnstile-response'] ?? '');

            $verify = wp_remote_post("https://challenges.cloudflare.com/turnstile/v0/siteverify", [
                'body' => [
                    'secret' => get_option('cv_cloudflare_secret_key', ''),
                    'response' => $token,
                    'remoteip' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
                ]
            ]);

            $body = json_decode(wp_remote_retrieve_body($verify), true);

            if(!empty(get_option('cv_cloudflare_secret_key', '')) && !empty(get_option('cv_site_key_text', ''))) {
                if (empty($body['success'])) {
                    echo '<p style="color:red;">Bot protection failed. Please try again.</p>';
                    return ob_get_clean();
                }
            }

            $username = 'user_' . wp_generate_password(6, false);
            $password = wp_generate_password(12);
            $email = $username . '@example.com';

            $user_id = wp_create_user($username, $password, $email);

            if (!is_wp_error($user_id)) {
                wp_update_user([
                    'ID' => $user_id,
                    'role' => 'cv_editor'
                ]);

                wp_set_current_user($user_id);
                wp_set_auth_cookie($user_id);

                $cv_page_id = $this->create_cv_page( $user_id, $username );
                if ( ! is_wp_error( $cv_page_id ) ) {
                    $this->switch_to_gutenberg( $cv_page_id );
                    wp_redirect( $this->get_bwdcv_editor_page_url( $cv_page_id ) );
                } else {
                    // Handle error if page creation fails
                    $dashboard_page = get_option( 'bwd_userfronted_options' )['dashboard_page'];
                    wp_redirect( get_permalink( $dashboard_page ) );
                }
            } else {
                echo "<p style='color:red;'>" . esc_html($user_id->get_error_message()) . "</p>";
            }
        }

        // Create CV instant
        if (!is_user_logged_in()) {
            echo '<form method="post">';
                echo '<div class="cf-turnstile" data-sitekey="'.esc_attr(get_option('cv_site_key_text', '')).'" style="position: fixed;bottom: 0;right: 0;"></div>';
                echo '<br>
                <button type="submit" name="cv_auto_register" class="bwdcv-instantly-cv-create">'.esc_html($atts['text']).'</button>
            </form>';
        }

        return ob_get_clean();

    }

    // Check if the client ID is valid
    private function is_valid_client_id( $client_id, $platform = '' ) {
        // Empty check
        if ( empty( $client_id ) ) {
            return false;
        }
        // Format check based on platform
        switch ( strtolower( $platform ) ) {
            case 'google':
                return strpos( $client_id, '.apps.googleusercontent.com' ) !== false;
            case 'facebook':
                return preg_match( '/^\d+$/', $client_id );
            case 'linkedin':
                return preg_match( '/^[a-z0-9]{10,}$/i', $client_id );
            default:
                return false;
        }
    }

    public function display_social_login_btn() {
        $google_url = 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query( [
                'client_id'     => $this->google_client_id,
                'redirect_uri'  => home_url( '?social-login=google' ),
                'response_type' => 'code',
                'scope'         => 'email profile',
                'access_type'   => 'online',
            ] );

        $facebook_url = 'https://www.facebook.com/v18.0/dialog/oauth?' . http_build_query( [
                'client_id'     => $this->facebook_app_id,
                'redirect_uri'  => home_url( '?social-login=facebook' ),
                'response_type' => 'code',
                'scope'         => 'email public_profile',
            ] );

        $linkedin_url = 'https://www.linkedin.com/oauth/v2/authorization?' . http_build_query( [
                'response_type' => 'code',
                'client_id'     => $this->linkedin_client_id,
                'redirect_uri'  => home_url( '?social-login=linkedin' ),
                'scope'         => 'openid profile email',
                'state'         => wp_create_nonce( 'linkedin_oauth' ),
            ] );

        $social_buttons = [
            'google'   => [
                'url'   => $google_url,
                'label' => esc_html__( 'Continue with Google Login', 'cv-builder' ),
                'icon'  => 'fab fa-google',
                'bg'    => '#db4437',
                'valid' => ( ! empty( $this->google_client_id ) && ! empty( $this->google_client_secret ) ),
            ],
            'facebook' => [
                'url'   => $facebook_url,
                'label' => esc_html__( 'Continue with Facebook Login', 'cv-builder' ),
                'icon'  => 'fab fa-facebook-f',
                'bg'    => '#3b5998',
                'valid' => ( ! empty( $this->facebook_app_id ) && ! empty( $this->facebook_app_secret ) ),
            ],
            'linkedin' => [
                'url'   => $linkedin_url,
                'label' => esc_html__( 'Continue with LinkedIn Login', 'cv-builder' ),
                'icon'  => 'fab fa-linkedin-in',
                'bg'    => '#0077b5',
                'valid' => ( ! empty( $this->linkedin_client_id ) && ! empty( $this->linkedin_client_secret ) ),
            ],
        ];
        ob_start();
        echo '<div class="bwd-social-login" style="display: grid; font-family: sans-serif; font-size: 20px;">';
        if ( $social_buttons['google']['valid'] || $social_buttons['facebook']['valid'] || $social_buttons['linkedin']['valid'] ) {
            echo '<h2 style="margin-bottom: 10px;">' . esc_html__( 'Join with Social', 'cv-builder' ) . '</h2>';
        }
        foreach ( $social_buttons as $platform => $data ) {
            if ( $data['valid'] ) {
                echo '<a href="' . esc_url( $data['url'] ) . '" class="button" style="display: flex; align-items: center; width:330px; justify-content: center; text-decoration: none; background:' . esc_attr( $data['bg'] ) . '; color:#fff; padding:10px; margin:5px auto; border-radius:5px;">';
                echo '<i class="' . esc_attr( $data['icon'] ) . '" style="margin-right: 10px;"></i>';
                echo esc_html( $data['label'] );
                echo '</a>';
            }
        }
        echo '</div>';

        return ob_get_clean();
    }

    public function user_social_oauth_response() {
        if ( ! isset( $_GET['social-login'] ) || ! isset( $_GET['code'] ) ) {
            return;
        }
        $code = sanitize_text_field( $_GET['code'] );
        $type = sanitize_text_field( $_GET['social-login'] );
        switch ( $type ) {
            case 'google':
                $token_response = wp_remote_post( 'https://oauth2.googleapis.com/token', [
                    'body' => [
                        'code'          => $code,
                        'client_id'     => $this->google_client_id,
                        'client_secret' => $this->google_client_secret,
                        'redirect_uri'  => home_url( '?social-login=google' ),
                        'grant_type'    => 'authorization_code',
                    ],
                ] );
                $token_body     = json_decode( wp_remote_retrieve_body( $token_response ), true );
                if ( ! empty( $token_body['access_token'] ) ) {
                    $user_response = wp_remote_get( 'https://www.googleapis.com/oauth2/v2/userinfo', [
                        'headers' => [ 'Authorization' => 'Bearer ' . $token_body['access_token'] ],
                    ] );
                    $user_data     = json_decode( wp_remote_retrieve_body( $user_response ), true );
                    $this->user_create_from_social( $user_data, $type );
                }
                break;

            case 'facebook':
                $access_token_response = wp_remote_get( 'https://graph.facebook.com/v18.0/oauth/access_token?' . http_build_query( [
                        'client_id'     => $this->facebook_app_id,
                        'redirect_uri'  => home_url( '?social-login=facebook' ),
                        'client_secret' => $this->facebook_app_secret,
                        'code'          => $code,
                    ] ) );
                $token_body            = json_decode( wp_remote_retrieve_body( $access_token_response ), true );
                if ( ! empty( $token_body['access_token'] ) ) {
                    $user_info = wp_remote_get( 'https://graph.facebook.com/me?fields=name,email&access_token=' . $token_body['access_token'] );
                    $user_data = json_decode( wp_remote_retrieve_body( $user_info ), true );
                    $this->user_create_from_social( $user_data, $type );
                }
                break;

            case 'linkedin':
                $token_response = wp_remote_post( 'https://www.linkedin.com/oauth/v2/accessToken', [
                    'body' => [
                        'grant_type'    => 'authorization_code',
                        'code'          => $code,
                        'redirect_uri'  => home_url( '?social-login=linkedin' ),
                        'client_id'     => $this->linkedin_client_id,
                        'client_secret' => $this->linkedin_client_secret,
                    ],
                ] );

                $token_body = json_decode( wp_remote_retrieve_body( $token_response ), true );
                if ( ! empty( $token_body['access_token'] ) ) {
                    $access_token   = $token_body['access_token'];
                    $email_response = wp_remote_get( 'https://api.linkedin.com/v2/userinfo', [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $access_token,
                        ],
                    ] );
                    $email_data     = json_decode( wp_remote_retrieve_body( $email_response ), true );
                    $this->user_create_from_social( $email_data, $type );
                }
                break;
        }
    }

    private function user_create_from_social( $email_data, $socialType ) {
        $email    = sanitize_email( $email_data['email']);
        $name     = sanitize_text_field($email_data['name']);
        $photo    = $email_data['picture'] ?? '';

        if ( email_exists( $email ) ) {
            $user = get_user_by( 'email', $email );
        } else {
            $user_id = wp_create_user( $name, wp_generate_password(), $email );
            wp_update_user( [
                'ID'           => $user_id,
                'role'         => 'cv_editor',
                'display_name' => $name,
            ] );
            $user = get_user_by( 'ID', $user_id );
        }

        if ( $user_id ) {
            add_user_meta( $user_id, 'wp_cv_social_type', $socialType );
            add_user_meta( $user_id, 'wp_cv_social_photo', $photo );
        }

        if ( $user ) {
            $options = get_option( 'bwd_userfronted_options' );
            wp_set_current_user( $user->ID );
            wp_set_auth_cookie( $user->ID );
            wp_redirect( get_permalink( $options['dashboard_page'] ) );
            exit;
        }
    }

    // Get user ID by token
    public function bwd_get_user_id_by_token( $token_to_find ) {
        $users = get_users( [
            'meta_key'   => 'wp_cv_user_token',
            'meta_value' => $token_to_find,
            'number'     => 1,
            'fields'     => [ 'ID' ],
        ] );

        return ! empty( $users ) ? $users[0]->ID : false;
    }

    public function cv_restrict_page_view_with_token() {
        if ( ! is_singular( 'cv' ) ) {
            return;
        }
        $page_id = get_queried_object_id();
        if ( ! $page_id || $page_id === 0 ) {
            wp_die( 'Page ID not found' );
        }
        $creator_user_id = get_post_field( 'post_author', $page_id );
        $user_token      = bwdcv_get_user_token( $creator_user_id );
        $token           = $_GET['token'] ?? '';
        $token_User_id   = $this->bwd_get_user_id_by_token( $token );
        if ( ! is_user_logged_in() ) {
            if ( isset( $_GET['token'] ) && $_GET['token'] === $user_token ) {
                return;
            } else {
                wp_redirect( home_url( '/404' ) );
                exit;
            }
        } else {
            $current_user_id = get_current_user_id();
            if ( $current_user_id == $creator_user_id ) {
                return;
            } else {
                if ( isset( $_GET['token'] ) && $_GET['token'] == $user_token ) {
                    return;
                } else {
                    if ( $token_User_id == $creator_user_id ) {
                        return;
                    } else {
                        wp_redirect( home_url( '/404' ) );
                        exit;
                    }
                }
            }
        }
    }

    public function wc_lost_password_ajax() {
        if ( isset( $_POST['user_login'], $_POST['math_captcha'], $_POST['math_captcha_answer'] ) ) {
            $user_login     = sanitize_text_field( $_POST['user_login'] );
            $captcha_input  = intval( $_POST['math_captcha'] );
            $captcha_answer = intval( $_POST['math_captcha_answer'] );

            // Captcha Check
            if ( $captcha_input !== $captcha_answer ) {
                wp_send_json( [ 'message' => '<span style="color:red;">Incorrect captcha!</span>' ] );
            }

            // WooCommerce Lost Password Process
            $user_data = get_user_by( 'login', $user_login );
            if ( ! $user_data ) {
                wp_send_json( [ 'message' => '<span style="color:red;">User not found!</span>' ] );
            }

            $reset_key = get_password_reset_key( $user_data );
            $reset_url = wc_get_endpoint_url( 'lost-password', $reset_key, wc_get_page_permalink( 'myaccount' ) );

            // Send email
            wp_send_json( [ 'message' => '<span style="color:green;">Password reset email sent!</span>' ] );
        }

        wp_send_json( [ 'message' => '<span style="color:red;">Something went wrong!</span>' ] );
    }

    private const ONES      = [
        0  => 'zero',
        1  => 'one',
        2  => 'two',
        3  => 'three',
        4  => 'four',
        5  => 'five',
        6  => 'six',
        7  => 'seven',
        8  => 'eight',
        9  => 'nine',
        10 => 'ten',
        11 => 'eleven',
        12 => 'twelve',
        13 => 'thirteen',
        14 => 'fourteen',
        15 => 'fifteen',
        16 => 'sixteen',
        17 => 'seventeen',
        18 => 'eighteen',
        19 => 'nineteen',
    ];

    private const TENS      = [
        2 => 'twenty',
        3 => 'thirty',
        4 => 'forty',
        5 => 'fifty',
        6 => 'sixty',
        7 => 'seventy',
        8 => 'eighty',
        9 => 'ninety',
    ];

    private const OPERATORS = [ '+', '-', '*' ];

    /**
     * Convert a number to its word representation
     *
     * @param  int  $number  The number to convert
     *
     * @return string The word representation
     */
    public function toWords( int $number ): string {
        if ( $number < 0 ) {
            return 'negative ' . $this->toWords( abs( $number ) );
        }

        if ( $number < 20 ) {
            return self::ONES[ $number ];
        }

        if ( $number < 100 ) {
            return self::TENS[ floor( $number / 10 ) ] . ( $number % 10 ? ' ' . self::ONES[ $number % 10 ] : '' );
        }

        return 'Number too large';
    }

    /**
     * Convert a word representation to a number
     *
     * @param  string  $string  The word representation
     *
     * @return int|null The number or null if conversion failed
     */
    public function toNumber( string $string ): ?int {
        $string = strtolower( trim( $string ) );

        if ( isset( self::ONES[ $string ] ) ) {
            return self::ONES[ $string ];
        }

        foreach ( self::TENS as $word => $value ) {
            if ( strpos( $string, $word ) === 0 ) {
                $remainder = trim( substr( $string, strlen( $word ) ) );

                if ( empty( $remainder ) ) {
                    return $value;
                }

                if ( isset( self::ONES[ $remainder ] ) ) {
                    return $value + self::ONES[ $remainder ];
                }
            }
        }

        return null;
    }

    /**
     * WooCommerce Lost Password form Math Captcha added
     */
    public function add_math_captcha() {
        $num1     = rand( 1, 9 );
        $num2     = rand( 1, 9 );
        $operator = self::OPERATORS[ array_rand( self::OPERATORS ) ];

        switch ( $operator ) {
            case '+':
                $result = $num1 + $num2;
                break;
            case '-':
                $result = $num1 - $num2;
                break;
            case '*':
                $result = $num1 * $num2;
                break;
        }

        $word1 = ( rand( 0, 1 ) ? $this->toWords( $num1 ) : $num1 );
        $word2 = ( rand( 0, 1 ) ? $this->toWords( $num2 ) : $num2 );

        echo '<p class="form-row form-row-first">';
        echo '<label for="captcha"><strong>Solve:</strong> ' . $word1 . ' ' . $operator . ' ' . $word2 . ' = ? <span class="required">*</span></label>';
        echo '<input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="captcha_result" required />';
        echo '<input type="hidden" name="captcha_sum" value="' . $result . '" />';
        echo '</p>';
    }

    /**
     * Math Captcha compare
     */
    public function validate_math_captcha() {
        if ( ! isset( $_POST['captcha_result'] ) || ! isset( $_POST['captcha_sum'] ) ) {
            wc_add_notice( 'Please solve the math problem.', 'error' );

            return;
        }

        $user_input     = $this->toNumber( $_POST['captcha_result'] ) ?? (int) $_POST['captcha_result'];
        $correct_answer = (int) $_POST['captcha_sum'];

        if ( $user_input !== $correct_answer ) {
            wc_add_notice( 'Incorrect math answer. Please try again.', 'error' );
        }
    }

    public function wp_signature_enqueue_assets() {
        if ( current_user_can( 'cv_editor' ) ) {
            wp_enqueue_script( 'wp-signature-combo-js', plugin_dir_url( __FILE__ ) . '../assets/public/signature/signature.js', [ 'jquery' ], null, true );
            wp_enqueue_style( 'wp-signature-combo-css', plugin_dir_url( __FILE__ ) . '../assets/public/signature/signature.css' );
            wp_localize_script( 'wp-signature-combo-js', 'wpSignatureCombo', [
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce'    => wp_create_nonce( 'bwdcv_save_signature_nonce' ),
            ] );
        }
    }

    public function wp_save_signature_image() {

        check_ajax_referer( 'bwdcv_save_signature_nonce', 'security' );

        if ( ! current_user_can( 'cv_editor' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
            return;
        }

        if ( ! isset( $_POST['image_data'] ) ) {
            wp_send_json_error( [ 'message' => 'No image data' ], 400 );
            return;
        }

        $image_data = $_POST['image_data'];
        if ( ! str_starts_with( $image_data, 'data:image/png;base64,' ) ) {
            wp_send_json_error( [ 'message' => 'Invalid image format' ], 400 );
            return;
        }
        $base64_data   = str_replace( 'data:image/png;base64,', '', $image_data );
        $decoded_image = base64_decode( $base64_data, true );

        if ( $decoded_image === false ) {
            wp_send_json_error( [ 'message' => 'Invalid base64 data' ], 400 );
            return;
        }

        $upload_dir    = wp_upload_dir();
        $file_name     = 'signature_' . time() . '.png';
        $file_path     = $upload_dir['path'] . '/' . $file_name;
        file_put_contents( $file_path, $decoded_image );
        $attachment    = [
            'guid'           => $upload_dir['url'] . '/' . $file_name,
            'post_mime_type' => 'image/png',
            'post_title'     => sanitize_file_name( $file_name ),
            'post_content'   => '',
            'post_status'    => 'inherit',
        ];
        $attachment_id = wp_insert_attachment( $attachment, $file_path );
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        $metadata = wp_generate_attachment_metadata( $attachment_id, $file_path );
        wp_update_attachment_metadata( $attachment_id, $metadata );

        echo wp_json_encode( [ 'success' => true, 'image_url' => $upload_dir['url'] . '/' . $file_name ] );
        wp_die();
    }

    public function save_custom_links_from_dashboard() {
        if ( isset( $_POST['custom_links_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['custom_links_nonce'] ) ), 'save_custom_links' ) ) {
            if ( isset( $_POST['custom_links'] ) && is_array( $_POST['custom_links'] ) ) {
                foreach ( wp_unslash( $_POST['custom_links'] ) as $page_id => $custom_link ) {
                    $page_id     = absint( $page_id );
                    $custom_link = sanitize_text_field( $custom_link );

                    if ( ! $page_id ) {
                        continue;
                    }

                    update_post_meta( $page_id, '_custom_page_link', $custom_link );

                    if ( ! empty( $custom_link ) ) {
                        $new_slug = sanitize_title( $custom_link );
                        wp_update_post( [
                            'ID'        => $page_id,
                            'post_name' => $new_slug,
                        ] );
                    }
                }
            }
        }
        // editor image upload
        if ( isset( $_POST['submit_dashboard_image'] ) && ! empty( $_FILES['custom_dashboard_image']['name'] ) ) {
            $user_id = get_current_user_id();
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
            $uploaded_file = wp_handle_upload( $_FILES['custom_dashboard_image'], [ 'test_form' => false ] );
            if ( isset( $uploaded_file['url'] ) ) {
                update_user_meta( $user_id, 'dashboard_uploaded_image', $uploaded_file['url'] );
                wc_add_notice( esc_html__( 'Image uploaded successfully!', 'cv-builder' ), 'success' );
            } else {
                wc_add_notice( esc_html__( 'Image upload failed. Please try again.', 'cv-builder' ), 'error' );
            }
            wp_safe_redirect( wc_get_account_endpoint_url( 'dashboard' ) );
            exit;
        }
    }

    public function assign_editor_role( $customer_id, $new_customer_data, $password_generated ) {
        $user = new WP_User( $customer_id );
        $user->remove_all_caps();
        $user->add_role( 'cv_editor' );
    }

    public function display_custom_login() {
        ob_start();
        include 'dashboard/login.php';

        return ob_get_clean();
    }

    public function display_custom_registration() {
        ob_start();
        include 'dashboard/registration.php';

        return ob_get_clean();
    }

    public function handle_custom_registration() {
        $error_messages = [
            'password_mismatch' => '',
            'username_exists'   => '',
            'email_exists'      => '',
            'empty_fields'      => '',
        ];

        if ( isset( $_POST['custom_register_form'] ) || isset( $_POST['custom_register_button'] ) ) {
            if ( ! isset( $_POST['custom_registration_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['custom_registration_nonce'] ) ), 'custom_registration_nonce_action' ) ) {
                return;
            }
            if ( isset( $_POST['custom_register_button'] ) ) {
                $username = 'user_' . wp_generate_uuid4();
                $email    = 'user_' . wp_generate_uuid4() . '@example.com';
                $password = wp_generate_password( 12, true, true );
            } else {
                $username        = isset( $_POST['user_username'] ) ? sanitize_user( $_POST['user_username'] ) : sanitize_email( $_POST['user_email'] );
                $email           = isset( $_POST['user_email'] ) ? sanitize_email( $_POST['user_email'] ) : '';
                $password        = isset( $_POST['user_password'] ) ? sanitize_text_field( $_POST['user_password'] ) : wp_generate_password( 12, true, true );
                $password_repeat = isset( $_POST['user_password_repeat'] ) ? sanitize_text_field( $_POST['user_password_repeat'] ) : '';

                if ( $password !== $password_repeat ) {
                    $error_messages['password_mismatch'] = 'Passwords do not match. Please try again.';
                }
            }

            if ( empty( $username ) || empty( $email ) || empty( $password ) ) {
                $error_messages['empty_fields'] = 'Please fill in all required fields.';
            }

            if ( username_exists( $username ) ) {
                $error_messages['username_exists'] = 'This username is already taken. Please choose another one.';
            }

            if ( email_exists( $email ) ) {
                $error_messages['email_exists'] = 'This email is already registered. Please use a different email.';
            }

            if ( ! empty( array_filter( $error_messages ) ) ) {
                $_SESSION['bwd_registration_errors'] = $error_messages;

                return;
            }

            $user_id = wp_create_user( $username, $password, $email );
            if ( is_wp_error( $user_id ) ) {
                return;
            }

            $user = new WP_User( $user_id );
            $user->set_role( 'cv_editor' );
            $capabilities = BWDCV_BLOCKS_CLASS::get_cv_editor_capabilities();
            foreach ( $capabilities as $cap ) {
                $user->add_cap( $cap );
            }

            wp_set_current_user( $user_id );
            wp_set_auth_cookie( $user_id );

            $this->bwd_generate_user_token( $user_id );

            $cv_page_id = $this->create_cv_page( $user_id, $username );

            if ( ! is_wp_error( $cv_page_id ) ) {
                $this->switch_to_gutenberg( $cv_page_id );
                wp_redirect( $this->get_bwdcv_editor_page_url( $cv_page_id ) );
            } else {
                // Handle error if page creation fails
                $dashboard_page = get_option( 'bwd_userfronted_options' )['dashboard_page'];
                wp_redirect( get_permalink( $dashboard_page ) );
            }

            /**
             *
             * To pass the username and email to the welcome email
             *
             */
            if ( ! is_wp_error( $user_id ) ) {
                // Log the user in
                wp_set_current_user( $user_id );
                wp_set_auth_cookie( $user_id );

                // Start session if not already started
                if ( ! session_id() ) {
                    session_start();
                }

                // Redirect to that URL
                wp_redirect( $this->get_bwdcv_editor_page_url( $cv_page_id ) );
                $this->send_welcome_email_to_editor( $user_id, $email, $username );
                if ( ! empty( get_option( 'cv_m_api_key_text', '' ) ) || ! empty( get_option( 'cv_m_audience_bwd', '' ) ) ) {
                    $this->bwdcv_collect_editor_email_to_mailchimp( $email, $username );
                }

                // error_log( "User {$username} with email {$email} registered successfully." );
                /**
                 * Split the name into first and last names.
                 * For WeMail
                 */
                $name_parts = explode(' ', $username, 2);
                $first_name = $name_parts[0];
                $last_name  = isset($name_parts[1]) ? $name_parts[1] : '';
                $data = [
                    'first_name' => $first_name,
                    'last_name'  => $last_name,
                    'email'      => $email,
                    'tags'       => ['bwdcv-plugin'],
                ];
                $api_response = $this->bwdcv_wemail_create_subscriber_simple($data);

                exit;
            }
            exit;
        }
    }

    /**
     *
     * Send welcome email to the cv editor
     *
     */
    public function send_welcome_email_to_editor( $user_id, $email, $username ) {
        $processed_text = get_option( 'bwdcv_user_text', '' );
        $cv_page_id     = get_user_meta( $user_id, 'cv_page_id', true );

        $processed_text = $this->replacePlaceholdersRegex( $processed_text, [
            'edit_page'         => $this->get_bwdcv_editor_page_url( $cv_page_id ),
            'cv_user_dashboard' => get_permalink( get_option( 'bwd_userfronted_options' )['dashboard_page'] ),
            'login_page'        => get_permalink( get_option( 'bwd_userfronted_options' )['login_page'] ),
            'username'          => $username,
            'site_name'         => get_bloginfo( 'name' ),
        ] );

        $edit_cv_url = '';
        if ( $cv_page_id ) {
            $edit_cv_url = add_query_arg( [
                'post'   => $cv_page_id,
                'action' => 'edit',
            ], admin_url( 'post.php' ) );
        }
        $admin_email = get_option( 'admin_email' );
        $site_name   = get_bloginfo( 'name' );
        $subject     = "Welcome to $site_name!";
        $message     = str_replace( "\n", "\r\n", $processed_text );
        $headers     = [
            'Content-Type: text/plain; charset=UTF-8',
            "From: $site_name <$admin_email>",
        ];

        $sent = wp_mail( $email, $subject, $message, $headers );
        if ( $sent ) {
            update_user_meta( $user_id, 'welcome_email_sent', true );
        } else {
            error_log( "Failed to send welcome email from $admin_email to {$email}." );
        }
    }

    public function replacePlaceholdersRegex( $template, $replacements ) {
        return preg_replace_callback( '/\[([^\]]+)\]/', function ( $matches ) use ( $replacements ) {
            $placeholder = $matches[1];

            return isset( $replacements[ $placeholder ] ) ? $replacements[ $placeholder ] : $matches[0];
        }, $template );
    }

    /**
     * Create a subscriber in Wemail using the provided data.
     *
     * @param array $data Subscriber data.
     * @return array|WP_Error Response from the Wemail API.
     */
    public function bwdcv_wemail_create_subscriber_simple($data) {
        // WeMail Integration
        $api_key = sanitize_text_field( get_option( 'cv_wemail_api_key_text', '' ) );
        $list_id           = sanitize_text_field( get_option( 'cv_wemail_list_number', '' ) );
        $url = "https://api.getwemail.io/api/v1/lists/$list_id/subscribers";

        $response = wp_remote_post($url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept'       => 'application/json',
                'X-API-KEY'    => $api_key,
            ],
            'body'    => wp_json_encode($data),
            'timeout' => 20,
        ]);

        if (is_wp_error($response)) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($code === 200 || $code === 201) {
            return $body;
        }

        return $body;
    }

    /**
     *
     * Collect the cv editor email to mailchimp
     *
     */
    public function bwdcv_collect_editor_email_to_mailchimp( $email, $username ) {
        // Start session if not already started
        if ( ! session_id() ) {
            session_start();
        }

        if ( empty( $email ) || empty( $username ) ) {
            error_log( 'Missing username or email in session.' );

            return;
        }

        // Get user by email
        $user = get_user_by( 'email', $email );
        if ( ! $user ) {
            error_log( "No user found with email: $email" );

            return;
        }

        $user_id = $user->ID;

        // Check for Mailchimp settings
        $mailchimp_status = $this->add_editor_email_to_mailchimp( $email );
        $email_sent       = get_user_meta( $user_id, 'welcome_email_sent', true );

        if ( ! $email_sent ) {
            if ( $mailchimp_status ) {
                error_log( "Successfully added {$email} to Mailchimp." );
            } else {
                error_log( "Failed to add {$email} to Mailchimp." );
            }

            $this->send_welcome_email_to_editor( $user_id, $email, $username );
        }
    }

    // Editor mail collect
    public function add_editor_email_to_mailchimp( $email ) {
        $api_key     = get_option( 'cv_m_api_key_text', '' );
        $list_id     = get_option( 'cv_m_audience_bwd', '' );
        $data_center = substr( $api_key, strpos( $api_key, '-' ) + 1 );
        $url         = "https://$data_center.api.mailchimp.com/3.0/lists/$list_id/members/";
        $data        = [
            'email_address' => $email,
            'status'        => 'subscribed',
            'tags'          => [
                get_option( 'cv_m_tag_bwd', 'WP CV Builder' ),
            ],
        ];
        $args        = [
            'method'  => 'POST',
            'body'    => wp_json_encode( $data ),
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode( 'user:' . $api_key ),
                'Content-Type'  => 'application/json',
            ],
        ];
        $response    = wp_remote_post( $url, $args );
        if ( is_wp_error( $response ) ) {
            error_log( 'Mailchimp API error: ' . $response->get_error_message() );

            return false;
        }
        $status_code = wp_remote_retrieve_response_code( $response );
        $body        = wp_remote_retrieve_body( $response );

        if ( $status_code == 200 ) {
            return true;
        } else {
            error_log( 'Error adding email to Mailchimp: ' . $body );

            return false;
        }
    }

    public function bwd_generate_user_token( $user_id ) {
        $user = get_userdata( $user_id );
        if ( ! $user ) {
            return;
        }

        $email    = $user->user_email;
        $timezone = get_option( 'timezone_string' ) ?: 'UTC';
        $domain   = $_SERVER['SERVER_NAME'];

        $raw   = $domain . '|' . $timezone . '|' . $email;
        $token = hash( 'sha256', $raw );

        add_user_meta( $user_id, 'wp_cv_user_token', $token );
    }

    // Create a new CV page
    private function create_cv_page( $user_id, $username ) {
        $user_page_title = $username . "'s CV Page";
        $cv_page_id      = wp_insert_post( [
            'post_title'   => $user_page_title,
            'post_content' => '',
            'post_status'  => 'publish',
            'post_author'  => $user_id,
            'post_type'    => 'cv',
        ] );

        if ( ! is_wp_error( $cv_page_id ) ) {
            update_user_meta( $user_id, 'cv_page_id', $cv_page_id );
        }

        return $cv_page_id;
    }

    private function switch_to_gutenberg( $cv_page_id ) {
        $bwdcvBlock = '
        <!-- wp:bwdcv/wp-cv-builder {"heading":"WP CV Builder","subheading":"A Block"} /-->
        ';
        wp_update_post( [
            'ID'           => $cv_page_id,
            'post_content' => $bwdcvBlock,
        ] );
        delete_post_meta( $cv_page_id, '_wp_page_template' );
    }

    // Get the page editor URL for the CV page
    private function get_bwdcv_editor_page_url( $cv_page_id ) {
        return add_query_arg( [
            'post'   => $cv_page_id,
            'action' => 'edit',
        ], admin_url( 'post.php' ) );
    }

}

new BWD_User_Registration();
?>
