<?php
/**
 * اسکریپت دیباگ کامل برای بررسی مشکل نمایش لیدها
 */

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');

$debug = [
    'session_exists' => isset($_SESSION['user_id']),
    'session_data' => [
        'user_id' => $_SESSION['user_id'] ?? 'NOT SET',
        'role' => $_SESSION['role'] ?? 'NOT SET',
        'didar_id' => $_SESSION['didar_id'] ?? 'NOT SET',
        'name' => $_SESSION['name'] ?? 'NOT SET',
    ],
    'user_from_db' => null,
    'leads_analysis' => [],
    'query_tests' => []
];

if (!isset($_SESSION['user_id'])) {
    $debug['error'] = 'User not logged in';
    echo json_encode($debug, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// 1. بررسی کاربر در دیتابیس
$stmt = $pdo->prepare("SELECT id, didar_user_id, display_name, role, email, is_active FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$debug['user_from_db'] = $user;

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

// 2. بررسی تطابق didar_id
$sessionDidarId = $_SESSION['didar_id'] ?? '';
$dbDidarId = $user['didar_user_id'] ?? '';

$debug['didar_id_comparison'] = [
    'session_didar_id' => $sessionDidarId,
    'db_didar_id' => $dbDidarId,
    'session_empty' => empty($sessionDidarId),
    'db_empty' => empty($dbDidarId),
    'match' => ($sessionDidarId === $dbDidarId),
    'session_length' => strlen($sessionDidarId),
    'db_length' => strlen($dbDidarId)
];

// 3. بررسی لیدها
$isAdmin = $_SESSION['role'] === 'admin';
$didarId = $_SESSION['didar_id'] ?? '';

$debug['query_tests']['isAdmin'] = $isAdmin;
$debug['query_tests']['didarId'] = $didarId;
$debug['query_tests']['condition'] = !$isAdmin && !empty($didarId);

// Query 1: تعداد کل لیدها
$stmt = $pdo->query("SELECT COUNT(*) FROM persons WHERE didar_contact_id IS NOT NULL");
$debug['leads_analysis']['total_leads'] = (int)$stmt->fetchColumn();

// Query 2: لیدهای با owner_didar_id مشخص
if (!empty($dbDidarId)) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM persons WHERE didar_contact_id IS NOT NULL AND owner_didar_id = ?");
    $stmt->execute([$dbDidarId]);
    $debug['leads_analysis']['leads_with_db_didar_id'] = (int)$stmt->fetchColumn();
    
    // نمونه لیدها
    $stmt = $pdo->prepare("SELECT didar_contact_id, first_name, last_name, owner_didar_id FROM persons WHERE owner_didar_id = ? LIMIT 5");
    $stmt->execute([$dbDidarId]);
    $debug['leads_analysis']['sample_leads'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

if (!empty($sessionDidarId)) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM persons WHERE didar_contact_id IS NOT NULL AND owner_didar_id = ?");
    $stmt->execute([$sessionDidarId]);
    $debug['leads_analysis']['leads_with_session_didar_id'] = (int)$stmt->fetchColumn();
}

// Query 3: شبیه‌سازی دقیق get_dashboard_stats
$debug['query_tests']['dashboard_stats_simulation'] = [];

if ($isAdmin) {
    $sql = "SELECT COUNT(*) FROM persons WHERE didar_contact_id IS NOT NULL";
    $stmt = $pdo->query($sql);
    $debug['query_tests']['dashboard_stats_simulation']['total_leads'] = (int)$stmt->fetchColumn();
} else {
    if (!empty($didarId)) {
        $sql = "SELECT COUNT(*) FROM persons WHERE didar_contact_id IS NOT NULL AND owner_didar_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$didarId]);
        $debug['query_tests']['dashboard_stats_simulation']['total_leads'] = (int)$stmt->fetchColumn();
    } else {
        $debug['query_tests']['dashboard_stats_simulation']['total_leads'] = 0;
        $debug['query_tests']['dashboard_stats_simulation']['error'] = 'didarId is empty';
    }
}

// Query 4: شبیه‌سازی دقیق get_leads
$debug['query_tests']['get_leads_simulation'] = [];

if (!$isAdmin && !empty($didarId)) {
    $where = ["p.didar_contact_id IS NOT NULL"];
    $where[] = "p.owner_didar_id = ?";
    $params = [$didarId];
    $whereClause = implode(' AND ', $where);
    
    $sql = "SELECT p.*, 
            (SELECT vs2.stage_name FROM virtual_stages vs2 
             WHERE vs2.contact_didar_id = p.didar_contact_id 
             ORDER BY vs2.entered_at DESC LIMIT 1) as virtual_stage,
            u.display_name as owner_name
            FROM persons p
            LEFT JOIN users u ON p.owner_didar_id = u.didar_user_id
            WHERE $whereClause
            ORDER BY p.register_time DESC, p.created_at DESC
            LIMIT 10";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $debug['query_tests']['get_leads_simulation'] = [
        'sql' => $sql,
        'params' => $params,
        'count' => count($results),
        'results' => $results
    ];
} else {
    $debug['query_tests']['get_leads_simulation'] = [
        'error' => 'Condition not met',
        'isAdmin' => $isAdmin,
        'didarId' => $didarId,
        'didarId_empty' => empty($didarId)
    ];
}

// 5. بررسی همه owner_didar_id های موجود
$stmt = $pdo->query("SELECT DISTINCT owner_didar_id, COUNT(*) as cnt FROM persons GROUP BY owner_didar_id");
$debug['leads_analysis']['all_owner_ids'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 6. بررسی همه didar_user_id های موجود در users
$stmt = $pdo->query("SELECT id, didar_user_id, display_name, role FROM users WHERE is_active = 1");
$debug['leads_analysis']['all_users'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($debug, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

