<?php
// Test Didar API directly without requiring index.php

$apiKey = 'o2wi5oksfn0ha4zppr0xz5637f92mzee';
$phone = '9025028611'; // شماره از لاگ

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 1: Search by phone number ===\n";
echo "Phone: $phone\n\n";

// Test 1: Search by phone
$searchData = [
    'Criteria' => [
        'ContactType' => 0,
        'IsDeleted' => 0,
        'IsPinned' => -1,
        'IsVIP' => -1,
        'LeadType' => -1,
        'Pin' => -1,
        'SortOrder' => 1,
        'Keywords' => $phone,
        'SearchFromTime' => '1930-01-01T00:00:00.000Z',
        'SearchToTime' => '9999-12-01T00:00:00.000Z',
        'CustomFields' => [],
        'FilterId' => null
    ],
    'From' => 0,
    'Limit' => 10
];

$result = callDidarTest('/contact/PersonSearch', 'POST', $searchData, $apiKey);

echo "Response:\n";
if (isset($result['error'])) {
    echo "ERROR: " . $result['error'] . "\n";
    if (isset($result['response'])) {
        print_r($result['response']);
    }
} else {
    echo "Success!\n";
    if (isset($result['Response']['List']) && count($result['Response']['List']) > 0) {
        $person = $result['Response']['List'][0];
        $contactId = $person['Id'] ?? null;
        
        echo "\n=== Found Person Details ===\n";
        echo "Id (contactId): " . ($person['Id'] ?? 'N/A') . "\n";
        echo "Id Type: " . gettype($person['Id'] ?? null) . "\n";
        echo "DisplayName: " . ($person['DisplayName'] ?? 'N/A') . "\n";
        echo "MobilePhone: " . ($person['MobilePhone'] ?? 'N/A') . "\n";
        echo "Email: " . ($person['Email'] ?? 'N/A') . "\n";
        
        if ($contactId) {
            echo "\n=== ContactId Analysis ===\n";
            echo "ContactId: $contactId\n";
            echo "ContactId Type: " . gettype($contactId) . "\n";
            echo "Is GUID: " . (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $contactId) ? 'YES' : 'NO') . "\n";
            echo "Length: " . strlen($contactId) . "\n";
            
            // Test 2: Get deals with ContactIds (array with GUID)
            echo "\n=== TEST 2: Get deals with ContactIds (GUID) ===\n";
            $dealsData = [
                'Criteria' => [
                    'ContactIds' => [$contactId],
                    'Status' => -1
                ],
                'From' => 0,
                'Limit' => 10
            ];
            
            echo "Request JSON:\n";
            echo json_encode($dealsData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";
            
            $dealsResult = callDidarTest('/deal/search', 'POST', $dealsData, $apiKey);
            
            if (isset($dealsResult['error'])) {
                echo "ERROR: " . $dealsResult['error'] . "\n";
                if (isset($dealsResult['response'])) {
                    print_r($dealsResult['response']);
                }
            } else {
                echo "Success!\n";
                if (isset($dealsResult['Response']['List'])) {
                    echo "Deals Count: " . count($dealsResult['Response']['List']) . "\n";
                    if (count($dealsResult['Response']['List']) > 0) {
                        echo "\nFirst Deal:\n";
                        $firstDeal = $dealsResult['Response']['List'][0];
                        echo "Title: " . ($firstDeal['Title'] ?? 'N/A') . "\n";
                        echo "Code: " . ($firstDeal['Code'] ?? 'N/A') . "\n";
                        echo "Status: " . ($firstDeal['Status'] ?? 'N/A') . "\n";
                        echo "Price: " . ($firstDeal['Price'] ?? 'N/A') . "\n";
                    }
                } else {
                    echo "No deals in response\n";
                    echo "Response structure:\n";
                    print_r(array_keys($dealsResult));
                }
            }
            
            // Test 3: Get activities with ContactId (direct, not in Criteria)
            echo "\n=== TEST 3: Get activities with ContactId (direct) ===\n";
            $activitiesData = [
                'ContactId' => $contactId,
                'FromDate' => '1901-01-01T00:00:00.000Z',
                'ToDate' => '9999-12-01T00:00:00.000Z',
                'IsDone' => -1,
                'From' => 0,
                'Limit' => 10
            ];
            
            echo "Request JSON:\n";
            echo json_encode($activitiesData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";
            
            $activitiesResult = callDidarTest('/activity/search', 'POST', $activitiesData, $apiKey);
            
            if (isset($activitiesResult['error'])) {
                echo "ERROR: " . $activitiesResult['error'] . "\n";
                if (isset($activitiesResult['response'])) {
                    print_r($activitiesResult['response']);
                }
            } else {
                echo "Success!\n";
                if (isset($activitiesResult['Response']['List'])) {
                    echo "Activities Count: " . count($activitiesResult['Response']['List']) . "\n";
                    if (count($activitiesResult['Response']['List']) > 0) {
                        echo "\nFirst Activity:\n";
                        $firstAct = $activitiesResult['Response']['List'][0];
                        echo "Title: " . ($firstAct['Title'] ?? 'N/A') . "\n";
                        echo "ActivityTypeId: " . ($firstAct['ActivityTypeId'] ?? 'N/A') . "\n";
                        echo "IsDone: " . (isset($firstAct['IsDone']) ? ($firstAct['IsDone'] ? 'true' : 'false') : 'N/A') . "\n";
                        echo "RegisterDate: " . ($firstAct['RegisterDate'] ?? 'N/A') . "\n";
                        echo "DueDate: " . ($firstAct['DueDate'] ?? 'N/A') . "\n";
                        echo "DoneDate: " . ($firstAct['DoneDate'] ?? 'N/A') . "\n";
                    }
                } else {
                    echo "No activities in response\n";
                    echo "Response structure:\n";
                    print_r(array_keys($activitiesResult));
                }
            }
            
        } else {
            echo "\nERROR: No contactId found in search results!\n";
        }
    } else {
        echo "No persons found in search results\n";
        echo "TotalCount: " . ($result['Response']['TotalCount'] ?? 'N/A') . "\n";
    }
}
?>
