<?php

namespace Formatrica\Admin;

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

use Formatrica\Forms\Form_Repository;

final class Duplicate_Controller
{
    private Form_Repository $forms;

    public function __construct(?Form_Repository $forms = null)
    {
        $this->forms = $forms ?? new Form_Repository();
    }

    public function handle(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You are not allowed to duplicate forms.', 'formatrica'), '', ['response' => 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 <= 0 || !wp_verify_nonce($nonce, 'formatrica_duplicate_' . $form_id)) {
            wp_die(esc_html__('Invalid duplicate request.', 'formatrica'), '', ['response' => 400]);
        }

        try {
            $duplicate_id = $this->forms->duplicate($form_id);
        } catch (\Throwable $error) {
            wp_die(esc_html($error->getMessage()), '', ['response' => 500]);
        }

        $redirect = add_query_arg([
            'page' => 'formatrica-builder',
            'form_id' => $duplicate_id,
        ], admin_url('admin.php'));

        wp_safe_redirect($redirect);
        exit;
    }
}
