<?php
/**
 * Database Status Checker
 * بررسی وضعیت دیتابیس و پیشرفت sync
 */

// Try to find the database file
$dbFiles = [
    __DIR__ . '/crm_database.db',
    __DIR__ . '/crm_database (2).db',
    __DIR__ . '/crm_database (1).db'
];

$DB_FILE = null;
foreach ($dbFiles as $file) {
    if (file_exists($file)) {
        $DB_FILE = $file;
        break;
    }
}

if (!$DB_FILE) {
    die("دیتابیس یافت نشد. فایل‌های جستجو شده:\n" . implode("\n", $dbFiles) . "\n");
}

define('DB_FILE', $DB_FILE);

try {
    $pdo = new PDO('sqlite:' . DB_FILE);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== وضعیت دیتابیس ===\n\n";
    
    // تعداد Users
    $usersCount = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    echo "✅ Users: $usersCount\n";
    
    // تعداد Persons
    $personsCount = $pdo->query("SELECT COUNT(*) FROM persons")->fetchColumn();
    echo "✅ Persons: $personsCount\n";
    
    // تعداد Deals
    $dealsCount = $pdo->query("SELECT COUNT(*) FROM deals")->fetchColumn();
    echo "✅ Deals: $dealsCount\n";
    
    // تعداد Activities
    $activitiesCount = $pdo->query("SELECT COUNT(*) FROM activities")->fetchColumn();
    echo "✅ Activities: $activitiesCount\n\n";
    
    // درصد پیشرفت
    $expectedDeals = 18327;
    $progress = $expectedDeals > 0 ? round(($dealsCount / $expectedDeals) * 100, 2) : 0;
    echo "📊 پیشرفت Deals: $progress% ($dealsCount از $expectedDeals)\n";
    
    // تعداد صفحات sync شده
    $limit = 250; // Limit جدید
    $pagesSynced = ceil($dealsCount / $limit);
    $totalPages = ceil($expectedDeals / $limit);
    echo "📄 صفحات sync شده: $pagesSynced از $totalPages\n\n";
    
    // آخرین sync time
    $lastDealSync = $pdo->query("SELECT MAX(last_sync) FROM deals")->fetchColumn();
    $lastPersonSync = $pdo->query("SELECT MAX(last_sync) FROM persons")->fetchColumn();
    echo "🕐 آخرین sync Deals: " . ($lastDealSync ?: 'ندارد') . "\n";
    echo "🕐 آخرین sync Persons: " . ($lastPersonSync ?: 'ندارد') . "\n\n";
    
    // بررسی Progress در config
    $stmt = $pdo->query("SELECT value FROM config WHERE key = 'setup_progress'");
    $progressJson = $stmt->fetchColumn();
    if ($progressJson) {
        $progressData = json_decode($progressJson, true);
        echo "💾 Progress ذخیره شده:\n";
        echo "   - Step: " . ($progressData['step'] ?? 'unknown') . "\n";
        echo "   - From: " . ($progressData['from'] ?? 0) . "\n";
        echo "   - Total Count: " . ($progressData['total_count'] ?? 0) . "\n";
        echo "   - Last Sync: " . ($progressData['last_sync'] ?? 'unknown') . "\n\n";
    } else {
        echo "⚠️  Progress ذخیره نشده است\n\n";
    }
    
    // بررسی خطاها در sync_log
    $errorCount = $pdo->query("SELECT COUNT(*) FROM sync_log WHERE status = 'failed'")->fetchColumn();
    if ($errorCount > 0) {
        echo "❌ تعداد خطاها در sync_log: $errorCount\n";
        $recentErrors = $pdo->query("SELECT entity_type, error_message, synced_at FROM sync_log WHERE status = 'failed' ORDER BY synced_at DESC LIMIT 5")
            ->fetchAll(PDO::FETCH_ASSOC);
        echo "   آخرین خطاها:\n";
        foreach ($recentErrors as $error) {
            echo "   - {$error['entity_type']}: {$error['error_message']} ({$error['synced_at']})\n";
        }
    } else {
        echo "✅ هیچ خطایی در sync_log ثبت نشده\n";
    }
    
    echo "\n=== خلاصه ===\n";
    echo "وضعیت: " . ($progress >= 100 ? "✅ تکمیل شده" : "⏳ در حال انجام") . "\n";
    echo "باقی‌مانده: " . max(0, $expectedDeals - $dealsCount) . " deal\n";
    
} catch (PDOException $e) {
    die("خطا در اتصال به دیتابیس: " . $e->getMessage() . "\n");
}
?>

