<?php
// Test Didar API search and phone matching

$apiKey = 'o2wi5oksfn0ha4zppr0xz5637f92mzee';
$phoneFromDb = '9025028611'; // از دیتابیس (بدون صفر)
$phoneWithZero = '09025028611'; // با صفر

function callDidarTest($endpoint, $method = 'POST', $data = [], $apiKey = null) {
    $url = "https://app.didar.me/api" . $endpoint . "?apikey=" . urlencode($apiKey);
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    if (!empty($data)) {
        $postData = json_encode($data, JSON_UNESCAPED_UNICODE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['error' => 'CURL Error: ' . $error, 'http_code' => $httpCode];
    }
    
    $json = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['error' => 'JSON Decode Error: ' . json_last_error_msg(), 'http_code' => $httpCode, 'raw_response' => substr($response, 0, 500)];
    }
    
    if ($httpCode !== 200) {
        $errorMsg = 'HTTP ' . $httpCode;
        if (isset($json['Message'])) {
            $errorMsg .= ' - ' . $json['Message'];
        }
        return ['error' => $errorMsg, 'http_code' => $httpCode, 'response' => $json];
    }
    
    return $json;
}

echo "=== TEST: Search with phone from DB (9025028611) ===\n";
$phoneCleaned = preg_replace('/\D/', '', $phoneFromDb);
echo "Phone from DB: $phoneFromDb\n";
echo "Phone cleaned: $phoneCleaned\n\n";

$searchCriteria = [
    'ContactType' => 0,
    'IsDeleted' => 0,
    'IsPinned' => -1,
    'IsVIP' => -1,
    'LeadType' => -1,
    'Pin' => -1,
    'SortOrder' => 1,
    'Keywords' => $phoneCleaned,
    'SearchFromTime' => '1930-01-01T00:00:00.000Z',
    'SearchToTime' => '9999-12-01T00:00:00.000Z',
    'CustomFields' => [],
    'FilterId' => null
];

$searchRes = callDidarTest('/contact/PersonSearch', 'POST', [
    'Criteria' => $searchCriteria,
    'From' => 0,
    'Limit' => 50
], $apiKey);

if (isset($searchRes['error'])) {
    echo "ERROR: " . $searchRes['error'] . "\n";
    exit(1);
}

echo "Search successful!\n";
echo "TotalCount: " . ($searchRes['Response']['TotalCount'] ?? 'N/A') . "\n";
echo "List Count: " . (isset($searchRes['Response']['List']) ? count($searchRes['Response']['List']) : 0) . "\n\n";

if (isset($searchRes['Response']['List']) && is_array($searchRes['Response']['List'])) {
    echo "=== All found persons ===\n";
    foreach ($searchRes['Response']['List'] as $index => $foundPerson) {
        $foundPhone = $foundPerson['MobilePhone'] ?? '';
        $foundPhoneCleaned = preg_replace('/\D/', '', $foundPhone);
        
        echo "\nPerson #" . ($index + 1) . ":\n";
        echo "  Id: " . ($foundPerson['Id'] ?? 'N/A') . "\n";
        echo "  DisplayName: " . ($foundPerson['DisplayName'] ?? 'N/A') . "\n";
        echo "  MobilePhone (original): " . $foundPhone . "\n";
        echo "  MobilePhone (cleaned): " . $foundPhoneCleaned . "\n";
        echo "  Match with DB phone ($phoneCleaned): " . ($foundPhoneCleaned === $phoneCleaned ? 'YES' : 'NO') . "\n";
        
        if ($foundPhoneCleaned === $phoneCleaned) {
            echo "  *** MATCH FOUND! ***\n";
            echo "  Real ContactId: " . ($foundPerson['Id'] ?? 'N/A') . "\n";
        }
    }
    
    // Now test the matching logic from the code
    echo "\n=== Testing matching logic ===\n";
    $realContactId = null;
    foreach ($searchRes['Response']['List'] as $foundPerson) {
        $foundPhone = preg_replace('/\D/', '', $foundPerson['MobilePhone'] ?? '');
        echo "Comparing: '$foundPhone' === '$phoneCleaned' ? " . ($foundPhone === $phoneCleaned ? 'YES' : 'NO') . "\n";
        if ($foundPhone === $phoneCleaned) {
            $realContactId = $foundPerson['Id'] ?? null;
            echo "MATCH! Real ContactId: $realContactId\n";
            break;
        }
    }
    
    if (empty($realContactId)) {
        echo "\nERROR: No match found! This is the problem.\n";
        echo "Expected phone (cleaned): $phoneCleaned\n";
        echo "Found phones in results:\n";
        foreach ($searchRes['Response']['List'] as $foundPerson) {
            $foundPhone = preg_replace('/\D/', '', $foundPerson['MobilePhone'] ?? '');
            echo "  - $foundPhone\n";
        }
    } else {
        echo "\nSUCCESS: Real ContactId found: $realContactId\n";
    }
} else {
    echo "No persons found in search results\n";
}
?>

