<?php
/*
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
*/
    chdir(dirname(__FILE__)."/../");
  
   
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: api-key, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
    header("Access-Control-Allow-Methods: POST, OPTIONS");
    header("Allow: POST, OPTIONS");
    $method = $_SERVER['REQUEST_METHOD'];
    if($method == "OPTIONS") {
        die();
    }
   require_once 'data/CRMEntity.php';
   include_once 'includes/main/WebUI.php';
   include_once 'vtlib/Vtiger/Module.php';
   require_once 'includes/Loader.php';
   require_once 'include/utils/utils.php';
   
   vimport('includes.http.Request');
   vimport('includes.runtime.Globals');
   vimport('includes.runtime.BaseModel');
   vimport ('includes.runtime.Controller');
   vimport('includes.runtime.LanguageHandler');

    function get_headers_from_curl_response($response)
    {
        $headers = array();

        $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));

        foreach (explode("\r\n", $header_text) as $i => $line)
            if ($i === 0)
                $headers['http_code'] = $line;
            else
            {
                list ($key, $value) = explode(': ', $line);

                $headers[$key] = $value;
            }

        return $headers;
    }

    if (!function_exists('getallheaders'))
    {
        function getallheaders()
        {
            $headers = [];
            foreach ($_SERVER as $name => $value)
            {
                if (substr($name, 0, 5) == 'HTTP_')
                {
                    $headers[str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($name, 5))))] = $value;
                }
            }
            return $headers;
        }
    } 

    function is_valid($token)
    {
        global $adb;
        $query = "SELECT * FROM vtiger_ws_userauthtoken WHERE token = ? AND expiretime > UNIX_TIMESTAMP()";
    
        $exec = $adb->pquery($query,[$token]);
        
        return $exec->numRows() > 0;
    }

    //Buscamos si existe el id por algun campo
	function searchValueExists($table,$field,$datasearch){
		
		global $adb, $dbconfig;

		//Para retornar las respuesta y el id
		$response = array();
		
		//Obtenemos el nombre de la primera columna que es el identificador
		$columns = $adb->pquery("SELECT COLUMN_NAME as 'indice'
									  FROM INFORMATION_SCHEMA.COLUMNS	
								  WHERE TABLE_SCHEMA = '".$dbconfig['db_name']."' AND TABLE_NAME = 'vtiger_{$table}' LIMIT 1;",array());
		
		//Obtenemos el nombre de la columna con el id principal
		$columnnid = $adb->query_result($columns,0,'indice');
		
		//buscamos el registro y si existe retornamos su crmid
		$rsexists = $adb->pquery("SELECT *FROM vtiger_{$table} tb 
										INNER JOIN vtiger_crmentity e ON e.crmid = tb.{$columnnid} AND e.deleted = 0
			WHERE tb.{$field} = '${datasearch}'",array());
		//Validamos si el registro existe para retornar el id 
		if($adb->num_rows($rsexists) > 0){
			$response["exists"] = true;
			$response["crmid"] = $adb->query_result($rsexists,0,$columnnid);
		}
		else{
			$response["exists"] = false;
			$response["crmid"] = '';
		}
		
		//retornamos si existe o no el registro
		return $response;
	}

    global $adb, $current_user;
    $current_user->id = 1;
    $input = file_get_contents("php://input");
    $headers = getallheaders();
    #print_r($headers_); exit;
    $responseData = [
        'error' => 'Invalid Token'
    ];
    
    if(!empty($input) && !empty($headers['api-key']) && is_valid($headers['api-key']))
    {
        $inputArray = json_decode($input,true);
        
        switch ($inputArray['action']) {
            case 'SyncOportunity':
                if(empty($inputArray['data']['account'])) {
                    $responseData = [
                        'error' => 'Cuenta Vacía'
                    ];
                    break;
                }

                if(empty($inputArray['data']['contact'])) {
                    $responseData = [
                        'error' => 'Contacto Vacío'
                    ];
                    break;
                }

                if(empty($inputArray['data']['contact']['tipo_documento'])) {
                    $responseData = [
                        'error' => 'Tipo de Documento Vacío'
                    ];
                    break;
                }

                if(empty($inputArray['data']['contact']['nro_documento'])) {
                    $responseData = [
                        'error' => 'Nro de Documento Vacío'
                    ];
                    break;
                }

                if(empty($inputArray['data']['potential'])) {
                    $responseData = [
                        'error' => 'Oportunidad Vacía'
                    ];
                    break;
                }

                /*
                    Cuentas: Campo Integrados
                    - RUC : siscode
                    - Nombre de la Cuenta : accountname
                    - DIRECCION : bill_street
                    - Provincia : bill_state
                    - Departamento : bill_pobox
                    - Distrito: bill_city
                    - Asignado a: assigned_user_id
                    - Origen de la Cuenta (x def Referido Digital) : leadsource
                    - Tipo de Persona (Juridica/Natural): cf_852 
                */
                $AccountData = $inputArray['data']['account'];
                if(!empty($AccountData))
                {
                    $asignado = 1; #Por defecto el asignado será Administrador
                    if(!empty($AccountData['user']))
                    {
                        $res = $adb->pquery('SELECT id FROM vtiger_users WHERE email1 = ?',[$AccountData['user']]);
                        $asignado = $adb->num_rows($res) > 0 ? $adb->query_result($res,0,'id') : 1;
                    }
                    $ruc = $AccountData['ruc'];
                    $dataexists = searchValueExists("account","siccode",$ruc); //Busqueda por RUC
                    if($dataexists['exists']){
                        $accountModel = Vtiger_Record_Model::getInstanceById($dataexists['crmid'],"Accounts");
                        $accountModel->set('mode', 'edit');
                    }
                    else{
                        $accountModel = Vtiger_Record_Model::getCleanInstance("Accounts");
                        $accountModel->set('mode', "");
                        $accountModel->set('leadsource','Referido Digital');
                        $accountModel->set('source','WEBSERVICE');
                    }

                    $accountModel->set('siccode',$ruc);
                    $accountModel->set('accountname',$AccountData['razon_social']);
                    $accountModel->set('bill_street',$AccountData['direccion']);
                    $accountModel->set('bill_state',$AccountData['provincia']);
                    $accountModel->set('bill_pobox',$AccountData['departamento']);
                    $accountModel->set('bill_city',$AccountData['distrito']);
                    $accountModel->set('cf_852',$AccountData['tipo_persona']);
                    $accountModel->set('assigned_user_id',$asignado);
                    
                    try{
                        $accountModel->save();
                        $Accountid = $accountModel->getId();
                    } catch (DuplicateException $e) {
                        $Accountid = $accountModel->getId();
                    } catch (Exception $e) {
						print_r($e);
					}

                }

                /*
                    Contactos: Campo Integrados
                    - Tipo documento : tipodocumento
                    - Nro de documento : nrodocumento
                    - Cuenta : account_id
                    - Nombre : firstname
                    - Apellidos : lastname
                    - Tel Empresa: mobile
                    - Correo Electrónico principal: email
                    - Asignado a : assigned_user_id
                */

                $ContactData = $inputArray['data']['contact'];
                if(!empty($ContactData))
                {
                    $asignado = 1; #Por defecto el asignado será Administrador
                    if(!empty($ContactData['user']))
                    {
                        $res = $adb->pquery('SELECT id FROM vtiger_users WHERE email1 = ?',[$ContactData['user']]);
                        $asignado = $adb->num_rows($res) > 0 ? $adb->query_result($res,0,'id') : 1;
                    }
                    
                    $tipDoc = $ContactData['tipo_documento'];
                    switch ($tipDoc) {
                        case 'Y': $tipodoc = 'DOC. IDENTIDAD (EXTRANJERO)'; break;
                        case 3: $tipodoc = 'CARNET DE IDENTIDAD'; break;
                        case 4: $tipodoc = 'CARNET DE EXTRANJERIA'; break;
                        case 5: $tipodoc = 'PASAPORTE'; break;
                        case 6: $tipodoc = 'CARNET IDENTIDAD FF PP'; break;
                        case 7: $tipodoc = 'CARNET IDENTIDAD FF AA'; break;
                        case 8: $tipodoc = 'LIBRETA TRIBUTARIA'; break;
                        case 9: $tipodoc = 'DOCUMENTO PROVISIONAL IDENTIDAD'; break;
                        case 'A': $tipodoc = 'CED. DIPLOMATICA DE IDENTIDAD'; break;
                        case 'B': $tipodoc = 'DOC. TRIB. NO DOM. SIN RUC'; break;
                        case 'D': $tipodoc = 'DNI'; break;
                        case 'R': $tipodoc = 'RUC'; break;
                        default:
                            # code...
                            break;
                    }

                    #Busca si el contacto existe o no:
                    $qu = $adb->pquery("SELECT c.contactid FROM vtiger_contactdetails c
                    JOIN vtiger_crmentity e ON c.contactid = e.crmid AND e.deleted = 0 WHERE c.nrodocumento = ? AND c.tipodocumento = ? LIMIT 1",[$ContactData['nro_documento'],$tipodoc]);
                    if($adb->num_rows($qu) > 0){
                        $concatId = $adb->query_result($qu,0,'contactid');
                        $contactModel = Vtiger_Record_Model::getInstanceById($concatId,"Contacts");
                        $contactModel->set('mode', 'edit');
                    }
                    else{
                        $contactModel = Vtiger_Record_Model::getCleanInstance("Contacts");
                        $contactModel->set('mode', "");
                        $contactModel->set('source','WEBSERVICE');
                    }

                    $contactModel->set('tipodocumento',$tipodoc);
                    $contactModel->set('nrodocumento',$ContactData['nro_documento']);
                    $contactModel->set('account_id',$Accountid);
                    $contactModel->set('firstname',$ContactData['nombre']);
                    $contactModel->set('lastname',$ContactData['apellido']);
                    $contactModel->set('mobile',$ContactData['telefono']);
                    $contactModel->set('email',$ContactData['email']);
                    $contactModel->set('assigned_user_id',$asignado);
                    
                    try{
                        $contactModel->save();
                        $Contactid = $contactModel->getId();
                    } catch (Exception $e) {
                        print_r($e);
                    }
                }
                
                 /*
                    Oportunidades: Campo Integrados
                    - Nombre de oportunidad : potentialname
                    - tipo de Oportunidad : opportunity_type
                    - Fase de venta : sales_stage
                    - Nombre de Cuenta : related_to
                    - Monto : amount
                    - Fecha de cierre : closingdate
                    - Origen: leadsource
                    - Asignado a : assigned_user_id
                */
                $PotentialData = $inputArray['data']['potential'];
                
                if(!empty($PotentialData)){
                    $asignado = 1; #Por defecto el asignado será Administrador
                    if(!empty($PotentialData['user']))
                    {
                        $res = $adb->pquery('SELECT id FROM vtiger_users WHERE email1 = ?',[$PotentialData['user']]);
                        $asignado = $adb->num_rows($res) > 0 ? $adb->query_result($res,0,'id') : 1;
                    }
                    
                    $potentialModel = Vtiger_Record_Model::getCleanInstance("Potentials");
                    $potentialModel->set('mode', "");
                    $potentialModel->set('source','WEBSERVICE');
                    $potentialModel->set('potentialname',$PotentialData['oportunidad']);
                    $potentialModel->set('opportunity_type',$PotentialData['tipo']);
                    $potentialModel->set('sales_stage','Documentacion');
                    $potentialModel->set('amount',$PotentialData['monto']);
                    $potentialModel->set('closingdate',date('Y-m-d',strtotime(date('Y-m-d')." +30 days")));
                    $potentialModel->set('leadsource','Referido Digital');
                    $potentialModel->set('contact_id',$Contactid);
                    $potentialModel->set('related_to',$Accountid);
                    $potentialModel->set('assigned_user_id',$asignado);
                    
                    try{
                        $potentialModel->save();
                    } catch (Exception $e) {
                        print_r($e);
                    }
                }
                $responseData = [
                    'error' => '',
                    'success' => true,
                    'data' => [
                        'account_id' => $accountModel->getId(),
                        'contact_id' => $contactModel->getId(),
                        'potential_id' => $potentialModel->getId()
                    ]
                ];
                
            break;
            
            case 'UpdatePotential':
                $numOp = $inputArray['data']['num_op'];
                if(!empty($numOp))
                {
                    $dataexists = searchValueExists("potential","nro_operacion",$numOp); //Busqueda por RUC
                    if($dataexists['exists']){
                        #Valida que la fase de venta sea válida
                        $v = $adb->pquery('SELECT * FROM vtiger_sales_stage WHERE sales_stage = ?',[$inputArray['data']['sales_stage']]);
                        if($adb->num_rows($v) > 0)
                        {
                            $PotentialModel = Vtiger_Record_Model::getInstanceById($dataexists['crmid'],"Potentials");
                            $PotentialModel->set('mode', 'edit');
                            $PotentialModel->set('sales_stage', $inputArray['data']['sales_stage']);
                            $PotentialModel->save();

                            $responseData = [
                                'error' => '',
                                'success' => true
                            ];
                        }
                        else{
                            $responseData = [
                                'success' => false,
                                'error' => 'Fase de venta invalida'
                            ];
                        }
                    }
                    else{
                        $responseData = [
                            'success' => false,
                            'error' => 'Nro de Operacion no existe'
                        ];
                    }
                }
                else {
                    $responseData = [
                        'success' => false,
                        'error' => 'Nro de Operacion faltante'
                    ];
                }
            break;
            default:
                $responseData = [
                    'success' => false,
                    'error' => 'Invalid Action'
                ];
                break;
        }
        

        
    }

    echo json_encode($responseData);
    
