<?php
function pr( $s_Content )
{
    echo "<pre>";
    print_r( $s_Content );
    echo "</pre>";
}

date_default_timezone_set ( "America/Lima" );

ini_set('max_execution_time', 0);
ini_set('log_errors', 'off');
error_reporting(E_ALL & ~E_NOTICE);

ini_set( "allow_url_fopen", 1 );

if ( ini_get( "allow_url_fopen" ) == 1) 
{
    echo "allow_url_fopen is ON<br>";
}
else 
{
    echo "allow_url_fopen is OFF<br>";
}
print ini_get("allow_url_fopen");

function curl( $url )
{
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    $return = curl_exec( $ch );
    curl_close ( $ch );
    return $return;
}

$cn = mysql_connect( "localhost", "root", "" );
//$cn = mysql_connect( "localhost", "micaela_user", "MHWinv2854624" );
mysql_select_db( "micaela_database" );

pr( mysql_error() );

function recuperarDataFor( $a_Datos, $s_Fecha )
{
    foreach ( $a_Datos as $i_Key => $a_Data )
    {
        $s_FechaFnd = $a_Data['fecha'];
        if( $s_FechaFnd == $s_Fecha )
        {
            return $a_Data;
        }
    }
    return null;
}

function RecuperarDia( $s_Anio, $s_Mes, $s_Dia )
{
    //$s_RespuestaContenido = file_get_contents( "http://code.staffsystems.us/webservices/tipo-de-cambio/serverside.php?work=get_sunat&mes=$s_Mes&anho=$s_Anio" );
    //pr( $s_RespuestaContenido );
    $s_RespuestaContenido = curl( "http://code.staffsystems.us/webservices/tipo-de-cambio/serverside.php?work=get_sunat&mes=$s_Mes&anho=$s_Anio" );
    $a_ResultCambios = json_decode( $s_RespuestaContenido, true );
    $b_Control = true;
    if( isset( $a_ResultCambios['success'] ) )
    {
        if( isset( $a_ResultCambios['data'] ) )
        {
            echo "<pre>"; print_r( $a_ResultCambios['data'] ); echo "</pre>";
            $a_Result = null;
            do 
            {
                $a_Result = recuperarDataFor( $a_ResultCambios['data'], $s_Anio."-".$s_Mes."-".$s_Dia );
                if( !$a_Result )
                {
                    $i_Dia = ( int ) $s_Dia;
                    if( $i_Dia == 1 )
                    {
                        $i_Dia = 32;
                        
                        $i_Mes = ( int ) $s_Mes;
                        $i_Mes = $i_Mes - 1;
                        $s_Mes = str_pad( $i_Mes, 2, "0", STR_PAD_LEFT );
                        
                        $i_Dia = $i_Dia - 1;
                        $s_Dia = str_pad( $i_Dia, 2, "0", STR_PAD_LEFT );
                        
                        $a_Result = RecuperarDia( $s_Anio, $s_Mes, $s_Dia );
                        if( $a_Result )
                        {
                            break;
                        }
                    }
                    $i_Dia = $i_Dia - 1;
                    $s_Dia = str_pad( $i_Dia, 2, "0", STR_PAD_LEFT );
                    
                }
            }
            while ( is_null( $a_Result ) );
            
            if( $a_Result )
            {
                return $a_Result;
            }
            else 
            {
                return null;
            }
        }
    }
    return null;
}

$s_Fecha  = date( "Y-m-d" );
$s_Dia   = date( "d" );
$s_Mes   = date( "m" );
$s_Anio  = date( "Y" );

$a_Result = RecuperarDia( $s_Anio, $s_Mes, $s_Dia );

echo "<pre>"; print_r( $a_Result ); echo "</pre>";

if( $a_Result )
{
    $s_Sql = "SELECT IdCompania, Codigo, DescripcionCorta, DescripcionLarga FROM GSS_Compania;";
    $rs = mysql_query( $s_Sql );
    $cnt = mysql_num_rows( $rs );
    if( $cnt > 0 )
    {
        while ( $a_row = mysql_fetch_array( $rs, MYSQL_ASSOC ) ) 
        {
        	$IdCompania = $a_row['IdCompania'];
        	
        	$SunatCompra = $a_Result['compra'];
        	$SunatVenta  = $a_Result['venta'];
        	
        	$s_Sql = "
                        REPLACE INTO GSS_TipoCambio 
                        (IdMoneda, IdMonedaCambio, IdFechaCambio, IdCompania, SunatCompra, SunatVenta, TipoCambioCobranza, Estado, FechaCreacion, UsuarioCreacion) 
                        VALUES
                        ('EX', 'LO', '$s_Fecha', $IdCompania, '$SunatCompra', '$SunatVenta', '$SunatVenta', 'A', NOW(), 'cron');
        	           ";
        	$_rs = mysql_query( $s_Sql );
        	echo "<pre>"; print_r( $_rs ); echo "</pre>";
        	echo "<pre>"; print_r( $IdCompania." - ".$s_Fecha." -> OK" ); echo "</pre>";
        }
    }
}