<?php

namespace Formatrica\Admin;

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

use Formatrica\Forms\Form_Repository;
use Formatrica\Submission\Submission_Repository;

final class Delete_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'])) : '';
        $action = isset($_REQUEST['action']) ? sanitize_key(wp_unslash((string) $_REQUEST['action'])) : '';

        $is_permanent = ($action === 'formatrica_delete_permanent');
        $expected_nonce_action = $is_permanent
            ? ('formatrica_delete_permanent_' . $form_id)
            : ('formatrica_delete_' . $form_id);

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

        $form_repo = new Form_Repository();
        $submission_repo = new Submission_Repository();

        if ($is_permanent) {
            // Hard delete: remove submissions first, then form record
            $submission_repo->delete_by_form_id($form_id);
            $form_repo->hard_delete($form_id);

            $redirect = add_query_arg(
                ['page' => 'formatrica', 'deleted' => '1', 'permanent' => '1'],
                admin_url('admin.php')
            );
        } else {
            // Soft delete: deactivate form, keep submissions
            $form_repo->delete($form_id);

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

        wp_safe_redirect($redirect);
        exit;
    }
}
