<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/api_service.php';

auth_require();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('/admin/dashboard');
}

$token = trim((string)($_POST['token'] ?? ''));
$id = (int)($_POST['id'] ?? 0);

if ($token === '' && $id <= 0) {
    set_flash(__('flash_duplicate_missing_token'), 'error');
    redirect('/admin/dashboard');
}

try {
    $duplicate = api_duplicate_contract($token, $id);

    if ($duplicate === null) {
        set_flash(__('flash_duplicate_not_found'), 'error');
        redirect('/admin/dashboard');
    }

    auth_start();
    $_SESSION['duplicated_contract_link'] = contract_public_sign_url_from_record($duplicate)
        ?: contract_customer_url($duplicate)
        ?: contract_url((string)($duplicate['token'] ?? ''));
    set_flash('flash_contract_duplicated', 'success', true);
} catch (Throwable $e) {
    set_flash(api_error_message($e), 'error');
}

redirect('/admin/dashboard');
