<?php
// Increase PHP max execution time to 600 seconds (10 minutes)
set_time_limit(-1);
// Optionally, you can also adjust the memory limit if needed
ini_set('memory_limit', '1024M'); // Increase memory limit to 512MB if needed

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: *");

$hsToken = 'pat-na1-20ef9794-3a4e-4f7a-8af2-1a33ffa815a0';
$url = "https://api.hubapi.com/crm/v3/objects/companies/search";


$batchSize = 10; // Number of records per batch
$nextPageUrl = "https://api.hubapi.com/crm/v3/objects/companies"; // Initial URL
$allIds = []; // Array to store all IDs
$offset = 0;

$companySearchPayload = json_encode([
                "properties" => ["hubspot_owner_id"],
                "limit" => $batchSize,
                "after" => $offset,
                "filterGroups" => [
                    [
                        "filters" => [
                            [
                                "propertyName" => "hubspot_owner_id",
                                "operator" => "HAS_PROPERTY"
                            ]
                        ]
                    ]
                ]
            ]);


http_response_code(201);


// Iterate through pages and store IDs in the array
foreach (getAllPages($url, $hsToken, $batchSize, $companySearchPayload, $offset) as $batchData) {
    foreach ($batchData as $record) {
        $allIds[] = $record['id'];
    }
}

            echo "<pre>";
            print_r($allIds); // Display all IDs
            echo "</pre>";


function getAllPages($url, $hsToken, $batchSizem, $companySearchPayload) {
    $currentUrl = $url;
    while ($currentUrl) {

        $response = makeCurlRequest($currentUrl, 'POST', $companySearchPayload, $hsToken);

        if ($response['status'] == 200) {
            $records = $response['data']['results']; // Get the results
            // echo "<pre>";
            // print_r($response); // Display all IDs
            // echo "</pre>";
            // Process the records in batches of 10
            $batchCount = 0;
            $batch = [];
            foreach ($records as $index => $record) {
                $batch[] = $record; // Add record to the current batch
                $batchCount++;

                // When batch size is reached, yield the batch
                if ($batchCount == $batchSize) {
                    yield $batch; // Return current batch
                    $batch = []; // Reset batch
                    $batchCount = 0;
                }
            }

            // If there are leftover records that didn't make up a full batch, yield them as well
            if (count($batch) > 0) {
                yield $batch; // Return the remaining records
            }

            // Set the next page URL
            $currentUrl = isset($response['data']['paging']['next']['after']) 
                          ? "https://api.hubapi.com/crm/v3/objects/companies?after=" . $response['data']['paging']['next']['after']
                          : null;


        } else {
            echo "Error: " . $response['error'];
            break;
        }
    // exit;
    }
}






/*$data = json_decode(file_get_contents("php://input"));
$data = $data[0]; //parth
$recordId = $data->objectId;

$getResponse = makeCurlRequest("https://api.hubapi.com/crm/v3/objects/companies/?properties=hubspot_owner_id", "GET", '', $hsToken);

$hubspotOwnerIds = [];

if (isset($getResponse['data']['results']) && is_array($getResponse['data']['results'])) {
    foreach ($getResponse['data']['results'] as $result) {
        if (!empty($result['properties']['hubspot_owner_id'])) {
            $hubspotOwnerIds[] = $result['properties']['hubspot_owner_id'];
        }
    }
}

echo "<pre>";print_r($hubspotOwnerIds);echo "</pre>";
*/

// echo "<pre>";print_r($getResponse);echo "</pre>";











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);
        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];
}



















// Define the log file path
$logFile = 'error_log.txt';

// Create or open the file
file_put_contents($logFile, "Log started on: " . date("Y-m-d H:i:s") . "\n", FILE_APPEND);

// Function to write logs
function writeLog($message) {
    $logFile = 'error_log.txt'; // Log file name
    $timestamp = date("Y-m-d H:i:s"); // Current date and time
    $logMessage = "[$timestamp] $message\n";

    file_put_contents($logFile, $logMessage, FILE_APPEND); // Append log
}

// Example usage
writeLog("This is an info log.");
writeLog("An error occurred in the system.");
writeLog("User logged in successfully.");

echo "Log file created and logs written.";
?>


<!-- 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 -->

