<?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'] ?? ''));
$contractId = isset($_POST['contract_id']) ? (int)$_POST['contract_id'] : null;
$password = (string)($_POST['password'] ?? '');

if ($token === '') {
    set_flash(__('flash_delete_missing_token'), 'error');
    redirect('/admin/dashboard');
}

if (admin_delete_password_required() && !admin_action_password_valid($password)) {
    set_flash(__('flash_delete_wrong_password'), 'error');
    redirect('/admin/dashboard');
}

try {
    if (!api_delete_contract($token, $contractId !== null && $contractId > 0 ? $contractId : null)) {
        set_flash(__('flash_delete_not_found'), 'error');
        redirect('/admin/dashboard');
    }

    set_flash('flash_contract_deleted', 'success', true);
} catch (Throwable $e) {
    set_flash(api_error_message($e), 'error');
}

redirect('/admin/dashboard');
