<?php
// cron_auto_send.php

// --- تنظیمات اولیه ---
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Tehran');

// --- تعریف ثابت‌ها ---
define('BOT_TOKEN', '7652901481:AAFsXTtnMGP8Tn4R49v6fu50EYmwjF5iSi8');
define('UPLOAD_PATH', __DIR__ . '/uploads/screenshots/');
define('DATA_DIR', __DIR__ . '/data/');
define('SUPPORT_ID', 'safegoldstore');
define('AUTO_SEND_CAPTION', "📤 ارسال خودکار توسط سیف بات\n");
define('LOG_FILE', __DIR__ . '/logs/cron_auto_send.log');

// --- اطمینان از وجود فایل‌های ضروری ---
if (!is_dir(DATA_DIR)) {
    if (!mkdir(DATA_DIR, 0755, true)) {
        error_log("Could not create data directory: " . DATA_DIR);
        die('Server Error');
    }
}
if (!is_dir(dirname(LOG_FILE))) {
    if (!mkdir(dirname(LOG_FILE), 0755, true)) {
        error_log("Could not create logs directory: " . dirname(LOG_FILE));
        die('Server Error');
    }
}
if (!is_dir(UPLOAD_PATH)) {
    if (!mkdir(UPLOAD_PATH, 0755, true)) {
        error_log("Could not create uploads directory: " . UPLOAD_PATH);
        die('Server Error');
    }
}

// --- ایمپورت jdf.php ---
if (!file_exists(__DIR__ . '/jdf.php')) {
    error_log("jdf.php not found in root directory. Cannot format date.");
    die('jdf.php not found');
} else {
    require_once __DIR__ . '/jdf.php';
}

// --- تعریف APIهای اسکرین‌شات ---
function getScreenshotAPIs() {
    return [
        'apiflash1' => 'https://api.apiflash.com/v1/urltoimage?access_key=6590e94682bf42afb79a6fcc9776b5f7&url=https%3A%2F%2Fsafegold.store%2Flatest-price&format=jpeg&width=1080&height=1920&fresh=true&quality=100&delay=10&ttl=5&response_type=image',
        'apiflash2' => 'https://api.apiflash.com/v1/urltoimage?access_key=ce1316432be3450da21f25a91c761f47&url=https%3A%2F%2Fsafegold.store%2Flatest-price&format=jpeg&width=1080&height=1920&fresh=true&quality=100&delay=10&ttl=5&response_type=image',
        'apiflash3' => 'https://api.apiflash.com/v1/urltoimage?access_key=9063ca754e8f40f8abbdbf6d360d514f&url=https%3A%2F%2Fsafegold.store%2Flatest-price&format=jpeg&width=1080&height=1920&fresh=true&quality=100&delay=10&ttl=5&response_type=image',
        'apiflash4' => 'https://api.apiflash.com/v1/urltoimage?access_key=e0a332cf0ae0417293bfc8ba8c438d95&url=https%3A%2F%2Fsafegold.store%2Flatest-price&format=jpeg&width=1080&height=1920&fresh=true&quality=100&delay=10&ttl=5&response_type=image',
        'apiflash5' => 'https://api.apiflash.com/v1/urltoimage?access_key=5f5b3735f3ed4107b5ab4fbb007e3b72&url=https%3A%2F%2Fsafegold.store%2Flatest-price&format=jpeg&width=1080&height=1920&fresh=true&quality=100&delay=10&ttl=5&response_type=image',
    ];
}

// --- کلاس ساده HttpClient برای استفاده در cron ---
class SimpleHttpClient {
    private $user_agents = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    ];

    public function get($url, $options = []) {
        $timeout = $options['timeout'] ?? 30;
        $max_retries = $options['max_retries'] ?? 2;
        $headers = $options['headers'] ?? [];

        $userAgent = $this->user_agents[array_rand($this->user_agents)];
        $defaultHeaders = [
            'User-Agent: ' . $userAgent,
            'Accept: image/jpeg, image/png, */*',
        ];
        $allHeaders = array_merge($defaultHeaders, $headers);

        $attempts = 0;
        
        while ($attempts <= $max_retries) {
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => $timeout,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_HTTPHEADER => $allHeaders,
                CURLOPT_HEADER => false,
                CURLOPT_BINARYTRANSFER => true,
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
            curl_close($ch);

            // بررسی موفقیت آمیز بودن پاسخ
            if (!$error && $httpCode === 200 && $response && strlen($response) > 1000) {
                if (strpos($contentType, 'image/jpeg') !== false || 
                    strpos($contentType, 'image/png') !== false) {
                    return ['success' => true, 'error' => null, 'data' => $response];
                }
            }

            error_log("cURL attempt $attempts failed for URL: $url. Error: $error, HTTP Code: $httpCode, Content-Type: $contentType, Response Size: " . strlen($response));
            
            if ($attempts < $max_retries) {
                sleep(2);
            }
            $attempts++;
        }

        return ['success' => false, 'error' => $error ?: "HTTP Error: $httpCode", 'data' => null];
    }
}

// --- تابع اصلی گرفتن تصویر ---
function captureAndSaveNewScreenshot() {
    $httpClient = new SimpleHttpClient();
    $apis = getScreenshotAPIs();

    foreach ($apis as $apiName => $url) {
        error_log("Cron: Trying API: $apiName");
        $response = $httpClient->get($url, ['timeout' => 30, 'max_retries' => 1]);

        if ($response['success'] && $response['data']) {
            $timestamp = time();
            $formatted_date = date('Y-m-d_H-i', $timestamp);
            $file_name = "auto_" . $formatted_date . '.jpg';
            $file_path = UPLOAD_PATH . $file_name;

            // بررسی حجم تصویر
            if (strlen($response['data']) < 1000) {
                error_log("Cron: Image too small from $apiName, size: " . strlen($response['data']));
                continue;
            }

            if (file_put_contents($file_path, $response['data'])) {
                if (file_exists($file_path) && filesize($file_path) > 1000) {
                    error_log("Cron: Screenshot saved successfully: $file_path, Size: " . filesize($file_path));
                    return $file_name;
                } else {
                    error_log("Cron: File saved but invalid: $file_path");
                }
            } else {
                error_log("Cron: Failed to save file: $file_path");
                if (!is_writable(UPLOAD_PATH)) {
                    error_log("Cron: Upload directory is not writable: " . UPLOAD_PATH);
                }
            }
        } else {
            error_log("Cron: API $apiName failed: " . $response['error']);
        }
    }

    error_log("Cron: All screenshot APIs failed");
    return false;
}

// --- تابع ارسال تصویر به یک چت ---
function sendPhotoToChat($chatId, $photoPath, $caption, $photoUrl) {
    $token = BOT_TOKEN;

    if (!file_exists($photoPath)) {
        error_log("Cron: Photo file not found: $photoPath");
        return false;
    }

    $fileSize = filesize($photoPath);
    if ($fileSize < 1000) {
        error_log("Cron: Photo file too small: $photoPath, Size: $fileSize");
        return false;
    }

    $url = "https://api.telegram.org/bot{$token}/sendPhoto";

    $postFields = [
        'chat_id' => $chatId,
        'photo' => new CURLFile($photoPath),
        'caption' => $caption,
        'parse_mode' => 'HTML'
    ];

    if (filter_var($photoUrl, FILTER_VALIDATE_URL)) {
        $postFields['reply_markup'] = json_encode([
            'inline_keyboard' => [
                [
                    ['text' => '📥 دانلود تصویر', 'url' => $photoUrl]
                ]
            ]
        ]);
    }

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);

    if ($error) {
        error_log("Cron: cURL Error for chat $chatId: $error");
        return false;
    } elseif ($httpCode !== 200) {
        error_log("Cron: HTTP Error $httpCode for chat $chatId: " . ($responseData['description'] ?? $response));
        return false;
    } elseif (!$responseData || !$responseData['ok']) {
        error_log("Cron: Telegram API Error for chat $chatId: " . ($responseData['description'] ?? 'Unknown error'));
        return false;
    } else {
        error_log("Cron: Successfully sent to chat $chatId");
        return true;
    }
}

// --- اصل اسکریپت Cron ---
try {
    error_log("=== Cron Auto-Send Started ===");

    // 1. گرفتن تصویر جدید
    error_log("Cron: Starting screenshot capture...");
    $newFileName = captureAndSaveNewScreenshot();
    
    if (!$newFileName) {
        throw new Exception("Failed to capture new screenshot from all APIs");
    }

    $fullPath = UPLOAD_PATH . $newFileName;
    if (!file_exists($fullPath)) {
        throw new Exception("Captured file not found: $fullPath");
    }

    // 2. ساخت URL تصویر
    $photoUrl = "https://safegold.store/telegram-bot/uploads/screenshots/" . $newFileName;

    // 3. ایجاد کپشن
    $currentTime = time();
    $jalaliDateTime = jdate('Y/m/d H:i', $currentTime);
    $caption = AUTO_SEND_CAPTION . "⏰ ساعت: {$jalaliDateTime}\n";
    $caption .= "🔗 @safegoldstore";

    // 4. لیست ثابت کاربران و گروه‌ها برای ارسال
    $targetChats = [
        6685722743,      // کاربر
        -4683206479      // گروه
    ];

    // 5. ارسال به لیست ثابت
    $successCount = 0;
    $failCount = 0;
    $total = count($targetChats);
    
    error_log("Cron: Starting to send to $total target chats...");

    foreach ($targetChats as $index => $chatId) {
        error_log("Cron: Sending to chat $index/$total: $chatId");
        
        if (sendPhotoToChat($chatId, $fullPath, $caption, $photoUrl)) {
            $successCount++;
        } else {
            $failCount++;
            error_log("Cron: Failed to send to chat: $chatId");
        }

        // تاخیر بین ارسال‌ها برای جلوگیری از محدودیت تلگرام
        if ($index < $total - 1) {
            sleep(1);
        }
    }

    // 6. گزارش نهایی
    $logMessage = "Cron Auto-Send completed. Success: $successCount, Failed: $failCount, Total: $total, File: $newFileName";
    error_log($logMessage);

} catch (Exception $e) {
    $errorMsg = "Cron Auto-Send Error: " . $e->getMessage();
    error_log($errorMsg);
}

error_log("=== Cron Auto-Send Finished ===");