<?php
/**
 * Deep Analysis of Didar CRM Data Structure
 */

$apiKey = 'o2wi5oksfn0ha4zppr0xz5637f92mzee';
$baseUrl = 'https://app.didar.me/api';

function callDidarAPI($endpoint, $method = 'POST', $data = []) {
    global $apiKey, $baseUrl;
    
    $url = $baseUrl . $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, 30);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    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']);
    } else {
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        }
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return [
        'http_code' => $httpCode,
        'json' => json_decode($response, true)
    ];
}

$analysis = [];

// 1. Users Analysis
echo "Fetching Users...\n";
$usersRes = callDidarAPI('/User/List', 'POST');
if ($usersRes['http_code'] === 200 && isset($usersRes['json']['Response'])) {
    $users = $usersRes['json']['Response'];
    $analysis['users'] = [
        'total' => count($users),
        'sample' => $users[0] ?? null,
        'fields' => !empty($users) ? array_keys($users[0]) : []
    ];
}

// 2. Persons Analysis - Get multiple samples
echo "Fetching Persons...\n";
$personsRes = callDidarAPI('/contact/personsearch', 'POST', [
    'Criteria' => ['IsDeleted' => 0],
    'From' => 0,
    'Limit' => 50
]);
if ($personsRes['http_code'] === 200 && isset($personsRes['json']['Response'])) {
    $persons = $personsRes['json']['Response'];
    $personsList = $persons['List'] ?? [];
    
    // Analyze different types of persons
    $withDeals = [];
    $withActivities = [];
    $withEmail = [];
    $withMobile = [];
    
    foreach (array_slice($personsList, 0, 20) as $person) {
        if (!empty($person['Email'])) $withEmail[] = $person['Id'];
        if (!empty($person['MobilePhone'])) $withMobile[] = $person['Id'];
        
        // Check if has deals
        $dealsCheck = callDidarAPI('/deal/search', 'POST', [
            'Criteria' => ['ContactId' => $person['Id']],
            'From' => 0,
            'Limit' => 1
        ]);
        if (isset($dealsCheck['json']['Response']['TotalCount']) && $dealsCheck['json']['Response']['TotalCount'] > 0) {
            $withDeals[] = $person['Id'];
        }
        
        // Check if has activities
        $actsCheck = callDidarAPI('/activity/search', 'POST', [
            'Criteria' => ['ContactId' => $person['Id']],
            'From' => 0,
            'Limit' => 1
        ]);
        if (isset($actsCheck['json']['Response']['TotalCount']) && $actsCheck['json']['Response']['TotalCount'] > 0) {
            $withActivities[] = $person['Id'];
        }
    }
    
    $analysis['persons'] = [
        'total_count' => $persons['TotalCount'] ?? 0,
        'returned' => count($personsList),
        'sample' => $personsList[0] ?? null,
        'fields' => !empty($personsList) ? array_keys($personsList[0]) : [],
        'stats' => [
            'with_email' => count($withEmail),
            'with_mobile' => count($withMobile),
            'with_deals' => count($withDeals),
            'with_activities' => count($withActivities)
        ]
    ];
}

// 3. Deals Analysis
echo "Fetching Deals...\n";
$dealsRes = callDidarAPI('/deal/search', 'POST', [
    'Criteria' => ['Status' => -1],
    'From' => 0,
    'Limit' => 50
]);
if ($dealsRes['http_code'] === 200 && isset($dealsRes['json']['Response'])) {
    $deals = $dealsRes['json']['Response'];
    $dealsList = $deals['List'] ?? [];
    
    $statusCounts = ['Won' => 0, 'Lost' => 0, 'Pending' => 0];
    foreach ($dealsList as $deal) {
        if ($deal['Status'] === 'Won') $statusCounts['Won']++;
        elseif ($deal['Status'] === 'Lost') $statusCounts['Lost']++;
        else $statusCounts['Pending']++;
    }
    
    $analysis['deals'] = [
        'total_count' => $deals['TotalCount'] ?? 0,
        'returned' => count($dealsList),
        'sample' => $dealsList[0] ?? null,
        'fields' => !empty($dealsList) ? array_keys($dealsList[0]) : [],
        'status_distribution' => $statusCounts
    ];
}

// 4. Activities Analysis
echo "Fetching Activities...\n";
$activitiesRes = callDidarAPI('/activity/search', 'POST', [
    'Criteria' => [],
    'From' => 0,
    'Limit' => 50
]);
if ($activitiesRes['http_code'] === 200 && isset($activitiesRes['json']['Response'])) {
    $activities = $activitiesRes['json']['Response'];
    $activitiesList = $activities['List'] ?? [];
    
    $doneCount = 0;
    $withDealCount = 0;
    $withContactCount = 0;
    foreach ($activitiesList as $act) {
        if ($act['IsDone']) $doneCount++;
        if (!empty($act['DealId'])) $withDealCount++;
        if (!empty($act['Contacts'])) $withContactCount++;
    }
    
    $analysis['activities'] = [
        'returned' => count($activitiesList),
        'sample' => $activitiesList[0] ?? null,
        'fields' => !empty($activitiesList) ? array_keys($activitiesList[0]) : [],
        'stats' => [
            'done' => $doneCount,
            'with_deal' => $withDealCount,
            'with_contact' => $withContactCount
        ]
    ];
}

// 5. Activity Types Analysis
echo "Fetching Activity Types...\n";
$activityTypesRes = callDidarAPI('/activity/GetActivityType', 'POST');
if ($activityTypesRes['http_code'] === 200 && isset($activityTypesRes['json']['Response'])) {
    $types = $activityTypesRes['json']['Response'];
    
    $enabledTypes = array_filter($types, function($t) { return !$t['IsDisabled']; });
    $connectionTypes = array_filter($types, function($t) { return $t['IsConnection']; });
    
    $analysis['activity_types'] = [
        'total' => count($types),
        'enabled' => count($enabledTypes),
        'connection_types' => count($connectionTypes),
        'all_types' => $types
    ];
}

// 6. Pipelines Analysis
echo "Fetching Pipelines...\n";
$pipelinesRes = callDidarAPI('/pipeline/list/0', 'POST');
if ($pipelinesRes['http_code'] === 200 && isset($pipelinesRes['json']['Response'])) {
    $pipelines = $pipelinesRes['json']['Response'];
    
    $analysis['pipelines'] = [
        'total' => count($pipelines),
        'samples' => $pipelines
    ];
}

// Save analysis
file_put_contents('didar_deep_analysis.json', json_encode($analysis, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

echo "\n=== Analysis Complete ===\n";
echo "Results saved to: didar_deep_analysis.json\n";

