<?php
// /linkstorm/process.php
header('Content-Type: application/json; charset=utf-8');

function cleanText($text) {
    $text = preg_replace('/{\\\rtf1.*?{\\\fonttbl.*?}}/s', ' ', $text); // crude RTF header removal
    $text = strip_tags($text);
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    return $text;
}

function extractTagsFromText($text) {
    $text = cleanText($text);

    preg_match_all('/@([A-Za-z0-9_\.]+)/u', $text, $handlesMatches);
    $handles = $handlesMatches[0];

    preg_match_all('/#(\w+)/u', $text, $hashtagsMatches);
    $hashtags = $hashtagsMatches[0];

    preg_match_all('/https?:\/\/[^\s"<>\']+/i', $text, $urlMatches);
    $links = $urlMatches[0];

    preg_match_all('/[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/', $text, $emailMatches);
    $emails = $emailMatches[0];

    $handles = array_values(array_unique($handles));
    $hashtags = array_values(array_unique($hashtags));
    $links = array_values(array_unique($links));
    $emails = array_values(array_unique($emails));

    sort($handles);
    sort($hashtags);
    sort($links);
    sort($emails);

    return [
        'handles'     => $handles,
        'hashtags'    => $hashtags,
        'links'       => $links,
        'emails'      => $emails,
        'text_length' => mb_strlen($text, 'UTF-8')
    ];
}

$mode = $_POST['mode'] ?? '';

if ($mode === 'file') {
    if (!isset($_FILES['tagfile']) || $_FILES['tagfile']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['error' => 'File upload failed.']);
        exit;
    }

    $contents = file_get_contents($_FILES['tagfile']['tmp_name']);
    if ($contents === false) {
        echo json_encode(['error' => 'Could not read file.']);
        exit;
    }

    echo json_encode(extractTagsFromText($contents));
    exit;

} elseif ($mode === 'url') {
    $url = trim($_POST['source_url'] ?? '');
    if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
        echo json_encode(['error' => 'Invalid URL.']);
        exit;
    }

    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'user_agent' => 'LinkStormTagExtractor/1.0'
        ]
    ]);

    $html = @file_get_contents($url, false, $context);
    if ($html === false) {
        echo json_encode(['error' => 'Unable to fetch URL.']);
        exit;
    }

    echo json_encode(extractTagsFromText($html));
    exit;
}

echo json_encode(['error' => 'Invalid mode.']);
