<?php
require_once __DIR__ . '/bootstrap_api.php';

if (!function_exists('rz_fetch_pdf_for_addin')) {
    function rz_fetch_pdf_for_addin(string $url): string
    {
        if (!function_exists('curl_init')) {
            throw new RuntimeException('PHP cURL is required to generate the PDF.');
        }

        $ch = curl_init($url);
        if ($ch === false) {
            throw new RuntimeException('Could not initialise the PDF request.');
        }

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 4,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_TIMEOUT => 90,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_HTTPHEADER => [
                'Accept: application/pdf',
                'User-Agent: RoomZ-Outlook-Addin/1.1',
            ],
        ]);

        $body = curl_exec($ch);
        $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $contentType = strtolower((string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
        $error = curl_error($ch);
        curl_close($ch);

        if ($body === false || $error !== '') {
            throw new RuntimeException('The PDF request failed: ' . $error);
        }

        if ($status < 200 || $status >= 300) {
            $preview = trim(strip_tags(substr((string)$body, 0, 500)));
            throw new RuntimeException(
                'The PDF generator returned HTTP ' . $status . '.'
                . ($preview !== '' ? ' Response: ' . $preview : '')
            );
        }

        if (strncmp((string)$body, '%PDF-', 5) !== 0
            && strpos($contentType, 'application/pdf') === false) {
            $preview = trim(strip_tags(substr((string)$body, 0, 250)));
            throw new RuntimeException(
                'The PDF generator did not return a valid PDF.'
                . ($preview !== '' ? ' Response: ' . $preview : '')
            );
        }

        return (string)$body;
    }
}

try {
    $input = api_input();

    /*
     * The session token is deliberately accepted in JSON because the hosting
     * stack may strip the Authorization header before it reaches PHP.
     */
    $sessionToken = trim((string)($input['session_token'] ?? ''));
    if ($sessionToken === '') {
        $sessionToken = api_bearer();
    }

    $session = api_session($pdo, $sessionToken);
    $orderId = (int)$session['order_id'];
    $booking = comm_booking($pdo, $orderId);

    $type = strtolower(trim((string)($input['document_type'] ?? 'standard')));
    if ($type !== 'standard') {
        api_json([
            'ok' => false,
            'message' => 'Unsupported document type.',
        ], 422);
    }

    /*
     * proforma_invoice.php validates addin_token through the TOKEN_BRIDGE patch.
     * Pass the same verified add-in session token in the query string.
     */
    $url = comm_base_url()
        . '/rooms/modules/reservations/proforma_invoice.php?order_id='
        . rawurlencode((string)$orderId)
        . '&addin_token='
        . rawurlencode($sessionToken);

    $pdf = rz_fetch_pdf_for_addin($url);

    if (strlen($pdf) > 3 * 1024 * 1024) {
        api_json([
            'ok' => false,
            'message' => 'The PDF exceeds the 3 MB Outlook attachment limit.',
        ], 413);
    }

    $safeOrderNo = preg_replace(
        '/[^A-Za-z0-9_-]+/',
        '_',
        (string)($booking['order_no'] ?: $orderId)
    );
    $filename = 'Proforma_' . $safeOrderNo . '.pdf';

    $stmt = $pdo->prepare("
        INSERT INTO communication_log
        (
            order_id,
            user_id,
            channel,
            action,
            document_type,
            document_name,
            status,
            notes
        )
        VALUES
        (
            :order_id,
            :user_id,
            'outlook',
            'pdf_attached',
            'standard',
            :document_name,
            'completed',
            'Attached through Outlook add-in'
        )
    ");
    $stmt->execute([
        ':order_id'     => $orderId,
        ':user_id'      => (int)$session['user_id'],
        ':document_name'=> $filename,
    ]);

    api_json([
        'ok'       => true,
        'filename' => $filename,
        'base64'   => base64_encode($pdf),
    ]);
} catch (Throwable $exception) {
    error_log(
        'RoomZ Outlook document error: '
        . $exception->getMessage()
        . ' in '
        . $exception->getFile()
        . ':'
        . $exception->getLine()
    );

    api_json([
        'ok' => false,
        'message' => 'Could not attach the PDF: ' . $exception->getMessage(),
    ], 500);
}
