<?php
declare(strict_types=1);

/**
 * Recipient signing session + hosted URL. Loaded after pandadoc.php (needs pandadoc_http, pd_env).
 * Kept in a separate file so orchestrator can require it even if an older pandadoc.php omit these helpers.
 */

if (!function_exists('pandadoc_create_document_session')) {
    /**
     * After silent send, create a recipient signing session. Response body includes id (session id).
     *
     * @return array{success: bool, id?: string, expires_at?: string, error?: mixed, http?: int}
     */
    function pandadoc_create_document_session(string $documentId, string $recipientEmail, ?int $lifetimeSeconds = null): array {
        $email = trim($recipientEmail);
        if ($email === '') {
            return ['success' => false, 'error' => 'recipient_email_required', 'http' => 0];
        }
        $path = '/documents/' . rawurlencode($documentId) . '/session';
        $body = ['recipient' => $email];
        if ($lifetimeSeconds === null) {
            $lifetimeSeconds = (int) pd_env('PANDADOC_SESSION_LIFETIME_SECONDS', '604800');
        }
        if ($lifetimeSeconds > 0) {
            $body['lifetime'] = min($lifetimeSeconds, 31535999);
        }
        $res = pandadoc_http('POST', $path, $body, 'create_document_session');
        if (!$res['ok']) {
            return ['success' => false, 'error' => $res['data'], 'http' => $res['code']];
        }
        $data = $res['data'];
        $id = is_array($data) ? (string) ($data['id'] ?? '') : '';
        if ($id === '') {
            return ['success' => false, 'error' => $data, 'http' => $res['code']];
        }
        $expires = is_array($data) ? (string) ($data['expires_at'] ?? '') : '';
        return ['success' => true, 'id' => $id, 'expires_at' => $expires];
    }
}

if (!function_exists('pandadoc_recipient_sign_url')) {
    /** Hosted signing URL for external recipients (no workspace login). */
    function pandadoc_recipient_sign_url(string $sessionId): string {
        $host = rtrim(trim((string) pd_env('PANDADOC_SIGN_APP_HOST', 'https://app.pandadoc.com')), '/');
        $id = trim($sessionId, " \t\n\r\0\x0B/");
        return $host . '/s/' . rawurlencode($id) . '/';
    }
}
