<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

spl_autoload_extensions(".class.php, .php, .inc");
spl_autoload_register("my_autoload");
set_error_handler("handleWarningAvise");
error_reporting(E_ALL);
ini_set('display_errors',1);

require 'phpMailer/Exception.php';
require 'phpMailer/PHPMailer.php';
require 'phpMailer/SMTP.php';

function my_autoload($nomArchivo){
    //$path_class=array('./class/');
    $archivo="./class/".$nomArchivo.".php";
	if(file_exists(__DIR__.'/'.$nomArchivo.".php")){
		require_once __DIR__.'/'.$nomArchivo.".php";
	}elseif(file_exists("./class/fpdf/".$nomArchivo.".php")){
		$archivo="../class/fpdf/".$nomArchivo.".php";
		require_once($archivo);
	}	
}

function multi_attach_mail($to, $subject, $message, $senderMail, $senderName){
    $bcc="omezaere@gmail.com";
    $from = $senderName." <".$senderMail.">"; 
    $headers = "From: " . $from . "\r\n" ;
    $headers.= "bcc:" . 'Omar Meza'. " <" .$bcc. ">". "\r\n";

    // boundary 
    $semi_rand = md5(time()); 
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
    // Add headers for file attachment
    $headers .= "MIME-Version: 1.0\n" .
                "Content-Type: multipart/mixed;\n" .
                " boundary=\"{$mime_boundary}\"";
    // multipart boundary 
    $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 


    $message .= "--{$mime_boundary}--";
    $returnpath = "-f" . $senderMail;

    //send email
    $mail = @mail($to, $subject, $message, $headers, $returnpath); 

    //function return true, if email sent, otherwise return fasle
    if($mail){ return TRUE; } else { return FALSE; }

}

function envio_correo($to, $subject, $message, $senderMail, $senderName,$cliente,$bcc = ""){

    
    $mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->CharSet = 'UTF-8';                          // Set the character set to UTF-8
    $mail->Encoding = 'base64';                        // Set the encoding to base64
    $mail->Host       = 'mail.escuelalacasitadevalentina.pe';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'info@escuelalacasitadevalentina.pe';                     //SMTP username
    $mail->Password   = 'bSrd3]*W9]QD';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ));
        
    //Recipients
    $mail->setFrom('info@escuelalacasitadevalentina.pe', 'Mensaje Sistema ERP');
    //$mail->setFrom('info@gofastcenter.com', 'Mensaje Sistema ERP');

    // Convierte la cadena de direcciones de correo electrónico en un array
    $toArray = explode(';', $to);
    // Recorre el array y agrega cada dirección al campo BCC
    foreach ($toArray as $toAddress) {
        $mail->addAddress(trim($toAddress), '');    //Add a recipient
    }

    //$mail->addCC($copia);

    if (!empty($bcc)) {
        // Convierte la cadena de direcciones de correo electrónico en un array
        $bccArray = explode(';', $bcc);
    
        // Recorre el array y agrega cada dirección al campo BCC
        foreach ($bccArray as $bccAddress) {
            $mail->addBCC(trim($bccAddress)); // Trim para eliminar espacios en blanco alrededor de las direcciones
        }
    }
   
           //Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = $subject;
    $mail->Body    = $message;

    $mail->send();
    
    if($mail){ return TRUE; } else { return FALSE; }
} catch (Exception $e) {
   
    echo "Hubo un error al enviar el mensaje: {$mail->ErrorInfo}";
}
}

function getPlataform($user_agent){
	if(strpos($user_agent, 'Windows NT 10.0') !== FALSE)
        return "Windows 10";
    elseif(strpos($user_agent, 'Windows NT 6.3') !== FALSE)
        return "Windows 8.1";
    elseif(strpos($user_agent, 'Windows NT 6.2') !== FALSE)
        return "Windows 8";
    elseif(strpos($user_agent, 'Windows NT 6.1') !== FALSE)
        return "Windows 7";
    elseif(strpos($user_agent, 'Windows NT 6.0') !== FALSE)
        return "Windows Vista";
    elseif(strpos($user_agent, 'Windows NT 5.1') !== FALSE)
        return "Windows XP";
    elseif(strpos($user_agent, 'Windows NT 5.2') !== FALSE)
        return 'Windows 2003';
    elseif(strpos($user_agent, 'Windows NT 5.0') !== FALSE)
        return 'Windows 2000';
    elseif(strpos($user_agent, 'Windows ME') !== FALSE)
        return 'Windows ME';
    elseif(strpos($user_agent, 'Win98') !== FALSE)
        return 'Windows 98';
    elseif(strpos($user_agent, 'Win95') !== FALSE)
        return 'Windows 95';
    elseif(strpos($user_agent, 'WinNT4.0') !== FALSE)
        return 'Windows NT 4.0';
    elseif(strpos($user_agent, 'Windows Phone') !== FALSE)
        return 'Windows Phone';
    elseif(strpos($user_agent, 'Windows') !== FALSE)
        return 'Windows';
    elseif(strpos($user_agent, 'iPhone') !== FALSE)
        return 'iPhone';
    elseif(strpos($user_agent, 'iPad') !== FALSE)
        return 'iPad';
    elseif(strpos($user_agent, 'Debian') !== FALSE)
        return 'Debian';
    elseif(strpos($user_agent, 'Ubuntu') !== FALSE)
        return 'Ubuntu';
    elseif(strpos($user_agent, 'Slackware') !== FALSE)
        return 'Slackware';
    elseif(strpos($user_agent, 'Linux Mint') !== FALSE)
        return 'Linux Mint';
    elseif(strpos($user_agent, 'Gentoo') !== FALSE)
        return 'Gentoo';
    elseif(strpos($user_agent, 'Elementary OS') !== FALSE)
        return 'ELementary OS';
    elseif(strpos($user_agent, 'Fedora') !== FALSE)
        return 'Fedora';
    elseif(strpos($user_agent, 'Kubuntu') !== FALSE)
        return 'Kubuntu';
    elseif(strpos($user_agent, 'Linux') !== FALSE)
        return 'Linux';
    elseif(strpos($user_agent, 'FreeBSD') !== FALSE)
        return 'FreeBSD';
    elseif(strpos($user_agent, 'OpenBSD') !== FALSE)
        return 'OpenBSD';
    elseif(strpos($user_agent, 'NetBSD') !== FALSE)
        return 'NetBSD';
    elseif(strpos($user_agent, 'SunOS') !== FALSE)
        return 'Solaris';
    elseif(strpos($user_agent, 'BlackBerry') !== FALSE)
        return 'BlackBerry';
    elseif(strpos($user_agent, 'Android') !== FALSE)
        return 'Android';
    elseif(strpos($user_agent, 'Mobile') !== FALSE)
        return 'Firefox OS';
    elseif(strpos($user_agent, 'Mac OS X+') || strpos($user_agent, 'CFNetwork+') !== FALSE)
        return 'Mac OS X';
    elseif(strpos($user_agent, 'Macintosh') !== FALSE)
        return 'Mac OS Classic';
    elseif(strpos($user_agent, 'OS/2') !== FALSE)
        return 'OS/2';
    elseif(strpos($user_agent, 'BeOS') !== FALSE)
        return 'BeOS';
    elseif(strpos($user_agent, 'Nintendo') !== FALSE)
        return 'Nintendo';
    else
        return 'Unknown Platform';
}
function datefromformat($date, $input_format, $output_format="Y-m-d"){
    $date=DateTime::createFromFormat($input_format, $date);
    if(!$date instanceof DateTime || is_bool($date))
        throw new Exception("Vaya! ocurrio un problema serio en el sistema.<br/>Consulte con el Soporte Tecnico", "Conversion a DateTime is invalid", "--------");
    return $date->format($output_format);
}
function handleWarningAvise($errno, $errstr, $errfile, $errline){
	echo $errno, "<br/>", $errstr, "<br/>", $errfile, "<br/>", $errline;
	die();
	//throw new GException("Vaya! ocurrio un problema en el sistema.<br/>Consulte con el Soporte Tecnico", $errstr, 0, 1, $errfile, $errline);
}
function Ghidden($name_element, $value=''){
	echo '<input type="hidden" name="'.$name_element.'" id="'.$name_element.'" value="'.$value.'" />';
}
function GText($name_element, $value=''){
	echo '<input type="text" name="'.$name_element.'" id="'.$name_element.'" value="'.$value.'" />';
}
function timeInactividad(&$ultimoacceso){
	$ahora=date("Y-n-j H:i:s");
	$tiempo_inactivo=(strtotime($ahora)-strtotime($ultimoacceso));
	$ultimoacceso=$ahora;
	if($tiempo_inactivo>=SEGUNDOS_INACTIVOS){
		$_SESSION['autorizado']=$_SESSION['id_usuario']=$ultimoacceso=NULL;
		session_destroy();
	}
}


function calcular_neto($monto, $mto_impuesto, $excento){
    if($excento=='1' || $mto_impuesto==0.00)
        return $monto;
    return $monto/(1+($mto_impuesto/100));
}
function calcularedad($fec_nac){
	try{
		$hoy=new DateTime('NOW');
		$fecha_nac=new DateTime($fec_nac);
		$dif_date=$hoy->diff($fecha_nac);
		return $dif_date->y;
	}catch(Exception $e){
		echo $e->getOutMsg();
	}
}
function choque_horario($h_actual, $horas_inscribir){
	$choque=false;
	foreach($h_actual as $dia => $horas){
		if(array_key_exists($dia, $horas_inscribir)){
			foreach($horas_inscribir[$dia] as $add_hora)
				if(in_array($add_hora, $h_actual[$dia])){
					$choque=true;
					break 2;
				}	
		}
	}
	return $choque;
}
function HTTPStatus($num){
    $http = array(
        100 => 'HTTP/1.1 100 Continue',
        101 => 'HTTP/1.1 101 Switching Protocols',
		200 => 'HTTP/1.1 200 OK',
        201 => 'HTTP/1.1 201 Created',
        202 => 'HTTP/1.1 202 Accepted',
        203 => 'HTTP/1.1 203 Non-Authoritative Information',
        204 => 'HTTP/1.1 204 No Content',
        205 => 'HTTP/1.1 205 Reset Content',
        206 => 'HTTP/1.1 206 Partial Content',
        300 => 'HTTP/1.1 300 Multiple Choices',
        301 => 'HTTP/1.1 301 Moved Permanently',
        302 => 'HTTP/1.1 302 Found',
        303 => 'HTTP/1.1 303 See Other',
        304 => 'HTTP/1.1 304 Not Modified',
        305 => 'HTTP/1.1 305 Use Proxy',
        307 => 'HTTP/1.1 307 Temporary Redirect',
        400 => 'HTTP/1.1 400 Bad Request',
        401 => 'HTTP/1.1 401 Unauthorized',
        402 => 'HTTP/1.1 402 Payment Required',
        403 => 'HTTP/1.1 403 Forbidden',
        404 => 'HTTP/1.1 404 Not Found',
        405 => 'HTTP/1.1 405 Method Not Allowed',
        406 => 'HTTP/1.1 406 Not Acceptable',
        407 => 'HTTP/1.1 407 Proxy Authentication Required',
        408 => 'HTTP/1.1 408 Request Time-out',
        409 => 'HTTP/1.1 409 Conflict',
        410 => 'HTTP/1.1 410 Gone',
        411 => 'HTTP/1.1 411 Length Required',
        412 => 'HTTP/1.1 412 Precondition Failed',
        413 => 'HTTP/1.1 413 Request Entity Too Large',
        414 => 'HTTP/1.1 414 Request-URI Too Large',
        415 => 'HTTP/1.1 415 Unsupported Media Type',
        416 => 'HTTP/1.1 416 Requested Range Not Satisfiable',
        417 => 'HTTP/1.1 417 Expectation Failed',
        500 => 'HTTP/1.1 500 Internal Server Error',
        501 => 'HTTP/1.1 501 Not Implemented',
        502 => 'HTTP/1.1 502 Bad Gateway',
        503 => 'HTTP/1.1 503 Service Unavailable',
        504 => 'HTTP/1.1 504 Gateway Time-out',
        505 => 'HTTP/1.1 505 HTTP Version Not Supported'
    );
	return (array_key_exists($num, $http))?$http[$num]:$http[404];
}

function checked_json(&$cadena){
    $test=json_encode(utf8_decode($cadena));
    switch(json_last_error()){
        case JSON_ERROR_UTF8:
            $cadena=$cadena;
        break;
        default:
            $cadena=utf8_decode($cadena);
    }
}
function errorMySQL($errno){
    $msg="Error no especificado SQL";
    switch($errno){
        case 1451:
            $msg="El registro esta asociado a otra tabla como clave foranea";
        break;
    }
    return $msg;
}



class EnLetras
{
  var $Void = "";
  var $SP = " ";
  var $Dot = ".";
  var $Zero = "0";
  var $Neg = "Menos";
  
function ValorEnLetras($x, $Moneda ) 
{
    $s="";
    $Ent="";
    $Frc="";
    $Signo="";
        
    if(floatVal($x) < 0)
     $Signo = $this->Neg . " ";
    else
     $Signo = "";
    
    if(intval(number_format($x,2,'.','') )!=$x) //<- averiguar si tiene decimales
      $s = number_format($x,2,'.','');
    else
      $s = number_format($x,2,'.','');
       
    $Pto = strpos($s, $this->Dot);
        
    if ($Pto === false)
    {
      $Ent = $s;
      $Frc = $this->Void;
    }
    else
    {
      $Ent = substr($s, 0, $Pto );
      $Frc =  substr($s, $Pto+1);
    }

    if($Ent == $this->Zero || $Ent == $this->Void)
       $s = "Cero ";
    elseif( strlen($Ent) > 7)
    {
       $s = $this->SubValLetra(intval( substr($Ent, 0,  strlen($Ent) - 6))) . 
             "Millones " . $this->SubValLetra(intval(substr($Ent,-6, 6)));
    }
    else
    {
      $s = $this->SubValLetra(intval($Ent));
    }

    if (substr($s,-9, 9) == "Millones " || substr($s,-7, 7) == "Mill¨®n ")
       $s = $s . "de ";

    $s = $s . " CON ";

    if($Frc != $this->Void)
    {
       $s = $s . " " . $Frc. "/100";
       //$s = $s . " " . $Frc . "/100";
    }
    $letrass=$Signo . $s . " SOLES.";
    return ($Signo . $s . " SOLES.");
   
}


function SubValLetra($numero) 
{
    $Ptr="";
    $n=0;
    $i=0;
    $x ="";
    $Rtn ="";
    $Tem ="";

    $x = trim("$numero");
    $n = strlen($x);

    $Tem = $this->Void;
    $i = $n;
    
    while( $i > 0)
    {
       $Tem = $this->Parte(intval(substr($x, $n - $i, 1). 
                           str_repeat($this->Zero, $i - 1 )));
       If( $Tem != "Cero" )
          $Rtn .= $Tem . $this->SP;
       $i = $i - 1;
    }

    
    //--------------------- GoSub FiltroMil ------------------------------
    $Rtn=str_replace(" Mil Mil", " Un Mil", $Rtn );
    while(1)
    {
       $Ptr = strpos($Rtn, "Mil ");       
       If(!($Ptr===false))
       {
          If(! (strpos($Rtn, "Mil ",$Ptr + 1) === false ))
            $this->ReplaceStringFrom($Rtn, "Mil ", "", $Ptr);
          Else
           break;
       }
       else break;
    }

    //--------------------- GoSub FiltroCiento ------------------------------
    $Ptr = -1;
    do{
       $Ptr = strpos($Rtn, "Cien ", $Ptr+1);
       if(!($Ptr===false))
       {
          $Tem = substr($Rtn, $Ptr + 5 ,1);
          if( $Tem == "M" || $Tem == $this->Void)
             ;
          else          
             $this->ReplaceStringFrom($Rtn, "Cien", "Ciento", $Ptr);
       }
    }while(!($Ptr === false));

    //--------------------- FiltroEspeciales ------------------------------
    $Rtn=str_replace("Diez Un", "Once", $Rtn );
    $Rtn=str_replace("Diez Dos", "Doce", $Rtn );
    $Rtn=str_replace("Diez Tres", "Trece", $Rtn );
    $Rtn=str_replace("Diez Cuatro", "Catorce", $Rtn );
    $Rtn=str_replace("Diez Cinco", "Quince", $Rtn );
    $Rtn=str_replace("Diez Seis", "Dieciseis", $Rtn );
    $Rtn=str_replace("Diez Siete", "Diecisiete", $Rtn );
    $Rtn=str_replace("Diez Ocho", "Dieciocho", $Rtn );
    $Rtn=str_replace("Diez Nueve", "Diecinueve", $Rtn );
    $Rtn=str_replace("Veinte Un", "Veintiun", $Rtn );
    $Rtn=str_replace("Veinte Dos", "Veintidos", $Rtn );
    $Rtn=str_replace("Veinte Tres", "Veintitres", $Rtn );
    $Rtn=str_replace("Veinte Cuatro", "Veinticuatro", $Rtn );
    $Rtn=str_replace("Veinte Cinco", "Veinticinco", $Rtn );
    $Rtn=str_replace("Veinte Seis", "Veintiseis", $Rtn );
    $Rtn=str_replace("Veinte Siete", "Veintisiete", $Rtn );
    $Rtn=str_replace("Veinte Ocho", "Veintiocho", $Rtn );
    $Rtn=str_replace("Veinte Nueve", "Veintinueve", $Rtn );

    //--------------------- FiltroUn ------------------------------
    If(substr($Rtn,0,1) == "M") $Rtn = $Rtn;
    //--------------------- Adicionar Y ------------------------------
    for($i=65; $i<=88; $i++)
    {
      If($i != 77)
         $Rtn=str_replace("a " . Chr($i), "* y " . Chr($i), $Rtn);
    }
    $Rtn=str_replace("*", "a" , $Rtn);
    return($Rtn);
}


function ReplaceStringFrom(&$x, $OldWrd, $NewWrd, $Ptr)
{
  $x = substr($x, 0, $Ptr)  . $NewWrd . substr($x, strlen($OldWrd) + $Ptr);
}


function Parte($x)
{
    $Rtn='';
    $t='';
    $i='';
    Do
    {
      switch($x)
      {
         Case 0:  $t = "Cero";break;
         Case 1:  $t = "Un";break;
         Case 2:  $t = "Dos";break;
         Case 3:  $t = "Tres";break;
         Case 4:  $t = "Cuatro";break;
         Case 5:  $t = "Cinco";break;
         Case 6:  $t = "Seis";break;
         Case 7:  $t = "Siete";break;
         Case 8:  $t = "Ocho";break;
         Case 9:  $t = "Nueve";break;
         Case 10: $t = "Diez";break;
         Case 20: $t = "Veinte";break;
         Case 30: $t = "Treinta";break;
         Case 40: $t = "Cuarenta";break;
         Case 50: $t = "Cincuenta";break;
         Case 60: $t = "Sesenta";break;
         Case 70: $t = "Setenta";break;
         Case 80: $t = "Ochenta";break;
         Case 90: $t = "Noventa";break;
         Case 100: $t = "Cien";break;
         Case 200: $t = "Doscientos";break;
         Case 300: $t = "Trescientos";break;
         Case 400: $t = "Cuatrocientos";break;
         Case 500: $t = "Quinientos";break;
         Case 600: $t = "Seiscientos";break;
         Case 700: $t = "Setecientos";break;
         Case 800: $t = "Ochocientos";break;
         Case 900: $t = "Novecientos";break;
         Case 1000: $t = "Mil";break;
         Case 2000: $t = "Dos Mil";break;
         Case 3000: $t = "Tres Mil";break;
         Case 4000: $t = "Cuatro Mil";break;
         Case 5000: $t = "Cinto Mil";break;
         Case 6000: $t = "Seis Mil";break;
         Case 7000: $t = "Siete Mil";break;
         Case 8000: $t = "Ocho Mil";break;
         Case 9000: $t = "Nuevo Mil";break;
         Case 1000000: $t = "Mill¨®n";break;
      }

      If($t == $this->Void)
      {
        $i = $i + 1;
        $x = $x / 1000;
        If($x== 0) $i = 0;
      }
      else
         break;
           
    }while($i != 0);
   
    $Rtn = $t;
    Switch($i)
    {
       Case 0: $t = $this->Void;break;
       Case 1: $t = " Mil";break;
       Case 2: $t = " Millones";break;
       Case 3: $t = " Billones";break;
    }
    return($Rtn . $t);
}

}

?>