<?php
/**
 * Migration Script: Fix owner_didar_id mapping issues
 * 
 * این اسکریپت owner_didar_id های قدیمی را اصلاح می‌کند
 * تا با didar_user_id در جدول users match شوند
 */

$dbFile = __DIR__ . '/crm_database.db';

if (!file_exists($dbFile)) {
    die("دیتابیس یافت نشد: $dbFile\n");
}

try {
    $pdo = new PDO('sqlite:' . $dbFile);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== Fix Owner Mapping Issues ===\n\n";
    
    // 1. Get all users with their Id and UserId
    echo "1. دریافت لیست کاربران...\n";
    $users = $pdo->query("SELECT id, didar_user_id, display_name FROM users")->fetchAll(PDO::FETCH_ASSOC);
    echo "   ✅ " . count($users) . " کاربر یافت شد\n\n";
    
    // Create mapping: Id => UserId and UserId => UserId
    $idToUserId = [];
    $userIdToUserId = [];
    foreach ($users as $user) {
        $idToUserId[$user['didar_user_id']] = $user['didar_user_id'];
        $userIdToUserId[$user['didar_user_id']] = $user['didar_user_id'];
    }
    
    // 2. Find persons with owner_didar_id that doesn't match any user
    echo "2. بررسی persons با owner_didar_id نامطابق...\n";
    $stmt = $pdo->query("
        SELECT p.didar_contact_id, p.owner_didar_id, p.first_name, p.last_name
        FROM persons p
        WHERE p.owner_didar_id IS NOT NULL 
        AND p.owner_didar_id != ''
        AND NOT EXISTS (
            SELECT 1 FROM users u WHERE u.didar_user_id = p.owner_didar_id
        )
    ");
    $mismatchedPersons = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "   ⚠️  " . count($mismatchedPersons) . " person با owner_didar_id نامطابق یافت شد\n\n";
    
    // 3. Try to fix persons
    $fixedPersons = 0;
    $failedPersons = 0;
    foreach ($mismatchedPersons as $person) {
        $oldOwnerId = $person['owner_didar_id'];
        $found = false;
        
        // Try to find matching user by checking if oldOwnerId exists as Id in Didar response
        // Since we can't call API here, we'll try to find by checking if any user has similar ID
        // Or we can set to NULL and let sync fix it
        
        // For now, set to NULL and let next sync fix it
        try {
            $pdo->prepare("UPDATE persons SET owner_didar_id = NULL WHERE didar_contact_id = ?")
                ->execute([$person['didar_contact_id']]);
            $fixedPersons++;
            echo "   ✅ Person {$person['didar_contact_id']}: owner_didar_id از '{$oldOwnerId}' به NULL تغییر یافت (نیاز به sync)\n";
        } catch (Exception $e) {
            $failedPersons++;
            echo "   ❌ Person {$person['didar_contact_id']}: خطا - " . $e->getMessage() . "\n";
        }
    }
    
    // 4. Find deals with owner_didar_id that doesn't match any user
    echo "\n3. بررسی deals با owner_didar_id نامطابق...\n";
    $stmt = $pdo->query("
        SELECT d.didar_deal_id, d.owner_didar_id, d.title
        FROM deals d
        WHERE d.owner_didar_id IS NOT NULL 
        AND d.owner_didar_id != ''
        AND NOT EXISTS (
            SELECT 1 FROM users u WHERE u.didar_user_id = d.owner_didar_id
        )
    ");
    $mismatchedDeals = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "   ⚠️  " . count($mismatchedDeals) . " deal با owner_didar_id نامطابق یافت شد\n\n";
    
    // 5. Try to fix deals
    $fixedDeals = 0;
    $failedDeals = 0;
    foreach ($mismatchedDeals as $deal) {
        $oldOwnerId = $deal['owner_didar_id'];
        
        try {
            $pdo->prepare("UPDATE deals SET owner_didar_id = NULL WHERE didar_deal_id = ?")
                ->execute([$deal['didar_deal_id']]);
            $fixedDeals++;
            echo "   ✅ Deal {$deal['didar_deal_id']}: owner_didar_id از '{$oldOwnerId}' به NULL تغییر یافت (نیاز به sync)\n";
        } catch (Exception $e) {
            $failedDeals++;
            echo "   ❌ Deal {$deal['didar_deal_id']}: خطا - " . $e->getMessage() . "\n";
        }
    }
    
    // 6. Summary
    echo "\n=== خلاصه ===\n";
    echo "Persons:\n";
    echo "  - نامطابق: " . count($mismatchedPersons) . "\n";
    echo "  - اصلاح شده: $fixedPersons\n";
    echo "  - خطا: $failedPersons\n\n";
    
    echo "Deals:\n";
    echo "  - نامطابق: " . count($mismatchedDeals) . "\n";
    echo "  - اصلاح شده: $fixedDeals\n";
    echo "  - خطا: $failedDeals\n\n";
    
    echo "⚠️  توجه: owner_didar_id هایی که NULL شدند، در sync بعدی از Didar دوباره پر می‌شوند.\n";
    echo "✅ لطفاً بعد از اجرای این اسکریپت، یک sync کامل انجام دهید.\n";
    
} catch (Exception $e) {
    echo "❌ خطا: " . $e->getMessage() . "\n";
    exit(1);
}

