<?php
    /**
     *  wsFileLedes1998B.PHP
     * 
     *  Autor: Felipe Faccinetto
     *  Fecha: Octubre/2018
     * 
     *  DESCRIPCIÓN:
     * 
     *  Lleva a cabo la creación del archivo LEDES correspondiente 
     * 
     *  PARAMETROS:
     * 
     *  pNomArc	      	Nombre del archivo LEDES resultante
     *  pDatLed	      	Cadena codificada en base64 que contiene un arreglo JSON con los datos para el archivo LEDES
	 *  pRecordId		Identidicador del registro a actualizar en Zoho Creator
	 *  pInvoiceId		Identidicador del registro a actualizar en Zoho Books
	 *  pOrganiIdZB		Organization ID para Zoho Books
	 *  pauthtokenZB	Authtoken para Zoho Books
	 *  pauthtokenZC	Authtoken para Zoho Creator
     *  pDatGen         Cadena codificada en base64 que contiene un arreglo JSON con los datos generales de OAuth
     *  pAppOwner       Especifica el propietario de la aplicación que se actualizara.
     * 
	 *	http://64.235.39.50/aptusCFDIRF/wsFileLedes1998B.php?pNomArc=LEDES_INV-000001.txt&pRecordId=1&pDatLed=W3siQkl....1RZUEUiOiJFIn1d
     * 
    */
	
    header('Content-Type: text/html; charset=UTF-8');
    include("qrlib/qrlib.php");
    require('oauth.php');

    $bDatLed  	    = "";
	$bRecId   	    = "";
	$bInvId   	    = "";
	$arcLedes       = "";
	$organi_id_ZB   = "";
	$authtoken_ZB   = "";
	$authtoken_ZC   = "";
    $bDatGen        = "";
    $appOwner   = "";

    ## Cargamos los parametros enviados al WebService
    if (isset($_REQUEST['pDatGen']))
    {
        $bDatGen = $_REQUEST['pDatGen'];                    // Datos Generales de OAuth
    }
    
    if (isset($_REQUEST['pNomArc']))
    {
        $arcLedes = $_REQUEST['pNomArc'];        			// Parametro con nombre del archivo LEDES
    }

    if (isset($_REQUEST['pDatLed']))
    {
        $bDatLed = $_REQUEST['pDatLed'];        			// Parametros con arreglo de registros para LEDES
    }

    if (isset($_REQUEST['pRecordId']))
    {
        $bRecId = $_REQUEST['pRecordId'];        			// Identidicador del registro LEDES en Zoho Creator
    }

    if (isset($_REQUEST['pInvoiceId']))
    {
        $bInvId = $_REQUEST['pInvoiceId'];        			// Identidicador del invoice en Zoho Books
    }

    if (isset($_REQUEST['pOrganiIdZB']))
    {
        $organi_id_ZB = $_REQUEST['pOrganiIdZB'];    		// Parametro con Organization ID de Zoho Books
    }
	
    if (isset($_REQUEST['pauthtokenZB']))
    {
        $authtoken_ZB = $_REQUEST['pauthtokenZB'];        	// Parametro Authtoken para Zoho Books
    }
	
    if (isset($_REQUEST['pauthtokenZC']))
    {
        $authtoken_ZC = $_REQUEST['pauthtokenZC'];        	// Parametro Authtoken para Zoho Creator
    }

    if (isset($_REQUEST['pAppOwner']))
    {
        $appOwner = $_REQUEST['pAppOwner'];        // Parametros para el propietario de la aplicación
    }

    ## Validamos que esten completos los parametros necesarios para el webservice
    if($appOwner == "")
    {
		$j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan el Propoietario de la Aplicación");
		$Resultado = json_encode($j_array);
		echo $Resultado;
        return;
    }


    ## Validamos que esten completos los parametros necesarios para el webservice
    if($arcLedes == "")
    {
		$j_array = array('code' => "300", "message" => "ERROR - [wsFileLedes1998B] Parametros incompletos para el Servicio Web, faltan el Nombre del Archivo LEDES");
		$Resultado = json_encode($j_array);
		echo $Resultado;
        return;
    }

    if($bRecId == "")
    {
		$j_array = array('code' => "300", "message" => "ERROR - [wsFileLedes1998B] Parametros incompletos para el Servicio Web, faltan el ID del LEDES a actualizar");
		$Resultado = json_encode($j_array);
		echo $Resultado;
        return;
    }

    if($bInvId == "")
    {
		$j_array = array('code' => "300", "message" => "ERROR - [wsFileLedes1998B] Parametros incompletos para el Servicio Web, faltan el ID del Invoice a actualizar");
		$Resultado = json_encode($j_array);
		echo $Resultado;
        return;
    }

    if($bDatLed == "")
    {
		$j_array = array('code' => "300", "message" => "ERROR - [wsFileLedes1998B] Parametros incompletos para el Servicio Web, faltan los Datos de LEDES");
		$Resultado = json_encode($j_array);
		echo $Resultado;
        return;
    }

    if($bDatGen == "")
    {
		$j_array = array('code' => "300", "message" => "ERROR - [wsInvoiceSF] Parametros incompletos para el Servicio Web, faltan los datos de autorización");
		$Resultado = json_encode($j_array);
		echo $Resultado;
        return;
    }

    ### 1. EXTRACCION DE PARAMETROS PARA EL CFDI ######################################################
    #== Primero, extraemos el JSON del string en base 64
    $bdDatLed = base64_decode($bDatLed);

    #== Segundo, decodificamos el JSON a un arreglo
    $abdDatLed = json_decode($bdDatLed,true);
	
    $dirBase = realpath("../");


    ### 2. DEFINICIÓN DE CONSTANTES ###################################################
    $SendaPEMS  = "archs_pem/";   
    $SendaCFDI  = "archs_cfdi/";  
    $SendaGRAFS = "archs_graf/";  
    $SendaXSD   = "archs_xsd/";   
    
	$fileLedes = fopen($SendaCFDI.$arcLedes, "w");
	fwrite($fileLedes, "LEDES1998B[]" . PHP_EOL);
	fwrite($fileLedes, "INVOICE_DATE|INVOICE_NUMBER|CLIENT_ID|LAW_FIRM_MATTER_ID|INVOICE_TOTAL|BILLING_START_DATE|BILLING_END_DATE|INVOICE_DESCRIPTION|LINE_ITEM_NUMBER|EXP/FEE/INV_ADJ_TYPE|LINE_ITEM_NUMBER_OF_UNITS|LINE_ITEM_ADJUSTMENT_AMOUNT|LINE_ITEM_TOTAL|LINE_ITEM_DATE|LINE_ITEM_TASK_CODE|LINE_ITEM_EXPENSE_CODE|LINE_ITEM_ACTIVITY_CODE|TIMEKEEPER_ID|LINE_ITEM_DESCRIPTION|LAW_FIRM_ID|LINE_ITEM_UNIT_COST|TIMEKEEPER_NAME|TIMEKEEPER_CLASSIFICATION|CLIENT_MATTER_ID[]" . PHP_EOL);
	
    // Calculando subTotal, Impuestos Trasladados y Retenidos.
    for ($i = 0; $i<count($abdDatLed); $i++){
		fwrite($fileLedes,$abdDatLed[$i]["INVOICE_DATE"] . "|" . $abdDatLed[$i]["INVOICE_NUMBER"]."|" . $abdDatLed[$i]["CLIENT_ID"]."|" . $abdDatLed[$i]["LAW_FIRM_MATTER_ID"]."|" . $abdDatLed[$i]["INVOICE_TOTAL"] . "|" . $abdDatLed[$i]["BILLING_START_DATE"] . "|" . $abdDatLed[$i]["BILLING_END_DATE"] . "|" . $abdDatLed[$i]["INVOICE_DESCRIPTION"] . "|" . $abdDatLed[$i]["LINE_ITEM_NUMBER"] . "|" . $abdDatLed[$i]["EXP_FEE_INV_ADJ_TYPE"] . "|" . $abdDatLed[$i]["LINE_ITEM_NUMBER_OF_UNITS"] . "|" . $abdDatLed[$i]["LINE_ITEM_ADJUSTMENT_AMOUNT"] . "|" . $abdDatLed[$i]["LINE_ITEM_TOTAL"] . "|" . $abdDatLed[$i]["LINE_ITEM_DATE"] . "|" . $abdDatLed[$i]["LINE_ITEM_TASK_CODE"] . "|" . $abdDatLed[$i]["LINE_ITEM_EXPENSE_CODE"] . "|" . $abdDatLed[$i]["LINE_ITEM_ACTIVITY_CODE"] . "|" . $abdDatLed[$i]["TIMEKEEPER_ID"] . "|" . $abdDatLed[$i]["LINE_ITEM_DESCRIPTION"] . "|" . $abdDatLed[$i]["LAW_FIRM_ID"] . "|" . $abdDatLed[$i]["LINE_ITEM_UNIT_COST"] . "|" . $abdDatLed[$i]["TIMEKEEPER_NAME"] . "|" . $abdDatLed[$i]["TIMEKEEPER_CLASSIFICATION"] . "|" . $abdDatLed[$i]["CLIENT_MATTER_ID"] . "[]" . PHP_EOL);
    }
	
	fclose($fileLedes);

    chmod($SendaCFDI.$arcLedes, 0777); 

    # Obtenemos el access token de Zoho Creator

    #== Primero, extraemos el JSON del string en base 64
    $bdDatGen = base64_decode($bDatGen);

    #== Segundo, decodificamos el JSON a un arreglo
    $abdDatGen = json_decode($bdDatGen,true);

    #== Datos y Variables para OAuth Token
	$coa_ClientId 		= $abdDatGen["C_OAuth_client_id"];
	$coa_ClientSecret 	= $abdDatGen["C_OAuth_client_secret"];
	$coa_RefreshToken 	= $abdDatGen["C_OAuth_refresh_token"];
    $coa_GrantType      = $abdDatGen["C_OAuth_grant_type"];
    $coa_RedirectUri    = $abdDatGen["C_OAuth_redirect_uri"];
	$coa_AuthUrl 		= "https://accounts.zoho.com/oauth/v2/token";

    #----------------------------------------------------------------
  	# JFA: 2021-06-12
	# Obtenemos el access_token
  	#----------------------------------------------------------------

    //  $Params = array(
    //     "refresh_token" => $coa_RefreshToken,
    //     "client_id" => $coa_ClientId,
    //     "client_secret" => $coa_ClientSecret,
    //     "redirect_uri" => $coa_RedirectUri,
    //     "grant_type" => $coa_GrantType
    // );
    
    // $curl = curl_init();
    // curl_setopt($curl, CURLOPT_URL, $coa_AuthUrl);
    // curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
    // curl_setopt($curl, CURLOPT_POSTFIELDS, $Params);
    // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

    // $response = curl_exec($curl);

    // print_r($response);
    // echo "<br>";

    // $array = json_decode($response);
    // $coa_access_token = $array->access_token;

    $access_token = oauth($appOwner, 'ZCreator', $coa_RefreshToken, $coa_ClientId, $coa_ClientSecret, $coa_RedirectUri, $coa_GrantType, $coa_AuthUrl);

    # Envio del Archivo a Ledes de Zoho Creator 
    $file_name_with_full_path = '/var/www/html/aptusCFDIRF/archs_cfdi/'.$arcLedes;
    //$request_url = 'https://creator.zoho.com/api/xml/fileupload/scope=creatorapi';
    $request_url = 'https://creator.zoho.com/api/v2/'.$appOwner.'/'.$applnkname.'/report/LEDES_Report/'.$bRecId.'/fileLedesTxt/upload';

    if (function_exists('curl_file_create')) { // php 5.6+
      $cFile = curl_file_create($file_name_with_full_path);
    } 
    else 
	{  
      $cFile = '@' . realpath($file_name_with_full_path);
    }

    $post = array(
    // 'authtoken' => $authtoken_ZC,
    // 'applinkname' => 'ledes',
    // 'formname' => 'LEDES',
	// 'fieldname' => 'fileLedesTxt',
    // 'recordId' => $bRecId,
    // 'filename' => $arcLedes,
    'file'=> $cFile);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Zoho-oauthtoken ' . $coa_access_token));

    $r = curl_exec($ch);
	echo $r;
    curl_close ($ch);

    # Obtenemos el access token de Zoho Books

    $boa_ClientId 		= $abdDatGen["B_OAuth_client_id"];
	$boa_ClientSecret 	= $abdDatGen["B_OAuth_client_secret"];
	$boa_RefreshToken 	= $abdDatGen["B_OAuth_refresh_token"];
    $boa_GrantType      = $abdDatGen["B_OAuth_grant_type"];
    $boa_RedirectUri    = $abdDatGen["B_OAuth_redirect_uri"];
	$boa_AuthUrl 		= "https://accounts.zoho.com/oauth/v2/token";

    #----------------------------------------------------------------
  	# JFA: 2021-06-12
	# Obtenemos el access_token
  	#----------------------------------------------------------------

    //  $Params = array(
    //     "refresh_token" => $boa_RefreshToken,
    //     "client_id" => $boa_ClientId,
    //     "client_secret" => $boa_ClientSecret,
    //     "redirect_uri" => $boa_RedirectUri,
    //     "grant_type" => $boa_GrantType
    // );
    
    // $curl = curl_init();
    // curl_setopt($curl, CURLOPT_URL, $boa_AuthUrl);
    // curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
    // curl_setopt($curl, CURLOPT_POSTFIELDS, $Params);
    // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

    // $response = curl_exec($curl);
    // $array = json_decode($response);
    // $boa_access_token = $array->access_token;

    $boa_access_token = oauth($appOwner, 'ZBooks', $boa_RefreshToken, $boa_ClientId, $boa_ClientSecret, $boa_RedirectUri, $boa_GrantType, $boa_AuthUrl);

    # Envio del Archivos a Invoice de Zoho Books
    $file_name_with_full_path = '/var/www/html/aptusCFDIRF/archs_cfdi/'.$arcLedes;
    $request_url = 'https://www.zohoapis.com/books/v3/invoices/'.$bInvId.'/attachment';

    if (function_exists('curl_file_create')) { // php 5.6+
      $cFile = curl_file_create($file_name_with_full_path);
    } 
    else 
	{  
      $cFile = '@' . realpath($file_name_with_full_path);
    }

    $post = array(
    // 'authtoken' => $authtoken_ZB,
    // 'organization_id' => $organi_id_ZB,
    // 'can_send_in_mail' => 'true',
    'attachment'=> $cFile);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Zoho-oauthtoken ' . $boa_access_token));

    $r = curl_exec($ch);
    curl_close ($ch);

    unlink($SendaCFDI.$arcLedes);

    $j_array = array('code' => "200", 'message' => "Proceso de creacion del archivo LEDES fue exitoso", 'archivo_ledes' => $fileLedes);
    $Resultado = json_encode($j_array);
	echo $Resultado;
	return;
