<?php

namespace Formatrica\Registration;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class User_Registration_Handler
{
    /**
     * Handle user registration from form submission
     *
     * @param array $data Sanitized form data
     * @return array ['success' => bool, 'message' => string, 'user_id' => int|null]
     */
    public function register_user(array $data): array
    {
        // Check if user registration is enabled
        if (!get_option('users_can_register')) {
            return [
                'success' => false,
                'message' => __('User registration is currently disabled.', 'formatrica'),
                'user_id' => null,
            ];
        }

        // Extract registration fields
        $username = $data['username'] ?? '';
        $email = $data['email'] ?? '';
        $password = $data['password'] ?? '';

        // Validate required fields
        if (empty($username) || empty($email)) {
            return [
                'success' => false,
                'message' => __('Username and email are required.', 'formatrica'),
                'user_id' => null,
            ];
        }

        // Validate username
        if (!validate_username($username)) {
            return [
                'success' => false,
                'message' => __('Invalid username. Only letters, numbers, spaces, underscores, hyphens, periods, and @ symbols are allowed.', 'formatrica'),
                'user_id' => null,
            ];
        }

        // Validate email
        if (!is_email($email)) {
            return [
                'success' => false,
                'message' => __('Please provide a valid email address.', 'formatrica'),
                'user_id' => null,
            ];
        }

        // Do not reveal whether either identifier is already registered.
        if (username_exists($username) || email_exists($email)) {
            return [
                'success' => false,
                'message' => __('Registration could not be completed with those details.', 'formatrica'),
                'user_id' => null,
            ];
        }

        // Generate password if not provided
        if (empty($password)) {
            $password = wp_generate_password(12, false);
        }

        // Create the user
        $user_id = wp_insert_user([
            'user_login' => $username,
            'user_pass'  => $password,
            'user_email' => $email,
            'role'       => 'subscriber',
        ]);

        if (is_wp_error($user_id)) {
            return [
                'success' => false,
                'message' => __('Registration could not be completed. Please try again.', 'formatrica'),
                'user_id' => null,
            ];
        }

        // Add user meta if provided
        if (!empty($data['first_name'])) {
            update_user_meta($user_id, 'first_name', sanitize_text_field($data['first_name']));
        }
        if (!empty($data['last_name'])) {
            update_user_meta($user_id, 'last_name', sanitize_text_field($data['last_name']));
        }

        // Every public Formatrica-created account starts unverified, regardless
        // of later role changes or site-wide default-role settings.
        update_user_meta($user_id, 'fmt_verified', '0');

        $verification = new Verification_Service();
        $token = $verification->issue_token($user_id);
        $verify_url = $verification->verification_url($user_id, $token);

        $form_options = isset($data['__fmt_hporm_options']) && is_array($data['__fmt_hporm_options'])
            ? $data['__fmt_hporm_options']
            : null;

        $verification->send_verification_email($user_id, $email, $username, $verify_url, $form_options);

        $event_data = $data;
        unset($event_data['password'], $event_data['__fmt_hporm_options']);

        /**
         * Fires after a user is registered via Formatrica
         *
         * @param int $user_id The user ID
         * @param array $data The form submission data
         */
        do_action('formatrica_user_registered', $user_id, $event_data);

        return [
            'success' => true,
            'message' => __('Registration almost done! Please check your inbox to confirm your email address.', 'formatrica'),
            'user_id' => $user_id,
        ];
    }
}
