<?php
declare(strict_types=1);

require_once '/home/jrundfpc/private_ww/colabgpt/action_relay.php';

function colabgpt_direct_html(string $title,string $body,int $status=200): never
{
    http_response_code($status);
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: no-store');
    header('X-Content-Type-Options: nosniff');
    header('Referrer-Policy: no-referrer');
    $safeTitle=htmlspecialchars($title,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8');
    echo '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
    echo '<title>'.$safeTitle.'</title><style>body{font-family:Arial,sans-serif;background:#f7f2e8;color:#243447;max-width:760px;margin:40px auto;padding:0 20px;line-height:1.55}';
    echo '.card{background:#fffaf1;border:1px solid #9ab8b5;border-radius:12px;padding:24px}h1{color:#2f6f73}button{background:#2f6f73;color:white;border:0;border-radius:8px;padding:12px 18px;font-size:16px}';
    echo 'input[type=file]{display:block;margin:18px 0;font-size:16px}.ok{background:#e4f0e3;padding:12px;border-radius:8px}.err{background:#f3e2e0;padding:12px;border-radius:8px}</style></head><body>';
    echo '<div class="card"><h1>'.$safeTitle.'</h1>'.$body.'</div></body></html>';
    exit;
}

$token=isset($_GET['t'])&&is_string($_GET['t'])?$_GET['t']:'';
if($token==='') colabgpt_direct_html('Invalid link','<p class="err">This link is missing its secure token.</p>',400);

try{
    $service=colabgpt_direct_file_transfer_service();
    $method=strtoupper((string)($_SERVER['REQUEST_METHOD']??'GET'));

    // Try download token first.
    try{
        $claims=$service->decodePublicToken($token,'download');
        if($method!=='GET') colabgpt_direct_html('Method not allowed','<p class="err">This download link only supports GET.</p>',405);
        $service->downloadFile($claims);
    }catch(RuntimeException $downloadError){
        if(!in_array($downloadError->getMessage(),['DIRECT_TRANSFER_TOKEN_INVALID','DIRECT_TRANSFER_TOKEN_EXPIRED'],true)){
            throw $downloadError;
        }
    }

    $claims=$service->decodePublicToken($token,'upload');
    if($method==='GET'){
        $safeToken=htmlspecialchars($token,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8');
        colabgpt_direct_html(
            'Upload project files',
            '<p>Select one or more files. They will upload directly to the authorised CollabGPT project.</p>'.
            '<p><b>No Base64 or GPT chunk transfer is used.</b></p>'.
            '<form method="post" enctype="multipart/form-data" action="?t='.$safeToken.'">'.
            '<input type="file" name="files[]" multiple required>'.
            '<button type="submit">Upload files</button></form>'.
            '<p><small>This secure link expires automatically.</small></p>'
        );
    }
    if($method!=='POST') colabgpt_direct_html('Method not allowed','<p class="err">Unsupported request method.</p>',405);
    if(!isset($_FILES['files'])||!is_array($_FILES['files'])){
        colabgpt_direct_html('No files selected','<p class="err">Choose at least one file.</p>',400);
    }
    $result=$service->storeBrowserUploads($claims,$_FILES['files']);
    $items='';
    foreach($result['files'] as $f){
        $items.='<li><b>'.htmlspecialchars((string)$f['fileName'],ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8').'</b> - '.
            number_format((int)$f['byteSize']).' bytes</li>';
    }
    colabgpt_direct_html(
        'Upload complete',
        '<p class="ok"><b>'.(int)$result['storedCount'].' file(s) stored successfully.</b></p>'.
        '<ul>'.$items.'</ul><p>You can return to CollabGPT and ask it to list the project files.</p>'
    );
}catch(RuntimeException|InvalidArgumentException $e){
    $msg=$e->getMessage()==='DIRECT_TRANSFER_TOKEN_EXPIRED'
        ? 'This secure link has expired. Ask CollabGPT for a fresh link.'
        : 'The file transfer could not be completed safely.';
    colabgpt_direct_html('Transfer stopped','<p class="err">'.htmlspecialchars($msg,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8').'</p>',400);
}
