<?php
function crea_enti_escala()
{
     if(empty($link_data)){$link_data=$_SESSION['link_data'];}
     if(empty($cfg_empr)){$cfg_empr=$_SESSION['cfg_empr'];}

     $empr0=data_maes('empr',$_SESSION['empr_codigo']);

     if(empty($empr0['empr_escala_crm'])){return;}
     
     $sql_clie ='select * from clie0 ';
     $sql_clie.='where ifnull(clie_status,"")not in ("I","X") ';
     $sql_clie.='and ifnull(clie_escala_account,"")="" ';
     $sql_clie.='and clie_codigo not like "9999%" ';
     $sql_clie.='and clie_codigo in (select distinct enti from clie1 where fecha>="2024-08-01") ';
//      $sql_clie.='and clie_codigo in (select distinct enti from clie1 where fecha>="'.date('Y-m-01',strtotime('-1 month')).'") ';
     $sql_clie.='order by clie_idate desc ';
     $sql_clie.='limit 10 ';
     $res_clie=msql_query($sql_clie,$link_data);
     
//      echo '==='.$sql_clie;
     while($aso_clie=msql_fetch_assoc($res_clie))
     {
//                echo '<br>==== '.$aso_clie['clie_codigo'].'-'.$aso_clie['clie_descri'];
               
          $params=array(
            "annualRevenue"=> 0,
            "assignedTo"=> "unassigned",
          //   "custom"=> (
              "RUC"=> $aso_clie['clie_codigo'],
          //     "cf_name_text"=> "Mark Johnson"
          //   ),
          //   "email"=> "^a(?:\\.a)*@(?:a(?:a)?\\.)+a(?:a)+$",
          //   "industryTypeCode"=> "agriculture",
            "name"=> $aso_clie['clie_descri'],
            "numberOfEmployees"=> 0,
          //   "phone"=> $aso_clie['clie_telefono'],
          //   "website"=> ""
          );               
               
          $response=createAccount($params);
          $data = json_decode($response, true);

          $sql_updt='update enti0 set enti_escala_account="'.$data['id'].'" where enti_codigo="'.$aso_clie['clie_codigo'].'"';
          $res_updt=msql_query($sql_updt,$link_data);
     }
     
     
}


function crea_clie_escala()
{
     if(empty($link_data)){$link_data=$_SESSION['link_data'];}
     if(empty($cfg_empr)){$cfg_empr=$_SESSION['cfg_empr'];}

     $empr0=data_maes('empr',$_SESSION['empr_codigo']);

     if(empty($empr0['empr_escala_crma'])){return;}
     
     $sql_clie ='select * from clie1 ';
     $sql_clie.='where ifnull(status,"")not in ("O","X") ';
     $sql_clie.='and ifnull(escala_deal,"")="" ';
     $sql_clie.='and enti not like "9999%" ';
     $sql_clie.='and fecha>="2024-08-01" ';
     $sql_clie.='and fecha>="'.date('Y-m-01',strtotime('-1 month')).'" ';
     $sql_clie.='order by idnum1 ';
     $sql_clie.='limit 1 ';
     $res_clie=msql_query($sql_clie,$link_data);
     
     $params=array(
          'text'=>''
     );
     
//           $response=searchDeals($params);
          $response=searchContact($params);
          $data = json_decode($response, true);
          $response=str_replace('{"accountId":"','<br><br>{"accountId":"',$response);
          echo '<br><br>==== '.$response;
     
     
     while($aso_clie=msql_fetch_assoc($res_clie))
     {
//                echo '<br>==== '.$aso_clie['docu'].'-'.$aso_clie['numero'];
               
          $params=array(
            "annualRevenue"=> 0,
            "assignedTo"=> "unassigned",
          //   "custom"=> (
              "RUC"=> $aso_clie['clie_codigo'],
          //     "cf_name_text"=> "Mark Johnson"
          //   ),
          //   "email"=> "^a(?:\\.a)*@(?:a(?:a)?\\.)+a(?:a)+$",
          //   "industryTypeCode"=> "agriculture",
            "name"=> $aso_clie['clie_descri'],
            "numberOfEmployees"=> 0,
          //   "phone"=> $aso_clie['clie_telefono'],
          //   "website"=> ""
          );               
               
//           $response=createDeal($params);
//           $data = json_decode($response, true);

//           $sql_updt='update clie1 set escala_crmal="'.$data['id'].'" where idnum1="'.$aso_clie['idnum1'].'"';
//           $res_updt=msql_query($sql_updt,$link_data);
     }
     
     
}



function set_idescala_accounts($texto='')
{
     if(empty($link_data)){$link_data=$_SESSION['link_data'];}
     if(empty($cfg_empr)){$cfg_empr=$_SESSION['cfg_empr'];}

     $empr0=data_maes('empr',$_SESSION['empr_codigo']);

//      echo '=============================';
     if(empty($empr0['empr_escala_crm'])){return;}

//      $ruc='0993376519001';
     
//      $ruc=$texto;
//      $texto='';

     $params = array(
         'name' => $texto,
//          'RUC' => $ruc,
         // Add more parameters as needed
     );
     
//      return;
//      $idacc='b54a3b4b-2f30-11ef-9647-b7d5e688faea';
     $response=searchAccounts($params);
//           $response=getAccount($idacc);
     
//      echo '==== '.$response;
     $data = json_decode($response, true);
     
//      echo '<br>==== '.$data;
     // Iterar sobre los items
//      foreach ($data['entity'] as $key=>$value) 
     foreach ($data['items'] as $item) 
     {
//           if(!empty($item['id']))
          {
//                echo '<br>===>'.$item['id'];
               $sql_updt='update enti0 set enti_escala_account="'.$item['id'].'" where enti_descri like "'.$texto.'%" limit 1';
               $res_updt=msql_query($sql_updt,$link_data);
          }
//                echo '<br>=>'.$key . ': ' . $value . "";
//          foreach($item as $key=>$value)
//          {
//                if (is_array($value))
//                {
//                     $array1=$value;
//                     foreach ($array1 as $key1=>$value1)
//                     {echo '<br>- - ->'.$key1 . ': ' . $value1 . "";         }
//                }

//          }

     //     echo '<br>';
     //     echo "Account ID: " . $item['accountId'] . "\n";
     //     echo '<br>';
     //     echo "Assigned To: " . $item['assignedTo'] . "\n";
     //     echo '<br>';
     //     echo "Company Name: " . $item['company']['name'] . "\n";
     //     echo '<br>';
     //     echo "Created: " . $item['created'] . "\n";
     //     echo '<br>';
     //     echo "Email: " . $item['personal']['email'] . "\n";
     //     echo '<br>';
     //     echo "Phone Number: " . $item['personal']['phoneNumber'] . "\n";
     //     echo '<br>';
     //     echo "Status: " . $item['status'] . "\n";
     //     echo '<br>';
     //     echo "---------------------";
     //     echo '<br>';
     }

     
     
     
     
}



function getAccount($accountId) {
    // Get the authentication token from the environment
    $token = getenv('TOKEN');

    // Set the request headers
    $headers = array(
        'Content-Type: application/json',
        'x-api-key: ' . $token
    );

    // Build the query parameters
//     $queryParameters = http_build_query($params);

    // Construct the request URL
//     $baseApiUrl = 'https://public-api.escala.com/v1/crm/accounts';
//     $requestUrl = $baseApiUrl . '?' . $queryParameters;

     
        $baseApiUrl = 'https://public-api.escala.com/v1/crm/accounts/' . $accountId;
        $requestUrl=$baseApiUrl;

//                          https://public-api.escala.com/v1/crm/accounts/b54a3b4b-2f30-11ef-9647-b7d5e688faea     
        // Initialize a cURL session
//         $ch = curl_init($baseApiUrl);

//      echo '==== '.$baseApiUrl;
     
    try {
        // Initialize a cURL session
        $ch = curl_init($requestUrl);
        
        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 200) {
            echo 'Success';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}



function searchAccounts($params) {
    // Get the authentication token from the environment
    $token = getenv('TOKEN');

    // Set the request headers
    $headers = array(
        'Content-Type: application/json',
        'x-api-key: ' . $token
    );

    // Build the query parameters
    $queryParameters = http_build_query($params);

    // Construct the request URL
    $baseApiUrl = 'https://public-api.escala.com/v1/crm/accounts';
    $requestUrl = $baseApiUrl . '?' . $queryParameters;

    try {
        // Initialize a cURL session
        $ch = curl_init($requestUrl);
        
        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 200) {
            echo 'Success';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}

function searchActivities($params) {
    // Get the authentication token from the environment
    $token = getenv('TOKEN');

    // Set the request headers
    $headers = array(
        'Content-Type: application/json',
        'x-api-key: ' . $token
    );

    // Build the query parameters
    $queryParameters = http_build_query($params);

    // Construct the request URL
    $baseApiUrl = 'https://public-api.escala.com/v1/crm/activities';
    $requestUrl = $baseApiUrl . '?' . $queryParameters;

    try {
        // Initialize a cURL session
        $ch = curl_init($requestUrl);
        
        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 200) {
            echo 'Success';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}

// // Example usage
// // Array with search parameters
// $params = array(
//     'type' => 'event',
//     'status' => 'pending',
//     'assignedTo' => 'email@domain.com',
//     // Add more parameters as needed
// );

// // Call the searchActivities function
// $response = searchActivities($params);

// // Perform operations with the response here
// // For example, you can decode the JSON response if needed
// $data = json_decode($response);




// =============================================================================
// =============================================================================

function createAccount($data) {
    try {
        // Get the authentication token from the environment
        $token = getenv('TOKEN');

        // Set the request headers
        $headers = array(
            'Content-Type: application/json',
            'x-api-key: ' . $token
        );

        // Set the base API URL
        $baseApiUrl = 'https://public-api.escala.com/v1/crm/accounts';

        // Initialize a cURL session
        $ch = curl_init($baseApiUrl);

        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 201) {
//             echo 'Account Created';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}



function createContact($data) {
    try {
        // Get the authentication token from the environment
        $token = getenv('TOKEN');

        // Set the request headers
        $headers = array(
            'Content-Type: application/json',
            'x-api-key: ' . $token
        );

        // Set the base API URL
        $baseApiUrl = 'https://public-api.escala.com/v1/crm/contacts';

        // Initialize a cURL session
        $ch = curl_init($baseApiUrl);

        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 201) {
            echo 'Contact Created';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}

// Example usage
// $data = array(
//   "assignedTo" => "unassigned",
//   "company" => array(
//     "annualRevenue" => 10000000,
//     "email" => "company@email.com",
//     "industryType" => "agriculture",
//     "name" => "Acme Inc",
//     "numberOfEmployees" => 20,
//     "phoneNumber" => "56912345678",
//     "website" => "https://acme.com"
//   ),
//   "contacted" => true,
//   "notes" => "Note",
//   "personal" => array(
//     "address" => "1234 Street",
//     "birthDay" => 28,
//     "birthMonth" => 2,
//     "birthYear" => 1998,
//     "city" => "City",
//     "country" => "USA",
//     "email" => "contact@email.com",
//     "facebook" => "https://www.facebook.com/user_name",
//     "firstName" => "Monica",
//     "instagram" => "@user_name",
//     "jobTitle" => "Project Manager",
//     "lastName" => "Geller",
//     "linkedIn" => "https://www.linkedin.com/in/user_name",
//     "phoneNumber" => "56912345678",
//     "region" => "Region",
//     "secondaryPhoneNumber" => "56912345670",
//     "state" => "State",
//     "twitter" => "@user_name"
//   ),
//   "priority" => 0,
//   "source" => "referrer",
//   "status" => "lead",
//   "triggerWorkflow" => false
// );

// $response = createContact($data);








// =============================================================================
// =============================================================================


function updateContact($contactId, $data) {
    try {
        // Get the authentication token from the environment
        $token = getenv('TOKEN');

        // Set the request headers
        $headers = array(
            'Content-Type: application/json',
            'x-api-key: ' . $token
        );

        // Set the base API URL
        $baseApiUrl = 'https://public-api.escala.com/v1/crm/contacts/' . $contactId;

        // Initialize a cURL session
        $ch = curl_init($baseApiUrl);

        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 200) {
            echo 'Contact Updated';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}

// Example usage
// $data = array(
//     "assignedTo" => "unassigned",
//     "company" => array(
//         "annualRevenue" => 10000000,
//         "email" => "company@email.com",
//         "industryType" => "agriculture",
//         "name" => "Acme Inc",
//         "numberOfEmployees" => 20,
//         "phoneNumber" => "56912345678",
//         "website" => "https://acme.com"
//     ),
//     "contacted" => true,
//     "notes" => "Note",
//     "personal" => array(
//         "address" => "1234 Street",
//         "birthDay" => 28,
//         "birthMonth" => 2,
//         "birthYear" => 1998,
//         "city" => "City",
//         "country" => "USA",
//         "email" => "contact@email.com",
//         "facebook" => "https://www.facebook.com/user_name",
//         "firstName" => "Monica",
//         "instagram" => "@user_name",
//         "jobTitle" => "Project Manager",
//         "lastName" => "Geller",
//         "linkedIn" => "https://www.linkedin.com/in/user_name",
//         "phoneNumber" => "56912345678",
//         "region" => "Region",
//         "secondaryPhoneNumber" => "56912345670",
//         "state" => "State",
//         "twitter" => "@user_name"
//     ),
//     "priority" => 0,
//     "source" => "referrer",
//     "status" => "lead",
//     "triggerWorkflow" => false
// );

// $response = updateContact("contact_id_here", $data);


// =============================================================================
// =============================================================================


// Delete Deal

// Deletes a deal with the specified ID..
// Args:
// deal_id (str): Path parameter of Deal Id to be deleted.
// triggerWorkflow (bool, optional): Indicates whether to trigger a workflow. Defaults to None.
// Returns:
// a Response object from the requests library. This object contains all the information of the HTTP Response Deal Delete schema


function deleteDeal($dealId, $triggerWorkflow = null) {
    try {
        // Get the authentication token from the environment
        $token = getenv('TOKEN');

        // Set the request headers
        $headers = array(
            'Content-Type: application/json',
            'x-api-key: ' . $token
        );

        // Set the base API URL
        $baseApiUrl = 'https://public-api.escala.com/v1/crm/deals/' . $dealId;

        if ($triggerWorkflow !== null) {
            $baseApiUrl .= '?triggerWorkflow=' . ($triggerWorkflow ? 'true' : 'false');
        }

        // Initialize a cURL session
        $ch = curl_init($baseApiUrl);

        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 200) {
            echo 'Success';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}

// Example usage
// $response = deleteDeal("deal_id_here", true);




// =============================================================================
// =============================================================================


function searchContact($params) {
    // Get the authentication token from the environment
    $token = getenv('TOKEN');

    // Set the request headers
    $headers = array(
        'Content-Type: application/json',
        'x-api-key: ' . $token
    );

    // Build the query parameters
    $queryParameters = http_build_query($params);

    // Construct the request URL
    $baseApiUrl = 'https://public-api.escala.com/v1/crm/contacts';
    $requestUrl = $baseApiUrl . '?' . $queryParameters;

    try {
        // Initialize a cURL session
        $ch = curl_init($requestUrl);
        
        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 200) {
            echo 'Success';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}




// =============================================================================
// =============================================================================


function searchDeals($params) {
    // Get the authentication token from the environment
    $token = getenv('TOKEN');

    // Set the request headers
    $headers = array(
        'Content-Type: application/json',
        'x-api-key: ' . $token
    );

    // Build the query parameters
    $queryParameters = http_build_query($params);

    // Construct the request URL
    $baseApiUrl = 'https://public-api.escala.com/v1/crm/deals';
    $requestUrl = $baseApiUrl . '?' . $queryParameters;

    try {
        // Initialize a cURL session
        $ch = curl_init($requestUrl);
        
        // Set options for the cURL session
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL session
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($statusCode == 200) {
            echo 'Success';
        } else {
            echo $response;
        }

        // Close the cURL session
        curl_close($ch);

        return $response;
    } catch (Exception $ex) {
        echo 'An exception occurred: ' . $ex->getMessage();
    }

    return null;
}




// =============================================================================
// =============================================================================


// =============================================================================
// =============================================================================


// =============================================================================
// =============================================================================


// =============================================================================
// =============================================================================







?>