<?php
/**
 * SMM Paket Satış Scripti - Cron Job
 * 
 * Görevler:
 * 1. Yeni siparişlerde admin'e mail gönder
 * 2. Sipariş durumu değişikliklerinde müşteriye mail gönder
 * 3. API siparişlerinin durumunu sorgula ve güncelle
 * 
 * @version 1.1.0
 */

// Hataları göster (debug için)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Zaman limiti
set_time_limit(300);

// Zaman dilimi
date_default_timezone_set('Europe/Istanbul');

// Ana dizini bul
$baseDir = dirname(__DIR__);

// Logs klasörünü oluştur
$logsDir = $baseDir . '/logs';
if (!is_dir($logsDir)) {
    if (!@mkdir($logsDir, 0755, true)) {
        die("HATA: logs klasörü oluşturulamadı: " . $logsDir);
    }
}

// Günlük log dosyası
$logFile = $logsDir . '/cron_' . date('Y-m-d') . '.log';

// Log sayaçları
$logStats = [
    'started_at' => date('Y-m-d H:i:s'),
    'new_orders_checked' => 0,
    'admin_mails_sent' => 0,
    'status_changes_checked' => 0,
    'customer_mails_sent' => 0,
    'api_orders_checked' => 0,
    'api_orders_updated' => 0,
    'errors' => []
];

/**
 * Log yaz
 */
function cronLog($message, $type = 'INFO') {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[{$timestamp}] [{$type}] {$message}\n";
    file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);
    echo $logMessage;
}

function cronError($message) {
    global $logStats;
    $logStats['errors'][] = $message;
    cronLog($message, 'ERROR');
}

function cronSuccess($message) {
    cronLog($message, 'SUCCESS');
}

// Config dosyasını dahil et
$configFile = $baseDir . '/config.php';
if (!file_exists($configFile)) {
    die("HATA: config.php bulunamadı: " . $configFile);
}

require_once $configFile;

/**
 * Cron log kaydı var mı kontrol et
 */
function hasCronLog($db, $orderId, $logType, $status = null) {
    try {
        if ($status !== null) {
            $stmt = $db->prepare("SELECT COUNT(*) FROM cron_logs WHERE order_id = ? AND log_type = ? AND status_sent = ? AND success = 1");
            $stmt->execute([$orderId, $logType, $status]);
        } else {
            $stmt = $db->prepare("SELECT COUNT(*) FROM cron_logs WHERE order_id = ? AND log_type = ? AND success = 1");
            $stmt->execute([$orderId, $logType]);
        }
        return $stmt->fetchColumn() > 0;
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Cron log kaydı ekle
 */
function addCronLog($db, $orderId, $logType, $status, $emailSentTo, $success = true, $errorMessage = null) {
    try {
        $stmt = $db->prepare("INSERT INTO cron_logs (order_id, log_type, status_sent, email_sent_to, success, error_message) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$orderId, $logType, $status, $emailSentTo, $success ? 1 : 0, $errorMessage]);
        return true;
    } catch (PDOException $e) {
        cronError("Cron log kaydı eklenemedi: " . $e->getMessage());
        return false;
    }
}

/**
 * SMTP Ayarı oku
 */
function getSmtpSetting($db, $key, $default = '') {
    try {
        $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn();
        return $value !== false ? $value : $default;
    } catch (PDOException $e) {
        return $default;
    }
}

/**
 * Mail gönder
 */
function sendCronMail($db, $settings, $toEmail, $toName, $subject, $body) {
    global $baseDir;
    
    if (getSmtpSetting($db, 'smtp_enabled', '0') !== '1') {
        return ['success' => false, 'error' => 'SMTP devre dışı'];
    }
    
    $phpmailerPath = $baseDir . '/includes/PHPMailer/PHPMailer.php';
    if (!file_exists($phpmailerPath)) {
        return ['success' => false, 'error' => 'PHPMailer bulunamadı'];
    }
    
    require_once $baseDir . '/includes/PHPMailer/Exception.php';
    require_once $baseDir . '/includes/PHPMailer/PHPMailer.php';
    require_once $baseDir . '/includes/PHPMailer/SMTP.php';
    
    $smtpHost = getSmtpSetting($db, 'smtp_host', '');
    $smtpPort = (int)getSmtpSetting($db, 'smtp_port', 587);
    $smtpUsername = getSmtpSetting($db, 'smtp_username', '');
    $smtpPassword = getSmtpSetting($db, 'smtp_password', '');
    $smtpEncryption = getSmtpSetting($db, 'smtp_encryption', 'tls');
    $smtpFromEmail = getSmtpSetting($db, 'smtp_from_email', $smtpUsername);
    $smtpFromName = getSmtpSetting($db, 'smtp_from_name', $settings->get('site_name', 'SMM Panel'));
    
    if (empty($smtpHost) || empty($smtpUsername) || empty($smtpPassword)) {
        return ['success' => false, 'error' => 'SMTP ayarları eksik'];
    }
    
    try {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        
        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->Port = $smtpPort;
        $mail->SMTPAuth = true;
        $mail->Username = $smtpUsername;
        $mail->Password = $smtpPassword;
        
        if ($smtpEncryption === 'tls') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        } elseif ($smtpEncryption === 'ssl') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = false;
            $mail->SMTPAutoTLS = false;
        }
        
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];
        
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        
        $mail->setFrom($smtpFromEmail, $smtpFromName);
        $mail->addReplyTo($smtpFromEmail, $smtpFromName);
        $mail->addAddress($toEmail, $toName);
        
        $mail->isHTML(true);
        $mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
        $mail->Body = $body;
        $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $body));
        
        $mail->send();
        
        return ['success' => true];
        
    } catch (PHPMailer\PHPMailer\Exception $e) {
        return ['success' => false, 'error' => $mail->ErrorInfo];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

/**
 * Müşteri bilgilendirme mail şablonu
 */
function getCustomerStatusEmailTemplate($siteName, $siteUrl, $order, $package, $newStatus) {
    $statusTexts = [
        'pending' => ['text' => 'Beklemede', 'color' => '#f59e0b', 'icon' => '⏳', 'desc' => 'Siparişiniz ödeme bekleniyor.'],
        'paid' => ['text' => 'Ödeme Alındı', 'color' => '#3b82f6', 'icon' => '💳', 'desc' => 'Ödemeniz alındı, siparişiniz işleme alınacak.'],
        'processing' => ['text' => 'İşleniyor', 'color' => '#8b5cf6', 'icon' => '⚡', 'desc' => 'Siparişiniz işleniyor, lütfen bekleyin.'],
        'completed' => ['text' => 'Tamamlandı', 'color' => '#10b981', 'icon' => '✅', 'desc' => 'Siparişiniz başarıyla tamamlandı!'],
        'cancelled' => ['text' => 'İptal Edildi', 'color' => '#ef4444', 'icon' => '❌', 'desc' => 'Siparişiniz iptal edildi.'],
        'refunded' => ['text' => 'İade Edildi', 'color' => '#6b7280', 'icon' => '↩️', 'desc' => 'Siparişiniz iade edildi.'],
    ];
    
    $status = $statusTexts[$newStatus] ?? ['text' => $newStatus, 'color' => '#64748b', 'icon' => '📦', 'desc' => ''];
    
    return '<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#0f172a;font-family:Arial,Helvetica,sans-serif;">
<div style="max-width:600px;margin:0 auto;padding:40px 20px;">
<div style="background:#1e293b;border-radius:24px;overflow:hidden;border:1px solid #334155;">
<div style="background:linear-gradient(135deg,' . $status['color'] . ',#8b5cf6);padding:40px 30px;text-align:center;">
<div style="font-size:50px;margin-bottom:15px;">' . $status['icon'] . '</div>
<h1 style="margin:0;color:#fff;font-size:24px;font-weight:700;">Sipariş Durumu: ' . $status['text'] . '</h1>
<p style="margin:15px 0 0;color:rgba(255,255,255,0.8);font-size:15px;">' . $status['desc'] . '</p>
</div>
<div style="padding:35px 30px;">
<p style="color:#e2e8f0;font-size:16px;margin:0 0 25px;">Merhaba <strong>' . htmlspecialchars($order['customer_name']) . '</strong>,</p>
<div style="background:#0f172a;border-radius:16px;padding:25px;margin-bottom:25px;border:1px solid #334155;">
<table style="width:100%;border-collapse:collapse;">
<tr><td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Sipariş No</td><td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;font-weight:600;">#' . htmlspecialchars($order['order_number']) . '</td></tr>
<tr><td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Paket</td><td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;">' . htmlspecialchars($package['name']) . '</td></tr>
<tr><td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Tutar</td><td style="padding:12px 0;border-bottom:1px solid #1e293b;color:#10b981;font-size:16px;text-align:right;font-weight:700;">₺' . number_format($order['amount'], 2, ',', '.') . '</td></tr>
<tr><td style="padding:12px 0;color:#94a3b8;font-size:14px;">Durum</td><td style="padding:12px 0;text-align:right;"><span style="display:inline-block;background:' . $status['color'] . ';color:#fff;padding:6px 16px;border-radius:20px;font-size:13px;font-weight:600;">' . $status['text'] . '</span></td></tr>
</table>
</div>
<div style="text-align:center;margin:30px 0;">
<a href="' . $siteUrl . '/siparis-sorgula.php" style="display:inline-block;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;text-decoration:none;padding:16px 40px;border-radius:12px;font-weight:600;font-size:15px;">Sipariş Detayı</a>
</div>
<p style="color:#64748b;font-size:13px;margin:0;text-align:center;">Sorularınız için bizimle iletişime geçebilirsiniz.</p>
</div>
<div style="background:#0f172a;padding:25px 30px;text-align:center;border-top:1px solid #1e293b;">
<p style="color:#64748b;font-size:13px;margin:0;">© ' . date('Y') . ' ' . htmlspecialchars($siteName) . ' - Tüm hakları saklıdır.</p>
</div>
</div>
</div>
</body>
</html>';
}

/**
 * Admin yeni sipariş mail şablonu
 */
function getAdminNewOrderEmailTemplate($siteName, $siteUrl, $order, $package) {
    $isApi = !empty($package['api_provider_id']) && !empty($package['api_service_id']);
    $orderType = $isApi ? 'API Sipariş' : 'Manuel Sipariş';
    $typeColor = $isApi ? '#8b5cf6' : '#f59e0b';
    $typeIcon = $isApi ? '🤖' : '👤';
    
    return '<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#0f172a;font-family:Arial,Helvetica,sans-serif;">
<div style="max-width:600px;margin:0 auto;padding:40px 20px;">
<div style="background:#1e293b;border-radius:24px;overflow:hidden;border:1px solid #334155;">
<div style="background:linear-gradient(135deg,#10b981,#059669);padding:40px 30px;text-align:center;">
<div style="font-size:50px;margin-bottom:15px;">🛒</div>
<h1 style="margin:0;color:#fff;font-size:24px;font-weight:700;">Yeni Sipariş!</h1>
<p style="margin:15px 0 0;color:rgba(255,255,255,0.8);font-size:15px;">#' . htmlspecialchars($order['order_number']) . '</p>
</div>
<div style="padding:35px 30px;">
<table style="width:100%;margin-bottom:25px;"><tr>
<td style="width:50%;padding:10px;"><div style="background:#0f172a;border-radius:12px;padding:20px;text-align:center;border:1px solid #334155;"><span style="font-size:24px;font-weight:800;color:#10b981;display:block;">₺' . number_format($order['amount'], 2, ',', '.') . '</span><span style="font-size:12px;color:#64748b;">Tutar</span></div></td>
<td style="width:50%;padding:10px;"><div style="background:' . $typeColor . '20;border-radius:12px;padding:20px;text-align:center;border:1px solid ' . $typeColor . '40;"><span style="font-size:24px;display:block;">' . $typeIcon . '</span><span style="font-size:12px;color:' . $typeColor . ';font-weight:600;">' . $orderType . '</span></div></td>
</tr></table>
<div style="background:#0f172a;border-radius:16px;padding:25px;margin-bottom:25px;border:1px solid #334155;">
<h3 style="color:#fff;font-size:14px;margin:0 0 15px;text-transform:uppercase;letter-spacing:1px;"><span style="color:#6366f1;">●</span> Sipariş Bilgileri</h3>
<table style="width:100%;border-collapse:collapse;">
<tr><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Müşteri</td><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;">' . htmlspecialchars($order['customer_name']) . '</td></tr>
<tr><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">E-posta</td><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#60a5fa;font-size:14px;text-align:right;">' . htmlspecialchars($order['customer_email']) . '</td></tr>
<tr><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Telefon</td><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;">' . htmlspecialchars($order['customer_phone'] ?: '-') . '</td></tr>
<tr><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Paket</td><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;">' . htmlspecialchars($package['name']) . '</td></tr>
<tr><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Hedef</td><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#60a5fa;font-size:14px;text-align:right;word-break:break-all;">' . htmlspecialchars($order['social_media_link']) . '</td></tr>
<tr><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#94a3b8;font-size:14px;">Ödeme</td><td style="padding:10px 0;border-bottom:1px solid #1e293b;color:#fff;font-size:14px;text-align:right;">' . htmlspecialchars($order['payment_method']) . '</td></tr>
<tr><td style="padding:10px 0;color:#94a3b8;font-size:14px;">Tarih</td><td style="padding:10px 0;color:#fff;font-size:14px;text-align:right;">' . date('d.m.Y H:i', strtotime($order['created_at'])) . '</td></tr>
</table>
</div>
' . ($order['customer_note'] ? '<div style="background:#0f172a;border-radius:12px;padding:20px;margin-bottom:25px;border:1px solid #334155;"><h4 style="color:#f59e0b;font-size:13px;margin:0 0 10px;">💬 Müşteri Notu</h4><p style="color:#e2e8f0;font-size:14px;margin:0;line-height:1.6;">' . htmlspecialchars($order['customer_note']) . '</p></div>' : '') . '
<div style="text-align:center;">
<a href="' . $siteUrl . '/admin/siparis-detay.php?id=' . $order['id'] . '" style="display:inline-block;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;text-decoration:none;padding:16px 40px;border-radius:12px;font-weight:600;font-size:15px;">Siparişi Görüntüle</a>
</div>
</div>
<div style="background:#0f172a;padding:25px 30px;text-align:center;border-top:1px solid #1e293b;">
<p style="color:#64748b;font-size:13px;margin:0;">' . htmlspecialchars($siteName) . ' Admin Paneli</p>
</div>
</div>
</div>
</body>
</html>';
}

// ==================== CRON BAŞLAT ====================

cronLog("================================================================================");
cronLog("CRON JOB BAŞLADI - v1.1.0");
cronLog("================================================================================");
cronLog("Base Dir: " . $baseDir);
cronLog("Log File: " . $logFile);

$siteName = $settings->get('site_name', 'SMM Panel');
$siteUrl = $settings->get('site_url', SITE_URL);

// Admin e-postasını al
try {
    $adminEmail = $db->query("SELECT email FROM users WHERE role = 'admin' AND status = 'active' ORDER BY id ASC LIMIT 1")->fetchColumn();
    cronLog("Admin e-posta: " . ($adminEmail ?: 'Bulunamadı'));
} catch (PDOException $e) {
    $adminEmail = null;
    cronError("Admin e-postası alınamadı: " . $e->getMessage());
}

// SMTP durumu
$smtpEnabled = getSmtpSetting($db, 'smtp_enabled', '0') === '1';
cronLog("SMTP durumu: " . ($smtpEnabled ? 'Aktif' : 'Pasif'));

// cron_logs tablosu var mı kontrol et
try {
    $db->query("SELECT 1 FROM cron_logs LIMIT 1");
    cronLog("cron_logs tablosu: OK");
} catch (PDOException $e) {
    cronError("cron_logs tablosu bulunamadı! Lütfen SQL'i çalıştırın.");
    die("HATA: cron_logs tablosu bulunamadı!");
}

// ==================== GÖREV 1: YENİ SİPARİŞLER ====================

cronLog("--------------------------------------------------------------------------------");
cronLog("GÖREV 1: Yeni siparişler kontrol ediliyor");
cronLog("--------------------------------------------------------------------------------");

try {
    // Son 24 saat içinde oluşturulan siparişleri kontrol et
    $newOrders = $db->query("
        SELECT o.*, p.name as package_name, p.api_provider_id, p.api_service_id
        FROM orders o
        JOIN packages p ON o.package_id = p.id
        WHERE o.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        ORDER BY o.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $logStats['new_orders_checked'] = count($newOrders);
    cronLog("Son 24 saatteki sipariş sayısı: " . count($newOrders));
    
    if ($adminEmail && $smtpEnabled) {
        foreach ($newOrders as $order) {
            // Bu sipariş için admin bildirimi gönderilmiş mi?
            if (hasCronLog($db, $order['id'], 'admin_new_order')) {
                continue; // Zaten gönderilmiş, atla
            }
            
            $package = [
                'name' => $order['package_name'],
                'api_provider_id' => $order['api_provider_id'],
                'api_service_id' => $order['api_service_id']
            ];
            
            $isApi = !empty($package['api_provider_id']);
            $orderType = $isApi ? 'API' : 'Manuel';
            
            cronLog("İşleniyor: #{$order['order_number']} ({$orderType}) - {$order['customer_email']}");
            
            $subject = '🛒 Yeni Sipariş: #' . $order['order_number'] . ' - ' . $siteName;
            $body = getAdminNewOrderEmailTemplate($siteName, $siteUrl, $order, $package);
            
            $result = sendCronMail($db, $settings, $adminEmail, 'Admin', $subject, $body);
            
            if ($result['success']) {
                addCronLog($db, $order['id'], 'admin_new_order', 'new', $adminEmail, true);
                $logStats['admin_mails_sent']++;
                cronSuccess("Admin bildirimi gönderildi: #{$order['order_number']}");
            } else {
                addCronLog($db, $order['id'], 'admin_new_order', 'new', $adminEmail, false, $result['error']);
                cronError("Admin bildirimi gönderilemedi: #{$order['order_number']} - {$result['error']}");
            }
            
            usleep(200000);
        }
    }
    
} catch (PDOException $e) {
    cronError("Görev 1 hatası: " . $e->getMessage());
}

// ==================== GÖREV 2: DURUM DEĞİŞİKLİKLERİ ====================

cronLog("--------------------------------------------------------------------------------");
cronLog("GÖREV 2: Durum değişiklikleri kontrol ediliyor");
cronLog("--------------------------------------------------------------------------------");

try {
    // Tüm siparişleri kontrol et
    $allOrders = $db->query("
        SELECT o.*, p.name as package_name
        FROM orders o
        JOIN packages p ON o.package_id = p.id
        WHERE o.status != 'pending'
        ORDER BY o.updated_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $logStats['status_changes_checked'] = count($allOrders);
    cronLog("Kontrol edilecek sipariş sayısı: " . count($allOrders));
    
    if ($smtpEnabled) {
        foreach ($allOrders as $order) {
            // Bu sipariş için bu durum bildirimi gönderilmiş mi?
            if (hasCronLog($db, $order['id'], 'customer_status', $order['status'])) {
                continue; // Bu durum için zaten gönderilmiş, atla
            }
            
            $package = ['name' => $order['package_name']];
            
            cronLog("İşleniyor: #{$order['order_number']} -> {$order['status']} - {$order['customer_email']}");
            
            $subject = '📦 Sipariş Durumu Güncellendi: #' . $order['order_number'] . ' - ' . $siteName;
            $body = getCustomerStatusEmailTemplate($siteName, $siteUrl, $order, $package, $order['status']);
            
            $result = sendCronMail($db, $settings, $order['customer_email'], $order['customer_name'], $subject, $body);
            
            if ($result['success']) {
                addCronLog($db, $order['id'], 'customer_status', $order['status'], $order['customer_email'], true);
                $logStats['customer_mails_sent']++;
                cronSuccess("Müşteri bildirimi gönderildi: #{$order['order_number']} -> {$order['status']}");
            } else {
                addCronLog($db, $order['id'], 'customer_status', $order['status'], $order['customer_email'], false, $result['error']);
                cronError("Müşteri bildirimi gönderilemedi: #{$order['order_number']} - {$result['error']}");
            }
            
            usleep(200000);
        }
    }
    
} catch (PDOException $e) {
    cronError("Görev 2 hatası: " . $e->getMessage());
}

// ==================== GÖREV 3: API SİPARİŞLERİ ====================

cronLog("--------------------------------------------------------------------------------");
cronLog("GÖREV 3: API siparişleri sorgulanıyor");
cronLog("--------------------------------------------------------------------------------");

try {
    $apiOrders = $db->query("
        SELECT o.*, p.api_provider_id, p.api_service_id, ap.api_url, ap.api_key, ap.name as provider_name
        FROM orders o
        JOIN packages p ON o.package_id = p.id
        JOIN api_providers ap ON p.api_provider_id = ap.id
        WHERE o.api_order_id IS NOT NULL
        AND o.api_order_id != ''
        AND o.status IN ('processing', 'paid')
        AND (o.api_status IS NULL OR o.api_status NOT IN ('Completed', 'Canceled', 'Refunded', 'Partial'))
        ORDER BY o.created_at ASC
        LIMIT 50
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $logStats['api_orders_checked'] = count($apiOrders);
    cronLog("Sorgulanacak API sipariş sayısı: " . count($apiOrders));
    
    foreach ($apiOrders as $order) {
        try {
            cronLog("Sorgulanıyor: #{$order['order_number']} (API: {$order['api_order_id']}) - {$order['provider_name']}");
            
            $postData = [
                'key' => $order['api_key'],
                'action' => 'status',
                'order' => $order['api_order_id']
            ];
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $order['api_url'],
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => http_build_query($postData),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlError = curl_error($ch);
            curl_close($ch);
            
            if ($curlError) {
                cronError("CURL hatası: #{$order['order_number']} - {$curlError}");
                continue;
            }
            
            if ($httpCode === 200 && $response) {
                $result = json_decode($response, true);
                
                if (isset($result['status'])) {
                    $apiStatus = $result['status'];
                    $remains = isset($result['remains']) ? $result['remains'] : null;
                    $startCount = isset($result['start_count']) ? $result['start_count'] : null;
                    $charge = isset($result['charge']) ? $result['charge'] : null;
                    
                    $oldApiStatus = $order['api_status'];
                    
                    $updates = ["api_status = ?", "updated_at = NOW()"];
                    $params = [$apiStatus];
                    
                    if ($remains !== null) {
                        $updates[] = "api_remains = ?";
                        $params[] = $remains;
                    }
                    if ($startCount !== null) {
                        $updates[] = "api_start_count = ?";
                        $params[] = $startCount;
                    }
                    if ($charge !== null) {
                        $updates[] = "api_charge = ?";
                        $params[] = $charge;
                    }
                    
                    $newOrderStatus = null;
                    if (in_array($apiStatus, ['Completed', 'Partial'])) {
                        $newOrderStatus = 'completed';
                        $updates[] = "status = ?";
                        $updates[] = "completed_at = NOW()";
                        $params[] = 'completed';
                    } elseif ($apiStatus === 'Canceled') {
                        $newOrderStatus = 'cancelled';
                        $updates[] = "status = ?";
                        $params[] = 'cancelled';
                    } elseif ($apiStatus === 'Refunded') {
                        $newOrderStatus = 'refunded';
                        $updates[] = "status = ?";
                        $params[] = 'refunded';
                    } elseif (in_array($apiStatus, ['In progress', 'Processing', 'Pending'])) {
                        if ($order['status'] !== 'processing') {
                            $newOrderStatus = 'processing';
                            $updates[] = "status = ?";
                            $params[] = 'processing';
                        }
                    }
                    
                    $params[] = $order['id'];
                    $sql = "UPDATE orders SET " . implode(', ', $updates) . " WHERE id = ?";
                    $db->prepare($sql)->execute($params);
                    
                    $logStats['api_orders_updated']++;
                    
                    $statusChange = $newOrderStatus ? " | Durum: {$order['status']} -> {$newOrderStatus}" : "";
                    cronSuccess("API güncellendi: #{$order['order_number']} | API: {$oldApiStatus} -> {$apiStatus}{$statusChange}");
                    
                } elseif (isset($result['error'])) {
                    cronError("API hatası: #{$order['order_number']} - {$result['error']}");
                }
            } else {
                cronError("API isteği başarısız: #{$order['order_number']} - HTTP {$httpCode}");
            }
            
        } catch (Exception $e) {
            cronError("API sorgu hatası: #{$order['order_number']} - " . $e->getMessage());
        }
        
        usleep(300000);
    }
    
} catch (PDOException $e) {
    cronError("Görev 3 hatası: " . $e->getMessage());
}

// ==================== ESKİ LOGLARI TEMİZLE ====================

try {
    // 30 günden eski cron loglarını sil
    $db->query("DELETE FROM cron_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)");
} catch (PDOException $e) {
    // Hata olsa bile devam et
}

// ==================== ÖZET ====================

$logStats['ended_at'] = date('Y-m-d H:i:s');
$duration = strtotime($logStats['ended_at']) - strtotime($logStats['started_at']);

cronLog("================================================================================");
cronLog("CRON JOB TAMAMLANDI");
cronLog("================================================================================");
cronLog("ÖZET:");
cronLog("  Başlangıç: {$logStats['started_at']}");
cronLog("  Bitiş: {$logStats['ended_at']}");
cronLog("  Süre: {$duration} saniye");
cronLog("  Yeni sipariş kontrol: {$logStats['new_orders_checked']}");
cronLog("  Admin mail gönderildi: {$logStats['admin_mails_sent']}");
cronLog("  Durum değişikliği kontrol: {$logStats['status_changes_checked']}");
cronLog("  Müşteri mail gönderildi: {$logStats['customer_mails_sent']}");
cronLog("  API sipariş kontrol: {$logStats['api_orders_checked']}");
cronLog("  API sipariş güncellendi: {$logStats['api_orders_updated']}");
cronLog("  Hata sayısı: " . count($logStats['errors']));
cronLog("================================================================================");

echo "\n\nCRON TAMAMLANDI - Log dosyası: " . $logFile;