<?php


//increase max execution time of this script to 150 min:
ini_set('max_execution_time', 9000);

//increase Allowed Memory Size of this script:
ini_set('memory_limit','960M');

// Curl
require_once WOO_VTIGER_DIR . '/Curl/Curl.php';


//------------------------ Get Vtiger data information for login ------------------------

    // Get vtiger data
    $data = get_vtiger_crm_data_info();


    //url path to vtiger/webservice.php like http://vtiger_url/webservice.php
    $endpointUrl = $data['crm_endpointurl']."webservice.php";

    //username of the user who is to logged in.
    $userName = $data['crm_username'];

    //access key of the user admin, found on my preferences page.
    $userAccessKey = $data['crm_access_key'];

    //Vtiger crm database hostname.
    $crm_db_hostname = $data['crm_db_hostname'];

    //Vtiger crm database username
    $crm_db_username = $data['crm_db_username'];

    //Vtiger crm database password.
    $crm_db_password = $data['crm_db_password'];

    //Vtiger crm database name.
    $crm_db_name = $data['crm_db_name'];

    $db_connect = mysqli_connect($crm_db_hostname , $crm_db_username , $crm_db_password, $crm_db_name);

    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        die();
    }

    if($crm_db_name == ''){
        echo "Database Name Not Found. Set database name in CRM Setting";
       die();    
    }else if(!$db_connect){
        echo "Invalid CRM Credentials.";
        die();    
    }


//----------------------------- Get challenge token -------------------------------------

    $curl = new \Curl\Curl();
    $curl->get("$endpointUrl?operation=getchallenge&username=$userName");

    if ($curl->error) {
        echo '<pre>'; print_r($curl->error); echo '</pre>'; echo __FILE__; die();
    }

    $response = $curl->response;
    $jsonResponse = json_decode($response, true);

    if ($jsonResponse['success'] == false) {
        //handle the failure case.
        die('getchallenge failed:'.$jsonResponse['error']['errorMsg']);
    }

    //operation was successful get the token from the response.
    $challengeToken = $jsonResponse['result']['token'];

//------------------------------ Get login access ----------------------------------------

    //create md5 string concatenating user accesskey from my preference page 
    //and the challenge token obtained from get challenge result. 
    $generatedKey = md5($challengeToken.$userAccessKey);

    //login request must be POST request.
    $curl->post("$endpointUrl", array('operation' => 'login', 'username' => $userName,
        'accessKey' => $generatedKey));
    if ($curl->error) {
        echo '<pre>'; print_r($curl->error); echo '</pre>'; echo __FILE__; die();
    }
    $response = $curl->response;
    $jsonResponse = json_decode($response, true);

    //decode the json encode response from the server.

    //operation was successful get the token from the reponse.
    if($jsonResponse['success'] == false)
        //handle the failure case.
        die('login failed:' . $jsonResponse['error']['errorMsg']);

    //login successful extract sessionId and userId from LoginResult to it can used for further calls.
    $sessionId = $jsonResponse['result']['sessionName'];
    $userId = $jsonResponse['result']['userId'];

?>