<?php

logError("Cron Working:= ".date('Y-m-d H:i:s'));

function searchHubSpotCompanies($apiKey, $offset = 0, $limit = 1, &$collectedCompanies = []) {
    $url = "https://api.hubapi.com/crm/v3/objects/companies/search";
    $postData = json_encode([
        "properties" => ["hubspot_owner_id"],
        "filterGroups" => [[
            "filters" => [
                [
                    "propertyName" => "hubspot_owner_id",
                    "operator" => "HAS_PROPERTY"
                ]
            ]
        ]],
        "limit" => $limit,
        "after" => $offset
    ]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $apiKey",
        "Content-Type: application/json"
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200 || $response === false) {
        logError("Company API Error (HTTP Code: $httpCode): " . ($response ?: 'No response'."\n\n"));
        return $collectedCompanies;
    }

    $data = json_decode($response, true);
    logError("Company API Response: " . json_encode($data)."\n\n");
    if (isset($data["results"])) {
        //echo "<pre>";print_r($data["results"]);echo "</pre>";
        createHubSpotCompaniesTask($data["results"], $apiKey);
        //exit;
    }

    if (isset($data["paging"]["next"]["after"])) {
        return searchHubSpotCompanies($apiKey, $data["paging"]["next"]["after"], $limit, $collectedCompanies);
    }

    return $collectedCompanies;
}

// Example usage:
$apiKey = 'pat-na1-20ef9794-3a4e-4f7a-8af2-1a33ffa815a0';
$companies = searchHubSpotCompanies($apiKey);


function createHubSpotCompaniesTask($data, $apiKey){

    $taskParam = [];

    foreach ($data as $companyData) {
        if (isset($companyData['id']) && isset($companyData['properties']['hubspot_owner_id'])) {
            $hubspot_owner_id = $companyData['properties']['hubspot_owner_id'];
            $date = gmdate("Y-m-d\TH:i:s.v\Z");

            $taskParam[] = 
                                    [
                        "associations" => [
                            [
                                "to" => [
                                    "id" => $companyData['id']
                                ],
                                "types" => [
                                    [
                                        "associationCategory" => "HUBSPOT_DEFINED",
                                        "associationTypeId" => 192
                                    ]
                                ]
                            ]
                        ],
                        "properties" => [
                            "hs_timestamp" => $date,
                            "hs_task_body" => "",
                            "hubspot_owner_id" => $hubspot_owner_id,
                            "hs_task_subject" => "Check Your Credit Holds in Tableau",
                            "hs_task_status" => "WAITING",
                            "hs_task_priority" => "MEDIUM",
                            "hs_task_type" => "TODO"
                        ]
                    
                
            ];
        }
        // exit;
    }
    
    $fullData = ['inputs' => $taskParam];
    $encodeData = json_encode($fullData);
    logError("Task API Request Data: " . $encodeData."\n\n");
   
    // echo "<pre>";
    // print_r($encodeData);
    // echo "</pre>";
    $taskBatchUrl = "https://api.hubapi.com/crm/v3/objects/tasks/batch/create";
    $taskResponse = makeCurlRequest($taskBatchUrl, 'POST', $encodeData, $apiKey);
    logError("Task API Response: " . json_encode($taskResponse)."\n\n\n\n#######################################################################################################################################\n\n\n\n");
   // exit();

}

function makeCurlRequest($url, $method, $data = null, $token = '') {

    $ch = curl_init();
    // Set the options for the cURL request
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));

    // Set headers
    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $token
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Add data if provided

   
    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    // Execute the request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // Handle errors
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        logError("cURL Error: $error"."\n\n");
        return ['status' => 500, 'data' => null, 'error' => $error];
    }

    // Close cURL and parse the response
    curl_close($ch);
    $responseData = json_decode($response, true);

    return ['status' => $httpCode, 'data' => $responseData];
}

function logError($message) {
 
    $logFile = __DIR__ . '/logs/hubspot_api_errors.log';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

?>


<!-- URL: http://54.219.146.184/kanha-life/ -->
<!-- crontab -l -->
<!-- 1 -->
<!-- * * * * * /usr/bin/php /var/www/html/kanha-life/index.php >> /var/www/html/kanha-life/cron.log 2>&1 -->
<!-- 0 6 * * 1 /usr/bin/php /var/www/html/kanha-life/index.php >> /var/www/html/kanha-life/cron.log 2>&1 -->

