<?php
/**
 * اسکریپت برای بررسی و اصلاح عدم تطابق didar_user_id با owner_didar_id
 */

session_start();
date_default_timezone_set('Asia/Tehran');

define('DB_FILE', __DIR__ . '/crm_database.db');

if (!file_exists(DB_FILE)) {
    die(json_encode(['error' => 'Database file not found: ' . DB_FILE], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

$pdo = new PDO('sqlite:' . DB_FILE);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

header('Content-Type: application/json; charset=utf-8');

$result = [
    'status' => 'checking',
    'user_info' => null,
    'leads_analysis' => [],
    'mismatch_found' => false,
    'fix_applied' => false
];

// 1. بررسی کاربر ظهوری
$stmt = $pdo->prepare("SELECT id, didar_user_id, display_name, role FROM users WHERE display_name LIKE ?");
$stmt->execute(['%ظهوری%']);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    $result['error'] = 'User not found';
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

$result['user_info'] = $user;
$userDidarId = $user['didar_user_id'] ?? '';

// 2. بررسی owner_didar_id لیدها
$stmt = $pdo->query("
    SELECT DISTINCT owner_didar_id, COUNT(*) as cnt 
    FROM persons 
    WHERE owner_didar_id IS NOT NULL
    GROUP BY owner_didar_id
    ORDER BY cnt DESC
");
$ownerIds = $stmt->fetchAll(PDO::FETCH_ASSOC);

$result['leads_analysis']['all_owner_ids'] = $ownerIds;

if (empty($ownerIds)) {
    $result['error'] = 'No leads found';
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// 3. بررسی تطابق
$mostCommonOwner = $ownerIds[0]['owner_didar_id'];
$mostCommonCount = $ownerIds[0]['cnt'];

$result['leads_analysis']['most_common_owner'] = $mostCommonOwner;
$result['leads_analysis']['most_common_count'] = $mostCommonCount;

// تعداد لیدهای کاربر با didar_user_id فعلی
$stmt = $pdo->prepare("SELECT COUNT(*) FROM persons WHERE owner_didar_id = ?");
$stmt->execute([$userDidarId]);
$countWithCurrentId = (int)$stmt->fetchColumn();

// تعداد لیدهای کاربر با owner_didar_id صحیح
$stmt = $pdo->prepare("SELECT COUNT(*) FROM persons WHERE owner_didar_id = ?");
$stmt->execute([$mostCommonOwner]);
$countWithCorrectId = (int)$stmt->fetchColumn();

$result['leads_analysis']['count_with_current_didar_id'] = $countWithCurrentId;
$result['leads_analysis']['count_with_correct_owner_id'] = $countWithCorrectId;

// بررسی عدم تطابق
if ($userDidarId !== $mostCommonOwner) {
    $result['mismatch_found'] = true;
    $result['status'] = 'mismatch_detected';
    $result['message'] = "didar_user_id کاربر ({$userDidarId}) با owner_didar_id لیدها ({$mostCommonOwner}) تطابق ندارد";
    
    // اعمال اصلاح
    if (isset($_GET['fix']) && $_GET['fix'] === 'yes') {
        $stmt = $pdo->prepare("UPDATE users SET didar_user_id = ? WHERE id = ?");
        $stmt->execute([$mostCommonOwner, $user['id']]);
        
        $result['fix_applied'] = true;
        $result['status'] = 'fixed';
        $result['message'] = "didar_user_id به {$mostCommonOwner} تغییر یافت";
        $result['new_didar_user_id'] = $mostCommonOwner;
        $result['leads_visible_count'] = $countWithCorrectId;
    } else {
        $result['fix_instruction'] = "برای اعمال اصلاح، به این آدرس بروید: ?fix=yes";
    }
} else {
    $result['status'] = 'ok';
    $result['message'] = "تطابق کامل است";
    $result['leads_visible_count'] = $countWithCorrectId;
}

echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

