<?php
// اختبار تحميل فيديو من Twitter
include "../inc/con.php";

function getTwitterVideoUrl($itemUrl)
{
    $twitSaveUrl = 'https://twitsave.com/info?url=' . urlencode($itemUrl);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $twitSaveUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]);

    $html = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    echo "HTTP Code: $httpCode\n";
    echo "HTML Length: " . strlen($html) . "\n\n";

    if ($html === false) {
        echo "CURL failed\n";
        return false;
    }

    // حفظ HTML للفحص
    file_put_contents('twitsave_response.html', $html);
    echo "HTML saved to twitsave_response.html\n\n";

    // استخراج رابط الفيديو من <video src="...">
    if (preg_match('/<video[^>]+src="(https:\/\/video\.twimg\.com\/[^"]+\.mp4[^"]*)"/', $html, $matches)) {
        echo "Found video URL (from video tag): " . $matches[1] . "\n";
        return html_entity_decode($matches[1]);
    }

    // البحث عن رابط التحميل في الأزرار
    if (preg_match('/<a href="(https:\/\/[^"]+\.mp4[^"]*)"[^>]*download[^>]*>/i', $html, $matches)) {
        echo "Found video URL (pattern 1): " . $matches[1] . "\n";
        return html_entity_decode($matches[1]);
    }

    if (preg_match('/<a[^>]+download[^>]+href="(https:\/\/[^"]+\.mp4[^"]*)"/i', $html, $matches)) {
        echo "Found video URL (pattern 2): " . $matches[1] . "\n";
        return html_entity_decode($matches[1]);
    }

    echo "No video URL found\n";
    return false;
}

// اختبار
$testUrl = 'https://x.com/RassdNewsN/status/2020965931523158098';
echo "Testing URL: $testUrl\n\n";

$videoUrl = getTwitterVideoUrl($testUrl);

if ($videoUrl) {
    echo "\n✅ SUCCESS: Video URL found!\n";
    echo "URL: $videoUrl\n";
} else {
    echo "\n❌ FAILED: Could not extract video URL\n";
}
