<?php
namespace index;

error_reporting(E_ALL);
ini_set('display_errors',1);
require_once '/var/www/libraries/vendor/autoload.php';

use com\zoho\api\authenticator\OAuthBuilder;
use com\zoho\api\authenticator\OAuthToken;

use com\zoho\api\authenticator\TokenType;

use com\zoho\api\authenticator\store\DBStore;

use com\zoho\api\authenticator\store\FileStore;

use com\zoho\crm\api\Initializer;

use com\zoho\crm\api\UserSignature;

use com\zoho\crm\api\SDKConfigBuilder;

use com\zoho\crm\api\dc\USDataCenter;

use com\zoho\api\logger\Logger;

use com\zoho\api\logger\Levels;

use com\zoho\crm\api\record\RecordOperations;

use com\zoho\crm\api\HeaderMap;

use com\zoho\crm\api\ParameterMap;

use com\zoho\crm\api\record\GetRecordsHeader;

use com\zoho\crm\api\record\GetRecordsParam;

use com\zoho\crm\api\record\ResponseWrapper;

use com\zoho\crm\api\layouts\Layout;
use com\zoho\crm\api\record\APIException;
use com\zoho\crm\api\record\ActionWrapper;
use com\zoho\crm\api\record\BodyWrapper;

use com\zoho\crm\api\dc\EUDataCenter;


class Record
{
    public static function getRecord()
    {
        /*
            * Create an instance of Logger Class that takes two parameters
            * 1 -> Level of the log messages to be logged. Can be configured by typing Levels "::" and choose any level from the list displayed.
            * 2 -> Absolute file path, where messages need to be logged.
        */
        $logger = Logger::getInstance(Levels::DEBUG, "/var/www/tmp/zoho/php_sdk_log.".microtime(true).".log");

        //Create an UserSignature instance that takes user Email as parameter
        $user = new UserSignature("office@rca.md");

        /*
            * Configure the environment
            * which is of the pattern Domain.Environment
            * Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter
            * Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX()
        */
        $environment = USDataCenter::PRODUCTION();

        //Create a Token instance
        /**/$token = (new OAuthBuilder())
    ->clientId("1000.MWWIELVAFFZ4IADPTSRA9J1CL0OD3B")
    ->clientSecret("a963fc9a1d4857b9f365f9efcfcb622dab0d1e2a92")
    ->grantToken("1000.10242a43ff78ad0256041603ba10bbe7.beb0018168d4dc440294c791d2d581d4")
    ->build();/**/

        //Create an instance of TokenStore
        // $tokenstore = new DBStore();

        $tokenstore = new FileStore("/var/www/tmp/zoho/php_sdk_token.txt");

        $autoRefreshFields = false;

        $pickListValidation = false;

        $connectionTimeout = 2;

        $timeout = 2;


    $autoRefreshFields = false;

    $pickListValidation = false;

    $connectionTimeout = 2;//The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.

    $timeout = 2;//The maximum number of seconds to allow cURL functions to execute.

$enableSSLVerification=false;
    $sdkConfig = (new SDKConfigBuilder())
    ->autoRefreshFields($autoRefreshFields)->pickListValidation($pickListValidation)->sslVerification($enableSSLVerification)
    ->connectionTimeout($connectionTimeout)->timeout($timeout)->build();


        //$sdkConfig = (new SDKConfigBuilder())->setAutoRefreshFields($autoRefreshFields)->setPickListValidation($pickListValidation)->setSSLVerification($enableSSLVerification)->connectionTimeout($connectionTimeout)->timeout($timeout)->build();

        $resourcePath ="/var/www/tmp/zoho";

       /*
        * Call static initialize method of Initializer class that takes the following arguments
        * 1 -> UserSignature instance
        * 2 -> Environment instance
        * 3 -> Token instance
        * 4 -> TokenStore instance
        * 5 -> SDKConfig instance
        * 6 -> resourcePath -A String
        * 7 -> Log instance (optional)
        * 8 -> RequestProxy instance (optional)
        */
        Initializer::initialize($user, $environment, $token, $tokenstore, $sdkConfig, $resourcePath, $logger);

        try
        {
        
        
        
        $recordOperations = new RecordOperations();
        
        //Get instance of BodyWrapper Class that will contain the request body
        $bodyWrapper = new BodyWrapper();
        
        //List of Record instances
        $records = array();

        $recordClass = 'com\zoho\crm\api\record\Record';
        
        //Get instance of Record Class
        $record1 = new $recordClass();
        $recordData=@array(
                'Last_Name' => $_POST["data"]["firstname"] . ' ' . $_POST["data"]["lastname"],
                'Cod_Personal_Fiscal' => $_POST["data"]["idnp"],
                'Email' => 'nickolas.tests+'.date('YmdHis').'@gmail.com',
                'Phone' => '+37369587812',
                'Marca_Modelul' => $_POST['data']['car_brand'] . ' ' . $_POST['data']['car_model'],
                'Nume_Prenume' => $_POST["data"]["drivers"][0]["firstname"] . ' ' . $_POST["data"]["drivers"][0]["lastname"],
                'Coduri_Personale' => $_POST['data']["drivers"][0]["idnp"],
                'Num_rul_pa_aportului_tehnic' => $_POST['data']["car_reg_certificate_number"],
                'Num_r_de_nmatriculare' => $_POST['data']['vehicle_reg_number'],
                'Tipul_autovehiculului' => $_POST['data']['transport_type'],
                'Anul_fabric_rii' => $_POST['data']['year_of_issue'],
                'Teritoriul_asigurat' => $_POST['data']['insured_territory'],
                'Trailer' => $_POST['data']['calculate_trailer'],
                'Trailer_Reg_Certif' => $_POST['data']['trailer_reg_certif'],
                'Trailer_Reg' => $_POST['data']['trailer_reg'],
                'Right_Possession' => $_POST['data']['right_possession_car'],
                'Insurance_Period' => $_POST['data']['insurance_period'],
                'Insurance_Company' => $_POST['data']['insurance_company'],
                'Billing_Total' => $_POST['data']['billing_total'] . ' MDL',
                'Car_Registration_Certificate' => $_POST['data']['type_car_registration_certificate'],
                'Status_of_the_Insured' => $_POST['data']['data_insured'],
                'Payment_method' => $_POST['data']['payment_method'],
                'Beginning_insurance_policy' => $_POST['data']['beginning_insurance_policy'],
        );
        
        foreach($recordData AS $k=>$v){
        
        $record1->addKeyValue($k,($k!='Email' && $k!='Phone')?(date('Y-m-d H:i:s').' '.$k):$v);
        }
        
        array_push($records, $record1);
        
        //Set the list to Records in BodyWrapper instance
        $bodyWrapper->setData($records);
        
        $trigger = array("approval", "workflow", "blueprint");
        
        $bodyWrapper->setTrigger($trigger);
        
        
        $headerInstance = new HeaderMap();

        //$headerInstance->add(GetRecordsHeader::XEXTERNAL(), "Contacts.External");
        
        //Call createRecords method that takes BodyWrapper instance as parameter.
        $response = $recordOperations->createRecords('Contacts', $bodyWrapper, $headerInstance);
        
        if($response != null)
        {
            //Get the status code from response
            echo("Status Code: " . $response->getStatusCode() . "\n");
echo '<pre>';print_r($response);echo '</pre>';
            if($response->isExpected())
            {
                //Get object from response
                $actionHandler = $response->getObject();
                
                if($actionHandler instanceof ActionWrapper)
                {
                    //Get the received ActionWrapper instance
                    $actionWrapper = $actionHandler;
                    
                    //Get the list of obtained ActionResponse instances
                    $actionResponses = $actionWrapper->getData();
                    
                    foreach($actionResponses as $actionResponse)
                    {
                        //Check if the request is successful
                        if($actionResponse instanceof SuccessResponse)
                        {
                            //Get the received SuccessResponse instance
                            $successResponse = $actionResponse;
                            
                            //Get the Status
                            echo("Status: " . $successResponse->getStatus()->getValue() . "\n");
                            
                            //Get the Code
                            echo("Code: " . $successResponse->getCode()->getValue() . "\n");
                            
                            echo("Details: " );
                            
                            //Get the details map
                            foreach($successResponse->getDetails() as $key => $value)
                            {
                                //Get each value in the map
                                echo($key . " : ");
                                
                                print_r($value);
                                
                                echo("\n");
                            }
                            
                            //Get the Message
                            echo("Message: " . $successResponse->getMessage()->getValue() . "\n");
                        }
                        //Check if the request returned an exception
                        else if($actionResponse instanceof APIException)
                        {
                            //Get the received APIException instance
                            $exception = $actionResponse;
                            
                            //Get the Status
                            echo("Status: " . $exception->getStatus()->getValue() . "\n");
                            
                            //Get the Code
                            echo("Code: " . $exception->getCode()->getValue() . "\n");
                            
                            echo("Details: " );
                            
                            //Get the details map
                            foreach($exception->getDetails() as $key => $value)
                            {
                                //Get each value in the map
                                echo($key . " : " . $value . "\n");
                            }
                            
                            //Get the Message
                            echo("Message: " . $exception->getMessage()->getValue() . "\n");
                        }
                    }
                }
                //Check if the request returned an exception
                else if($actionHandler instanceof APIException)
                {
                    //Get the received APIException instance
                    $exception = $actionHandler;
                    
                    //Get the Status
                    echo("Status: " . $exception->getStatus()->getValue() . "\n");
                    
                    //Get the Code
                    echo("Code: " . $exception->getCode()->getValue() . "\n");
                    
                    echo("Details: " );
                    
                    //Get the details map
                    foreach($exception->getDetails() as $key => $value)
                    {
                        //Get each value in the map
                        echo($key . " : " . $value . "\n");
                    }
                    
                    //Get the Message
                    echo("Message: " . $exception->getMessage()->getValue() . "\n");
                }
            }
            else
            {
                print_r($response);
            }
        }
        
        
        }
        catch (\Exception $e)
        {
            print_r($e);
        }
    }
}

Record::getRecord();

?>