<?php
/*
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
*/
   chdir(dirname(__FILE__)."/../");
  
   
   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(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
                }
            }
            return $headers;
        }
    } 

    function save_log($input,$header)
    {   
        $log  = date('H:i:s d-m-Y')."-".$_SERVER['HTTP_ORIGIN']."-".$_SERVER['HTTP_REFERER']."-".$_SERVER['REMOTE_ADDR'].PHP_EOL.
                $input.PHP_EOL.
                $header.PHP_EOL.
                "-------------------------".PHP_EOL;

        //Save string to log, use FILE_APPEND to append.
        file_put_contents('formulario/log_'.date("j.n.Y").'.log', $log, FILE_APPEND);
    }

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

    global $site_URL;
    $urlCapture = $site_URL."modules/Webforms/capture.php"; #url del caputre
    $input =  file_get_contents("php://input");
    $headers = getallheaders();
    #print_r($headers_); exit;
    $responseData = [
        'error' => 'Invalid Token'
    ];

    save_log(json_encode(json_decode($input)),json_encode($headers));
    if(!empty($input) && !empty($headers['Api-Token']) && is_valid($headers['Api-Token']))
    {
        $inputArray = json_decode($input,true);
        $cu = curl_init();
		curl_setopt($cu, CURLOPT_URL, $urlCapture);
		curl_setopt($cu, CURLOPT_POST, 1);
		curl_setopt($cu, CURLOPT_POSTFIELDS, http_build_query($inputArray));
		curl_setopt($cu, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($cu, CURLOPT_HEADER, 1);
		$response = curl_exec($cu);

        if(curl_error($cu) === false)
        {
            echo 'Curl error: ' . curl_error($cu);
        }else{
            $header_size = curl_getinfo($cu, CURLINFO_HEADER_SIZE);
            $header = get_headers_from_curl_response(substr($response, 0, $header_size));
            $body = substr($response, $header_size);
            curl_close($cu);
            $responseData = [
                'error' => ''
            ];
            if(!empty($header))
            {
                $location = explode('?',$header['Location']);
                $responseCaptureStatus = explode("=",$location[1]);
                $responseData = [
                    'urlRedirect' => $location[0],
                    $responseCaptureStatus[0] => $responseCaptureStatus[1]
                ];
            }
        }
        
    }

    

    echo json_encode($responseData);
    
