<?php

namespace Vendtics\App\Http\Controllers;

defined( "ABSPATH" ) || exit;

use Vendtics\App\Http\Controllers\Controller;
use Vendtics\WpMVC\Exceptions\Exception;
use Vendtics\WpMVC\Routing\Response;
use Vendtics\App\Repositories\ContactRepository;
use Vendtics\App\Repositories\SettingsRepository;
use Vendtics\WpMVC\RequestValidator\Validator;
use WP_REST_Request;

class DoubleOptInController extends Controller {
    public ContactRepository $contact_repository;

    public SettingsRepository $settings_repository;

    public function __construct(  ContactRepository $contact_repository, SettingsRepository $settings_repository
    ) {
        $this->contact_repository  = $contact_repository;
        $this->settings_repository = $settings_repository;
    }

    /**
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function confirm( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                'token' => 'required|string'
            ]
        );
    
        $home_url = get_home_url();

        try {
            $payload      = vendtics_verify_jwt_token( $request->get_param( 'token' ) );
            $settings     = $this->settings_repository->get_settings();
            $double_optin = $settings['double_optin'];

            $contact_id = intval( $payload['contact_id'] );
            $this->contact_repository->update_status( $contact_id, 'subscribe' );

            $redirect_url = '';

            switch ( $double_optin['after_confirmation'] ) {
                case 'redirect_to_page':
                    $redirect_url = get_permalink( intval( $double_optin['redirect_to_page'] ) );
                    break;
                case 'redirect_to_custom_url':
                    $redirect_url = $double_optin['redirect_url'];
                    break;
            }

            if ( empty( $redirect_url ) ) {
                $redirect_url = $home_url;
            }

            //phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
            wp_redirect( $redirect_url );
            exit;
        } catch ( \Throwable $th ) {
        }

        wp_safe_redirect( $home_url );
        exit;
    }
}