<?php
/**
 * Single-page fetch proxy — same interface as backend/cloudflare-worker/worker.js,
 * so pointing any tool's "custom fetch backend" setting at this file's URL works
 * immediately with zero front-end code changes:
 *
 *   GET /backend-php/api/fetch.php?url=<target>  -> returns the target page's raw HTML
 *
 * Fetches happen server-side via cURL, so there's no CORS involved at all —
 * this class of failure the public relays hit (blocked/rate-limited relay IPs)
 * doesn't apply here. The target site can still block based on its own bot
 * detection, same as any fetch method.
 */
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

require_once __DIR__ . '/../includes/crawler.php';
require_once __DIR__ . '/../includes/auth.php';
send_cors_headers();

$target = $_GET['url'] ?? '';
if ($target === '') {
    http_response_code(400);
    header('Content-Type: text/plain');
    echo 'Missing ?url= parameter';
    exit;
}

$url = crawlie_normalize_url($target);
$result = crawlie_fetch($url);

if (!$result['ok']) {
    http_response_code(502);
    header('Content-Type: text/plain');
    echo 'Fetch failed: ' . $result['error'];
    exit;
}

header('Content-Type: text/html; charset=utf-8');
echo $result['html'];
