<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

/** Extract Google Drive file ID from common share / direct URL formats. */
function drive_extract_google_file_id(string $url): string {
    $u = trim($url);
    if ($u === '') {
        return '';
    }
    if (preg_match('~drive\\.google\\.com/file/d/([a-zA-Z0-9_-]+)~', $u, $m)) {
        return $m[1];
    }
    if (preg_match('~[\\?&]id=([a-zA-Z0-9_-]+)~', $u, $m)) {
        return $m[1];
    }
    return '';
}

/**
 * Build a direct-download URL PandaDoc can fetch (public PDF required).
 * Uses confirm=t to reduce Google virus-scan HTML responses on larger files.
 */
function drive_share_to_direct_download(string $url): string {
    $u = trim($url);
    if ($u === '') {
        return '';
    }

    $id = drive_extract_google_file_id($u);
    if ($id !== '') {
        return 'https://drive.google.com/uc?export=download&confirm=t&id=' . rawurlencode($id);
    }

    return $u;
}

/**
 * Verify the URL returns PDF bytes (PandaDoc rejects HTML login / virus-scan pages).
 *
 * @return array{ok: bool, http: int, content_type: ?string, bytes: int, error: ?string, preview: ?string}
 */
function drive_preflight_pdf_url(string $url): array {
    $url = trim($url);
    if ($url === '') {
        return ['ok' => false, 'http' => 0, 'content_type' => null, 'bytes' => 0, 'error' => 'empty_url', 'preview' => null];
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 45,
        CURLOPT_USERAGENT => 'VintageDoors-PandaDoc/1.0',
        CURLOPT_RANGE => '0-8191',
    ]);
    $body = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $curlErr = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        return ['ok' => false, 'http' => $http, 'content_type' => is_string($contentType) ? $contentType : null, 'bytes' => 0, 'error' => 'curl: ' . $curlErr, 'preview' => null];
    }
    if (!is_string($body) || $body === '') {
        return ['ok' => false, 'http' => $http, 'content_type' => is_string($contentType) ? $contentType : null, 'bytes' => 0, 'error' => 'empty_response', 'preview' => null];
    }

    $isPdf = strncmp($body, '%PDF', 4) === 0;
    if ($isPdf) {
        return ['ok' => true, 'http' => $http, 'content_type' => is_string($contentType) ? $contentType : null, 'bytes' => strlen($body), 'error' => null, 'preview' => null];
    }

    $preview = substr($body, 0, 200);
    $hint = 'URL did not return a PDF file';
    if (stripos($body, '<html') !== false || stripos($body, '<!DOCTYPE') !== false) {
        $hint = 'URL returned HTML (Google Drive file may be private, deleted, or requires confirm). Share as Anyone with the link can view and use a real file ID.';
    }
    if (preg_match('/1AbCdeFGhiJKLmnopQRstUVwxyz/i', $url)) {
        $hint = 'Placeholder example Drive URL detected — set a real Google Drive PDF link on the order/draft metafield.';
    }

    return [
        'ok' => false,
        'http' => $http,
        'content_type' => is_string($contentType) ? $contentType : null,
        'bytes' => strlen($body),
        'error' => $hint,
        'preview' => $preview,
    ];
}
