<?php
/**
 * Script to analyze real 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);
    $error = curl_error($ch);
    curl_close($ch);
    
    return [
        'http_code' => $httpCode,
        'error' => $error,
        'response' => $response,
        'json' => json_decode($response, true)
    ];
}

echo "=== DIDAR CRM DATA ANALYSIS ===\n\n";

// 1. Get Users List
echo "1. ANALYZING USERS...\n";
echo str_repeat("-", 80) . "\n";
$usersRes = callDidarAPI('/User/List', 'POST');
if ($usersRes['http_code'] === 200 && isset($usersRes['json']['Response'])) {
    $users = $usersRes['json']['Response'];
    echo "Total Users: " . count($users) . "\n";
    echo "Sample User Structure:\n";
    if (!empty($users)) {
        $sampleUser = $users[0];
        echo json_encode($sampleUser, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    }
} else {
    echo "ERROR: " . ($usersRes['error'] ?: json_encode($usersRes['json'], JSON_UNESCAPED_UNICODE)) . "\n";
}
echo "\n\n";

// 2. Get Persons (Contacts)
echo "2. ANALYZING PERSONS (CONTACTS)...\n";
echo str_repeat("-", 80) . "\n";
$personsRes = callDidarAPI('/contact/personsearch', 'POST', [
    'Criteria' => ['IsDeleted' => 0],
    'From' => 0,
    'Limit' => 10
]);
if ($personsRes['http_code'] === 200 && isset($personsRes['json']['Response'])) {
    $persons = $personsRes['json']['Response'];
    echo "Total Count: " . ($persons['TotalCount'] ?? 'N/A') . "\n";
    echo "Returned: " . count($persons['List'] ?? []) . "\n";
    echo "Sample Person Structure:\n";
    if (!empty($persons['List'])) {
        $samplePerson = $persons['List'][0];
        echo json_encode($samplePerson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    }
} else {
    echo "ERROR: " . ($personsRes['error'] ?: json_encode($personsRes['json'], JSON_UNESCAPED_UNICODE)) . "\n";
}
echo "\n\n";

// 3. Get Deals
echo "3. ANALYZING DEALS...\n";
echo str_repeat("-", 80) . "\n";
$dealsRes = callDidarAPI('/deal/search', 'POST', [
    'Criteria' => ['Status' => -1],
    'From' => 0,
    'Limit' => 10
]);
if ($dealsRes['http_code'] === 200 && isset($dealsRes['json']['Response'])) {
    $deals = $dealsRes['json']['Response'];
    echo "Total Count: " . ($deals['TotalCount'] ?? 'N/A') . "\n";
    echo "Returned: " . count($deals['List'] ?? []) . "\n";
    echo "Sample Deal Structure:\n";
    if (!empty($deals['List'])) {
        $sampleDeal = $deals['List'][0];
        echo json_encode($sampleDeal, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    }
} else {
    echo "ERROR: " . ($dealsRes['error'] ?: json_encode($dealsRes['json'], JSON_UNESCAPED_UNICODE)) . "\n";
}
echo "\n\n";

// 4. Get Activities
echo "4. ANALYZING ACTIVITIES...\n";
echo str_repeat("-", 80) . "\n";
$activitiesRes = callDidarAPI('/activity/search', 'POST', [
    'Criteria' => [],
    'From' => 0,
    'Limit' => 10
]);
if ($activitiesRes['http_code'] === 200 && isset($activitiesRes['json']['Response'])) {
    $activities = $activitiesRes['json']['Response'];
    echo "Total Count: " . ($activities['TotalCount'] ?? 'N/A') . "\n";
    echo "Returned: " . count($activities['List'] ?? []) . "\n";
    echo "Sample Activity Structure:\n";
    if (!empty($activities['List'])) {
        $sampleActivity = $activities['List'][0];
        echo json_encode($sampleActivity, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    }
} else {
    echo "ERROR: " . ($activitiesRes['error'] ?: json_encode($activitiesRes['json'], JSON_UNESCAPED_UNICODE)) . "\n";
}
echo "\n\n";

// 5. Get Activity Types
echo "5. ANALYZING ACTIVITY TYPES...\n";
echo str_repeat("-", 80) . "\n";
$activityTypesRes = callDidarAPI('/activity/GetActivityType', 'POST');
if ($activityTypesRes['http_code'] === 200 && isset($activityTypesRes['json']['Response'])) {
    $activityTypes = $activityTypesRes['json']['Response'];
    echo "Total Activity Types: " . count($activityTypes) . "\n";
    echo "Sample Activity Types:\n";
    foreach (array_slice($activityTypes, 0, 5) as $type) {
        echo json_encode($type, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    }
} else {
    echo "ERROR: " . ($activityTypesRes['error'] ?: json_encode($activityTypesRes['json'], JSON_UNESCAPED_UNICODE)) . "\n";
}
echo "\n\n";

// 6. Get Pipelines
echo "6. ANALYZING PIPELINES...\n";
echo str_repeat("-", 80) . "\n";
$pipelinesRes = callDidarAPI('/pipeline/list/0', 'POST');
if ($pipelinesRes['http_code'] === 200 && isset($pipelinesRes['json']['Response'])) {
    $pipelines = $pipelinesRes['json']['Response'];
    echo "Total Pipelines: " . count($pipelines) . "\n";
    echo "Sample Pipeline Structure:\n";
    if (!empty($pipelines)) {
        $samplePipeline = $pipelines[0];
        echo json_encode($samplePipeline, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    }
} else {
    echo "ERROR: " . ($pipelinesRes['error'] ?: json_encode($pipelinesRes['json'], JSON_UNESCAPED_UNICODE)) . "\n";
}
echo "\n\n";

// 7. Get a specific person with deals and activities
if (!empty($persons['List'])) {
    $testPersonId = $persons['List'][0]['Id'] ?? null;
    if ($testPersonId) {
        echo "7. ANALYZING SPECIFIC PERSON DETAILS...\n";
        echo str_repeat("-", 80) . "\n";
        echo "Person ID: $testPersonId\n";
        
        // Get person deals
        $personDealsRes = callDidarAPI('/deal/search', 'POST', [
            'Criteria' => ['ContactId' => $testPersonId],
            'From' => 0,
            'Limit' => 10
        ]);
        if ($personDealsRes['http_code'] === 200 && isset($personDealsRes['json']['Response'])) {
            $personDeals = $personDealsRes['json']['Response'];
            echo "Person Deals Count: " . ($personDeals['TotalCount'] ?? 0) . "\n";
            if (!empty($personDeals['List'])) {
                echo "Sample Deal for this person:\n";
                echo json_encode($personDeals['List'][0], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
            }
        }
        
        // Get person activities
        $personActivitiesRes = callDidarAPI('/activity/search', 'POST', [
            'Criteria' => ['ContactId' => $testPersonId],
            'From' => 0,
            'Limit' => 10
        ]);
        if ($personActivitiesRes['http_code'] === 200 && isset($personActivitiesRes['json']['Response'])) {
            $personActivities = $personActivitiesRes['json']['Response'];
            echo "\nPerson Activities Count: " . ($personActivities['TotalCount'] ?? 0) . "\n";
            if (!empty($personActivities['List'])) {
                echo "Sample Activities for this person:\n";
                foreach (array_slice($personActivities['List'], 0, 3) as $act) {
                    echo json_encode($act, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
                }
            }
        }
    }
}

echo "\n\n=== ANALYSIS COMPLETE ===\n";

