<?php
header("Content-Type: application/json; charset=UTF-8");

$urls = [
    'https://taw-bio.ir/f/cat/text/Horn~1~tr~bst',
    'https://taw-bio.ir/f/cat/text/Horn~2~tr~bst',
    'https://taw-bio.ir/f/cat/text/Horn~3~tr~bst',
    'https://taw-bio.ir/f/cat/text/Horn~4~tr~bst'
];

// گرفتن HTML از سایت
function getHtml($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    $html = curl_exec($ch);
    curl_close($ch);
    return $html;
}

// استخراج اشعار فارسی و ترکی از هر article
function extractPoems($html) {
    $poems = [];

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
    $xpath = new DOMXPath($dom);

    $articles = $xpath->query('//article[contains(@class, "iTxt")]');

    foreach ($articles as $article) {
        $farsiNode = $xpath->query('.//div[contains(@class, "t") and contains(@class, "fa")]', $article)->item(0);
        $torkiNode = $xpath->query('.//div[contains(@class, "t") and contains(@class, "tr")]', $article)->item(0);

        if ($farsiNode && $torkiNode) {
            $farsiText = trim($farsiNode->textContent);
            $torkiText = trim($torkiNode->textContent);

            if (!empty($farsiText) && !empty($torkiText)) {
                $poems[] = [
                    'farsi' => $farsiText,
                    'TORKI' => $torkiText
                ];
            }
        }
    }

    return $poems;
}

// استخراج اشعار از همه URLها
$allPoems = [];

foreach ($urls as $url) {
    $html = getHtml($url);
    $poems = extractPoems($html);
    $allPoems = array_merge($allPoems, $poems);
}

// خروجی تصادفی
if (!empty($allPoems)) {
    $randomPoem = $allPoems[array_rand($allPoems)];
    echo json_encode($randomPoem, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
    echo json_encode(['error' => 'هیچ متنی پیدا نشد.'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
?>
