<?php

namespace Formatrica\Admin;

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

use Formatrica\Forms\Form_Repository;

final class Activate_Controller
{
    public function handle(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized', 'formatrica'), 403);
        }

        $form_id = isset($_GET['form_id']) ? (int) $_GET['form_id'] : 0;
        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';

        if (!$form_id || !wp_verify_nonce($nonce, 'formatrica_activate_' . $form_id)) {
            wp_die(esc_html__('Invalid request', 'formatrica'), 400);
        }

        $repo = new Form_Repository();
        $repo->activate($form_id);

        $redirect = add_query_arg(
            ['page' => 'formatrica', 'activated' => '1'],
            admin_url('admin.php')
        );

        wp_safe_redirect($redirect);
        exit;
    }
}
