<?php
session_start();
$usuarioSession = $_SESSION['USUARIO'];
$grupo = $_SESSION['GRUPO'];
$contacto = $_SESSION['CONTACTO'];
$awa_session_id = $_SESSION['AWA_SESION_ID'];
include('includes/conex.php');
include('includes/eat.php');
include('includes/historial.php');
include('includes/functions.php');
include('includes/esquemas.php');
include('lg/config_vo.php');
if(!isset($usuarioSession) or $awa_session_id != $awa_id)
{
    eatCookies();
    header('Location:index.php');
}
if(isset($_COOKIE['usuario']) AND $_COOKIE['usuario'] != $staticUsu )
{
    eatCookies();
    header('Loction:index.php');
}
if(isset($_COOKIE['idioma']))
{
include('lg/LG_' . $_COOKIE['idioma'] . '.php');
}
else
{
include('lg/LG_SP.php');
}
$key = "";
$variable = "";
$rgpd_key = "";
$rgpd_var = "";
$nombre = htmlspecialchars(mysqli_real_escape_string($con,$_POST['nombre']));
$opcion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['opcion']));
$nif = htmlspecialchars(mysqli_real_escape_string($con,$_POST['nif']));
$email = htmlspecialchars(mysqli_real_escape_string($con,$_POST['email']));
$control = htmlspecialchars(mysqli_real_escape_string($con,$_POST['control']));
$telefono = htmlspecialchars(mysqli_real_escape_string($con,$_POST['telefono']));
$mostrar = $nombre;





if($control == '3d17')
{
    $codigoAgenda = htmlspecialchars(mysqli_real_escape_string($con,$_POST['thisAgenda']));
    $variable .= "NOMBRE = '$nombre',"; 
    $variable .= "EMAIL1 = '$email',"; 
    if($opcion == 0)
    {
        $opcion = 1;
        $variable .= "CONTACTO = $opcion,";
    }
    else
    {   
        $opcion = 1;
        $variable .= "ORGANIZACION = $opcion,";
    }
    if(!empty($_POST['segundo_nombre']))
    {
        $segundo_nombre = htmlspecialchars(mysqli_real_escape_string($con,$_POST['segundo_nombre']));
        $mostrar = $nombre . " " . $segundo_nombre;
        $variable .= "APELLIDO1 = '$segundo_nombre',";
        $variable .= "MOSTRAR = '$mostrar',";
        $key .= "2ºNombre: $segundo_nombre<br>";
    }
    if(!empty($_POST['telefono2']))
    {
        $telefono2 = htmlspecialchars(mysqli_real_escape_string($con,$_POST['telefono2']));
        $variable .= "TLFNO2 = '$telefono2',";
        $key .= "telefono2: $telefono2<br>";
    }
    if(!empty($_POST['email2']))
    {
        $email2 = htmlspecialchars(mysqli_real_escape_string($con,$_POST['email2']));
        $variable .= "EMAIL2 = '$email2',";
        $key .= "email2: $email2<br>";
    }
    if(!empty($_POST['ciudad']))
    {
        $ciudad = htmlspecialchars(mysqli_real_escape_string($con,$_POST['ciudad']));
        $variable .= "PROVINCIA_PER = '$ciudad',";
        $key .= "ciudad: $ciudad<br>";
    }
    if(!empty($_POST['poblacion']))
    {
        $poblacion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['poblacion']));
        $variable .= "POBLACION_PER = '$poblacion',";
        $key .= "poblacion: $poblacion<br>";
    }
    if(!empty($_POST['direccion']))
    {
        $direccion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['direccion']));
        $variable .= "DIRECCION_PER = '$direccion',";
        $key .= "direccion: $direccion<br>";
    }
    if(!empty($_POST['nif']))
    {
        $nif = htmlspecialchars(mysqli_real_escape_string($con,$_POST['nif']));
        $variable .= "NIF = '$nif',";
        $key .= "nif: $nif<br>";
    }
    if(!empty($_POST['relacion']))
    {
        $relacion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['relacion']));
        $key .= "relacion: $relacion<br>";
    }
    if(!empty($_POST['notas']))
    {
        $notas = htmlspecialchars(mysqli_real_escape_string($con,$_POST['notas']));
        $variable .= "NOTAS = '$notas',";
        $key .= "notas: $notas<br>";
    }
    if(!empty($_POST['rgpd']))
    {
        $cero = 0;
        $sql = "UPDATE CONTACTOS SET RGPD_1 = ?, RGPD_2 = ?, RGPD_3 = ?, RGPD_4 = ? WHERE CODIGO = ?";
        $stmt = $con->prepare($sql);
        $stmt->bind_param('iiiii',$cero,$cero,$cero,$cero,$codigoAgenda);
        $stmt->execute();
        for($i = 0; $i < count($_POST['rgpd']); $i++)
        {
            if($_POST['rgpd'][$i] == 1)
            {
                $variable .= "RGPD_1 = " . 1 . ",";
            }
            if($_POST['rgpd'][$i] == 2)
            {
                $variable .= "RGPD_2 = " . 2 . ",";
            }
            if($_POST['rgpd'][$i] == 3)
            {
                $variable .= "RGPD_3 = " . 3 . ",";
            }
            if($_POST['rgpd'][$i] == 4)
            {
                $variable .= "RGPD_4 = " . 4 . ",";
            }
        }
    }
    elseif(empty($_POST['rgpd']))
    {
        $cero = 0;
        $sql = "UPDATE CONTACTOS SET RGPD_1 = ?, RGPD_2 = ?, RGPD_3 = ?, RGPD_4 = ? WHERE CODIGO = ?";
        $stmt = $con->prepare($sql);
        $stmt->bind_param('iiiii',$cero,$cero,$cero,$cero,$codigoAgenda);
        $stmt->execute();
    }
    $variable .= "TLFNO1 = '$telefono',";
    $variable .= "NIF = '$nif'";
    $variable .= " WHERE CODIGO = $codigoAgenda"; 
    $sql = "UPDATE CONTACTOS SET $variable";
    $con->query($sql);


    if(empty($_POST['contacto_grupo']))
    {
        $sqlDelete = "DELETE FROM CONTACTOS_RELACIONES WHERE CONTACTO = ?";
        $stmt = $con->prepare($sqlDelete);
        $stmt->bind_param('i', $codigoAgenda);
        $stmt->execute();
    }
    elseif(!empty($_POST['contacto_grupo']))
    {
        $sqlDelete = "DELETE FROM CONTACTOS_RELACIONES WHERE CONTACTO = ?";
        $stmt = $con->prepare($sqlDelete);
        $stmt->bind_param('i', $codigoAgenda);
        $stmt->execute();

        foreach($_POST['contacto_grupo'] as $contacto_grupo)
        {
            $contacto_grupo = htmlspecialchars(mysqli_real_escape_string($con, $contacto_grupo));
            $sqlGR = "INSERT INTO CONTACTOS_RELACIONES VALUES(?,?)";
            $stmt = $con->prepare($sqlGR);
            $stmt->bind_param('ii', $codigoAgenda, $contacto_grupo);
            $stmt->execute();
        }
    }
    $_SESSION['agenda_m56'] = 2;
    header("Location:agenda.php");
} 
elseif($control == '1n53r7')
{
    

    $sql = "SELECT * FROM CONTACTOS WHERE NIF = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param('s',$nif);
    $stmt->execute();
    $res = $stmt->get_result();
    if($res->num_rows == 0)
    {
        $key .= "TLFNO1,";
        $variable .= "'$telefono',";
        if($opcion == 0)
        {
            $opcion = 1;
            $key .= "CONTACTO,";
            $variable .= "$opcion,";
        }
        else
        {   
            $opcion = 1;
            $key .= "ORGANIZACION,";
            $variable .= "$opcion,";
        }
        if(!empty($_POST['segundo_nombre']))
        {
            $segundo_nombre = htmlspecialchars(mysqli_real_escape_string($con,$_POST['segundo_nombre']));
            $mostrar = $nombre . " " . $segundo_nombre;
            $key .= "APELLIDO1,";
            $variable .= "'$segundo_nombre',";
        }
        if(!empty($_POST['ciudad']))
        {
            $ciudad = htmlspecialchars(mysqli_real_escape_string($con,$_POST['ciudad']));
            $key .= 'PROVINCIA_PER,';
            $variable .= "'$ciudad',";
        }
        if(!empty($_POST['poblacion']))
        {
            $poblacion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['poblacion']));
            $key .= "POBLACION_PER,"; 
            $variable .= "'$poblacion',";
        }
        if(!empty($_POST['direccion']))
        {
            $direccion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['direccion']));
            $key .= "DIRECCION_PER,";
            $variable .= "'$direccion',";
        }
        $key .= "ACTIVO,";
        $variable .= "1,";
        $key .= "EMAIL1,";
        $variable .= "'$email',";
        $tabla ="CONTACTOS";
        $next = max_codigo($con,$tabla);
        if(isset($_POST['rgpd']))
        {
            foreach($_POST['rgpd'] as $p)
            {
                switch($p)
                {
                    case 1:
                        $key .= "RGPD_1,";
                        $variable .= "$p,";
                    break;
                    case 2:
                        $key .= "RGPD_2,";
                        $variable .= "$p,";
                    break;
                    case 3:
                        $key .= "RGPD_3,";
                        $variable .= "$p,";
                    break;
                    case 4:
                        $key .= "RGPD_4,";
                        $variable .= "$p,";
                    break;
                }
            }
        }
        $key .= "NIF";
        $variable .= "'$nif'";
        $sql = "INSERT INTO CONTACTOS(CODIGO,USUARIO,NOMBRE,MOSTRAR,$key) VALUES($next,'$usuarioSession','$nombre','$mostrar',$variable)";
        $con->query($sql);
        if($_POST['btn_action'] == 'crear')
        {

            if(file_exists('tmp_img/firma.jpg'))
            {
                $clave = get_id_unico();
                $entrada = get_id_unico();
                $parte = 1;
                $version = 0;
                $extension = 'JPG';
                $nombreDOC = $mostrar . "-rgpd" . ".jpg";
                $item = 'tmp_img/firma.jpg';
        
                $size = filesize($item);
                $clave_elemento_padre = get_id_unico();
                $clave_elemento_carpeta_contacto = get_id_unico();
        
                if(!alias_biblioteca_elementos($con,'##CN_DOCS##'))
                {
                    crear_elemento($con,$clave_elemento_padre,utf8_decode($carpeta_contacto_doc_lg),NULL,'##PUBLICO##',NULL,'##PUBLICO##/','C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,'##CN_DOCS##');
                }
                else 
                {
                    $clave_elemento_padre = alias_biblioteca_elementos($con,'##CN_DOCS##'); 
                }
                if(!alias_biblioteca_elementos($con,"##CN_DOCS_$next##"))
                {
                    crear_elemento($con,$clave_elemento_carpeta_contacto,utf8_decode($carpeta_contacto_doc_codigo_lg.$next),NULL,$clave_elemento_padre,NULL,"##PUBLICO##/$clave_elemento_padre",'C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,"##CN_DOCS_$next##");
                    $clavePAU = $clave_elemento_carpeta_contacto;
                }
                else
                {
                    $clavePAU = alias_biblioteca_elementos($con,"##CN_DOCS_$next##");
                }
        
                $paramGb = valorParametros($con);
                $padre = $clavePAU;
                $acceso = getPAU($con,$clavePAU)['ACCESO'];
                $ubicacion = getPAU($con,$clavePAU)['UBICACION']. "/" . $clavePAU;
        
                $tipo = 'D';
                $ambito = 'PUB';
                $ordenador = selectOrdenador($con,$usuarioSession); 
        
                $fopen = fopen($item,'r');
                $fread = fread($fopen,filesize($item));
                fclose($fopen);
        
                if(selectTable($con,$database_cnx,$size,$paramGb))
                {
                    $sufijo = selectTable($con,$database_cnx,$size,$paramGb)['SUFIJO'];
                    $table_name = selectTable($con,$database_cnx,$size,$paramGb)['TABLE_NAME'];
                }
                else
                {
                    $sufijo = substr(get_id_unico(),0, 14);
                    $table_name = createTable($con,$sufijo);
                }
        
                insertDocInTable($con,$table_name,$clave,$parte,$version,$fread,$size,$entrada);
                crear_elemento($con,$clave,$nombreDOC,$extension,$padre,$acceso,$ubicacion,$tipo,$size,$ambito,$usuarioSession,$ordenador,$parte,$entrada,$sufijo);

                
        
        
                unlink('tmp_img/firma.jpg');
                
            }
            else
            {
                $clave_elemento_padre = get_id_unico();
                $clave_elemento_carpeta_contacto = get_id_unico();
        
                if(!alias_biblioteca_elementos($con,'##CN_DOCS##'))
                {
                    crear_elemento($con,$clave_elemento_padre,utf8_decode($carpeta_contacto_doc_lg),NULL,'##PUBLICO##',NULL,'##PUBLICO##/','C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,'##CN_DOCS##');
                }
                else 
                {
                    $clave_elemento_padre = alias_biblioteca_elementos($con,'##CN_DOCS##'); 
                }
                if(!alias_biblioteca_elementos($con,"##CN_DOCS_$next##"))
                {
                    crear_elemento($con,$clave_elemento_carpeta_contacto,utf8_decode($carpeta_contacto_doc_codigo_lg.$next),NULL,$clave_elemento_padre,NULL,"##PUBLICO##/$clave_elemento_padre",'C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,"##CN_DOCS_$next##");
                    $clavePAU = $clave_elemento_carpeta_contacto;
                }
                else
                {
                    $clavePAU = alias_biblioteca_elementos($con,"##CN_DOCS_$next##");
                }

            }
            
            $_SESSION['agenda_m56'] = 1;
            header("Location:agenda-nuevo-contacto.php");

        }
        elseif($_POST['btn_action'] == 'pdf')
        {

            $location = __DIR__ .'/ofertas/pdf/';
            require_once __DIR__ . '/vendor/autoload.php';
            $mpdf = new \Mpdf\Mpdf();
            $mpdf->showImageErrors = true;
            $date = date('H:i:s d/m/Y');
            $html = "";
    
            $html .= '<div align="left">';
                $html .= '<img src="img/' . $logo_pdf_vo . '" width="170px">';
            $html .= '</div>';
            $html .= '<br><br>';
            
            $html .= '<div>';
            $html .= '<h3 align="center"><u>' . $justificante_acc_lg . '</u></h2>';
            $html .= '</div>';
    
            $html .= '<h5 align="center">' . $rgpd_lg . '</h5>';
    
            $html .= '<div  style="font-family:Arial;border:2px solid #dddddd;border-radius:5px;background-color:#F5F7F8;padding:10;">';
                $html .= '<div id="body_doc" align="left">';
                    $html .= '<p style="text-align:justify; font-size:14px;">' . $fecha_lg . ': <strong>' . $date . '</strong></p>';
                    $html .= '<p style="text-align:justify; font-size:14px;">' . $nombre_del_receptor_lg . ': <strong>' . $mostrar . '</strong></p>';
                    $html .= '<p style="text-align:justify; font-size:14px;">' . $dni_del_receptor_lg . ': <strong>' . $nif . '</strong></p>';
                    $html .= '<p style="text-align:justify; font-size:14px;">' . $el_nombre_empresa_lg . ': <strong>' . $nombre_concesionario_vo . '</strong></p>';
                $html .= '</div>';
    
            if(file_exists('tmp_img/firma.jpg'))
            {
                $html .= '<div align="center" style="background-color:#FFFFFF;">';
                    $html .= '<img src="tmp_img/firma.jpg" width="200px">';
                $html .= '</div>';
            }
    
            $html .= '</div>';
            $html .= '<br><br><br>';
    
    
            $html .= '<div align="right">';
                $html .= '<small><em>' . $generado_lg . ' ' . $date . '</em></small>';
            $html .= '</div>';
            $mpdf->WriteHTML($html);


            $clave = get_id_unico();
            $entrada = get_id_unico();
            $parte = 1;
            $version = 0;
            $extension = 'PDF';
    
            $nombreDOC = $mostrar . "-rgpd" . ".pdf";
            $item = $location . "" . $mostrar . ".pdf";
            $ruta = $mostrar . "-rgpd" . ".pdf";
            $mpdf->Output($item, "F");
            $mpdf->Output($ruta, "D");
    
            $size = filesize($item);
            $clave_elemento_padre = get_id_unico();
            $clave_elemento_carpeta_contacto = get_id_unico();
    
            if(!alias_biblioteca_elementos($con,'##CN_DOCS##'))
            {
                crear_elemento($con,$clave_elemento_padre,utf8_decode($carpeta_contacto_doc_lg),NULL,'##PUBLICO##',NULL,'##PUBLICO##/','C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,'##CN_DOCS##');
            }
            else 
            {
                $clave_elemento_padre = alias_biblioteca_elementos($con,'##CN_DOCS##'); 
            }
            if(!alias_biblioteca_elementos($con,"##CN_DOCS_$next##"))
            {
                crear_elemento($con,$clave_elemento_carpeta_contacto,utf8_decode($carpeta_contacto_doc_codigo_lg.$next),NULL,$clave_elemento_padre,NULL,"##PUBLICO##/$clave_elemento_padre",'C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,"##CN_DOCS_$next##");
                $clavePAU = $clave_elemento_carpeta_contacto;
            }
            else
            {
                $clavePAU = alias_biblioteca_elementos($con,"##CN_DOCS_$next##");
            }
    
            $paramGb = valorParametros($con);
            $padre = $clavePAU;
            $acceso = getPAU($con,$clavePAU)['ACCESO'];
            $ubicacion = getPAU($con,$clavePAU)['UBICACION']. "/" . $clavePAU;
    
            $tipo = 'D';
            $ambito = 'PUB';
            $ordenador = selectOrdenador($con,$usuarioSession); 
    
            $fopen = fopen($item,'r');
            $fread = fread($fopen,filesize($item));
            fclose($fopen);
    
            if(selectTable($con,$database_cnx,$size,$paramGb))
            {
                $sufijo = selectTable($con,$database_cnx,$size,$paramGb)['SUFIJO'];
                $table_name = selectTable($con,$database_cnx,$size,$paramGb)['TABLE_NAME'];
            }
            else
            {
                $sufijo = substr(get_id_unico(),0, 14);
                $table_name = createTable($con,$sufijo);
            }
    
            insertDocInTable($con,$table_name,$clave,$parte,$version,$fread,$size,$entrada);
            crear_elemento($con,$clave,$nombreDOC,$extension,$padre,$acceso,$ubicacion,$tipo,$size,$ambito,$usuarioSession,$ordenador,$parte,$entrada,$sufijo);
    
    
            eat_all_files("ofertas/pdf/");
            unlink('tmp_img/firma.jpg');


        }

        if(!empty($_POST['contacto_grupo']))
        {
            
            foreach($_POST['contacto_grupo'] as $grupo_contacto)
            {
                $grupo_contacto = htmlspecialchars(mysqli_real_escape_string($con,$grupo_contacto));
                $sqlGR = "INSERT INTO CONTACTOS_RELACIONES VALUES(?,?)";
                $stmt = $con->prepare($sqlGR);
                $stmt->bind_param('ii', $next, $grupo_contacto);
                $stmt->execute();
            }
        }

    }
    else
    {
        $_SESSION['agenda_m56'] = 99;
        header("Location:agenda-nuevo-contacto.php");
    }

}
else
{
    eatCookies();
    header('Location:index.php');
} 

$con->close();

?>