<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/api_service.php';
require_once __DIR__ . '/../includes/invoice_contract.php';

header('Content-Type: application/json; charset=utf-8');

if (!auth_check()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    if (api_can_use_partner_api()) {
        $type = trim((string)($_GET['type'] ?? 'partner'));
        $contracts = api_fetch_partner_contracts($type !== '' ? $type : 'partner');
    } else {
        $contracts = array_values(array_filter(
            api_all_contracts(),
            static fn(array $contract): bool => invoice_contract_is_partner_record($contract)
                || !invoice_contract_is($contract)
        ));

        $contracts = array_map(static function (array $contract): array {
            if (!empty($contract['sign_token']) || !empty($contract['token'])) {
                return array_merge($contract, [
                    'customer_url' => contract_public_sign_path((string)($contract['sign_token'] ?? $contract['token'] ?? '')),
                ]);
            }

            return $contract;
        }, $contracts);
    }

    echo json_encode([
        'success' => true,
        'contracts' => $contracts,
        'count' => count($contracts),
        'synced_at' => gmdate('c'),
        'source' => api_can_use_partner_api() ? 'partner_api' : 'local',
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    $status = $e instanceof ApiException ? max(400, $e->statusCode) : 500;

    http_response_code($status);
    echo json_encode([
        'success' => false,
        'message' => api_error_message($e),
    ], JSON_UNESCAPED_UNICODE);
}
