<?php

namespace Formatrica\Registration;

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

final class Verification_Service
{
    public function issue_token(int $user_id, int $ttl_seconds = 3 * DAY_IN_SECONDS): string
    {
        $token = wp_generate_password(32, false, false);
        $expires = time() + max(60, $ttl_seconds);

        update_user_meta($user_id, 'fmt_verify_token', $token);
        update_user_meta($user_id, 'fmt_verify_expires', $expires);
        update_user_meta($user_id, 'fmt_verified', '0');

        return $token;
    }

    public function verification_url(int $user_id, string $token): string
    {
        $url = add_query_arg([
            'fmt_verify' => '1',
            'u' => $user_id,
            't' => $token,
        ], home_url('/'));

        return esc_url($url);
    }

    public function mark_verified(int $user_id): void
    {
        update_user_meta($user_id, 'fmt_verified', '1');
        delete_user_meta($user_id, 'fmt_verify_token');
        delete_user_meta($user_id, 'fmt_verify_expires');
    }

    public function is_valid_token(int $user_id, string $token): bool
    {
        $stored = (string) get_user_meta($user_id, 'fmt_verify_token', true);
        $expires = (int) get_user_meta($user_id, 'fmt_verify_expires', true);

        if ($stored === '' || $stored !== $token) {
            return false;
        }

        if ($expires > 0 && time() > $expires) {
            return false;
        }

        return true;
    }

    /**
     * Attempt to send via the plugin's Email_Service with form options if available.
     * Provide $form_options when calling from a form submission context.
     *
     * @param array<string,mixed>|null $form_options
     */
    public function send_verification_email(int $user_id, string $email, string $username, string $url, ?array $form_options = null): void
    {
        $subject = __('Confirm your account', 'formatrica');

        $lost_url = wp_lostpassword_url();
        $message = sprintf(
            // translators: 1: site name, 2: username, 3: verification link
            __("Welcome to %1\$s!\n\nHi %2\$s,\n\nPlease confirm your email address by clicking the link below:\n%3\$s\n\nIf you didn't set a password during registration, you can set one here after confirming: %4\$s\n\nIf you didn’t sign up, you can ignore this email.", 'formatrica'),
            wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES),
            $username,
            $url,
            $lost_url
        );

        // Prefer the plugin's configured delivery if options are provided; otherwise fall back to wp_mail.
        if (is_array($form_options)) {
            // Build a simple HTML body for better look when using providers that prefer HTML
            $html = nl2br(esc_html($message));
            $mailer = new \Formatrica\Email\Email_Service();
            $mailer->send_generic($form_options, [
                'to' => $email,
                'subject' => $subject,
                'html' => $html,
                'text' => $message,
                'from_name' => get_bloginfo('name'),
                'from_email' => '', // let Email_Service pick default/enforce domain
            ]);
            return;
        }

        $headers = [ 'Content-Type: text/plain; charset=UTF-8' ];
        wp_mail($email, $subject, $message, $headers);
    }
}
