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

$url = 'https://taw-bio.ir/category/Religious';

// گرفتن 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;
}

// استخراج اشعار
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) {
        $divs = $article->getElementsByTagName('div');
        foreach ($divs as $div) {
            if ($div->getAttribute('class') == 't fa') {
                $poem = trim($div->textContent);
                if (!empty($poem)) {
                    $poems[] = $poem;
                }
            }
        }
    }

    return $poems;
}

// اجرا
$html = getHtml($url);
$poems = extractPoems($html);

// انتخاب رندوم یکی از شعرها
if (!empty($poems)) {
    $randomPoem = $poems[array_rand($poems)];
    echo json_encode(['text' => $randomPoem], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
    echo json_encode(['error' => 'هیچ شعری یافت نشد.'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
