<?php
/**
 * Fix Progress Script
 * تنظیم دستی progress برای ادامه 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");
}

try {
    $pdo = new PDO('sqlite:' . $DB_FILE);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== تنظیم Progress ===\n\n";
    
    // Get current counts
    $usersCount = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $personsCount = $pdo->query("SELECT COUNT(*) FROM persons")->fetchColumn();
    $dealsCount = $pdo->query("SELECT COUNT(*) FROM deals")->fetchColumn();
    
    echo "وضعیت فعلی:\n";
    echo "  - Users: $usersCount\n";
    echo "  - Persons: $personsCount\n";
    echo "  - Deals: $dealsCount\n\n";
    
    // Determine step and from
    $step = 'users';
    $from = 0;
    $limit = 250; // For deals
    
    if ($usersCount > 0) {
        $step = 'persons';
        $from = 0;
        
        if ($personsCount > 0) {
            $step = 'deals';
            // Calculate from based on synced count
            $from = intval(floor($dealsCount / $limit) * $limit);
        }
    }
    
    echo "محاسبه شده:\n";
    echo "  - Step: $step\n";
    echo "  - From: $from\n";
    echo "  - Limit: $limit\n\n";
    
    // Save progress
    $progressData = [
        'step' => $step,
        'from' => $from,
        'total_count' => 18327, // Expected total deals
        'last_sync' => date('Y-m-d H:i:s'),
        'current_from' => $from,
        'current_limit' => $limit
    ];
    
    $pdo->prepare("INSERT OR REPLACE INTO config (key, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)")
        ->execute([
            'setup_progress',
            json_encode($progressData, JSON_UNESCAPED_UNICODE)
        ]);
    
    echo "✅ Progress ذخیره شد:\n";
    echo json_encode($progressData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";
    
    echo "حالا می‌توانید دکمه 'ادامه همگام‌سازی' را در صفحه setup بزنید.\n";
    
} catch (PDOException $e) {
    die("خطا: " . $e->getMessage() . "\n");
}
?>

