<?php
/**
 * اسکریپت دیباگ برای بررسی session و query
 */

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

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

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

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

// فقط برای کاربر لاگین شده
if (!isset($_SESSION['user_id'])) {
    die(json_encode(['error' => 'Not logged in', 'session' => $_SESSION], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

$debug = [
    'session' => [
        'user_id' => $_SESSION['user_id'] ?? null,
        'role' => $_SESSION['role'] ?? null,
        'didar_id' => $_SESSION['didar_id'] ?? null,
        'name' => $_SESSION['name'] ?? null,
        'email' => $_SESSION['email'] ?? null,
    ],
    'user_in_db' => null,
    'query_simulation' => [],
    'leads_count' => 0,
    'leads_sample' => []
];

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

// شبیه‌سازی Query
$isAdmin = $_SESSION['role'] === 'admin';
$didarId = $_SESSION['didar_id'] ?? '';

$debug['query_simulation'] = [
    'isAdmin' => $isAdmin,
    'didarId' => $didarId,
    'didarId_empty' => empty($didarId),
    'didarId_null' => is_null($didarId),
    'didarId_length' => strlen($didarId),
    'condition_check' => !$isAdmin && !empty($didarId),
    'didarId_from_db' => $user['didar_user_id'] ?? null,
    'match' => ($didarId === ($user['didar_user_id'] ?? null))
];

// Query برای کاربر غیرادمین
if (!$isAdmin && !empty($didarId)) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM persons WHERE didar_contact_id IS NOT NULL AND owner_didar_id = ?");
    $stmt->execute([$didarId]);
    $debug['leads_count'] = $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([$didarId]);
    $debug['leads_sample'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
} elseif ($isAdmin) {
    $stmt = $pdo->query("SELECT COUNT(*) FROM persons WHERE didar_contact_id IS NOT NULL");
    $debug['leads_count'] = $stmt->fetchColumn();
} else {
    $debug['leads_count'] = 0;
    $debug['error'] = 'didarId is empty or user is not admin';
}

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

// شبیه‌سازی دقیق query get_leads
$debug['exact_query_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);
    $debug['exact_query_simulation'] = [
        'sql' => $sql,
        'params' => $params,
        'count' => count($stmt->fetchAll(PDO::FETCH_ASSOC))
    ];
    
    // دوباره اجرا برای گرفتن داده
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $debug['exact_query_results'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

echo json_encode($debug, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
