<?php
require_once('aplicacion.php');


// Controlador::loadModule('Captcha');

class Contacto extends Aplicacion
{

    /**
     * Contiene la carga de los campos extra recibidos desde el formulario
     * @var type 
     */
    public $extra;
    private $limite_campos_extra;
    private $sendEmails;

    /**
     * 
     * @param type $archivo Debe encontrarse en "modulos" o "__template__/overwrite/view/modulos"
     * @param type $limite_campos_extra
     * @param type $sendEmails
     */
    function execute($archivo = 'contacto.php', $limite_campos_extra = 0, $sendEmails = array())
    {



        include_once('../model/contacto_insercion.php');
        include_once('../mailer/mailsmtp.php');
        include_once('../epanel/model/popup.class.php');
        include_once('../model/apartados_idiomas.php');
        include_once('../model/Control_Spam.php');

        //Formularios con campos extras, se definen los campos extras para que no se envien mas de lo normal
        $this->limite_campos_extra = $limite_campos_extra;
        //Envio de emails a otras cuentas
        $this->sendEmails = $sendEmails;





        if (isset($_POST['submit_contacto'])) {
            // Intenta enviar el email



            $this->enviar_mail();
        } else {
            // Carga los datos por defecto
            $this->show_default();
        }

        // Carga los datos
        $this->carga_datos();
        $this->show_contacta = true;
        // include Controlador::toIncludeFromPlantilla('modulos/' . $archivo);
    }




    function carga_datos()
    {
        // Cargara los datos a mostrar en la web

        if ($_POST) {
            $this->nombre = Controlador::ValorPost('nombre');
            // $this->empresa = Controlador::ValorPost('empresa');
            $this->email = Controlador::ValorPost('email');
            $this->telefono = Controlador::ValorPost('telefono');
            $this->localidad = Controlador::ValorPost('localidad');
            $this->motivo = Controlador::ValorPost('motivo');
            if ($this->motivo = "")
                $this->motivo = Controlador::ValorPost('observaciones');
            $this->extra = Controlador::ValorPost('extra', false, array());
        } else {
            // Intentamos cargar los datos del cliente
            if (isset($_SESSION['cliente_id']) and $_SESSION['cliente_id'] > 0) {
                // Cargamos el usuario para sacar sus datos
                include_once dir_app . 'model/clientes.php';
                $cliente = ClientesMapper::getById($_SESSION['cliente_id']);
            }

            $this->empresa = '';
            if (!isset($cliente->id) or $cliente->id != $_SESSION['cliente_id']) {
                // No hay cliente...
                $this->nombre = '';
                $this->email = '';
                $this->telefono = '';
            } else {
                $this->nombre = $cliente->nombre . ' ' . $cliente->apellidos;
                $this->email = ($cliente->email != '') ? $cliente->email : $cliente->user;
                $this->telefono = $cliente->telefono;
            }
        }
    }

    // function show_default()
    // {
    //     // Preparamos el campo del motivo si fuera necesario

    //     $this->showFromPlantillaContacto('contacto.php'); // no funciona si se pone contacto

    // }


    function show_default()
    {
        // Preparamos el campo del motivo si fuera necesafrio
        $this->showFromPlantilla('newsletter.php');
        //  $this->masInformacion();    
        // echo "<div class='alert alert-primary' role='alert'>Se acaba de suscribir correctamente a nuestra Newsletter</div>";
        echo "<script>";
        echo " let prevUrl = document.referrer;";
        echo "if (prevUrl.indexOf(window.location.host) !== -1) {"; //volvemos a la pagina que estamos -1
        echo "setTimeout(delay, 4000);"; //creamos la funcion para que recoja el tiempod el delay
        echo "function delay() {"; //llamamos a la función
        // echo "window.history.back();"; //vamos a la pagina web anterior despues de 4 segundos
        if ($_SESSION['idioma'] == 'es') {
            echo "window.location.replace('http://185.136.89.171/plesk-site-preview/instalacioneslara.es/https/185.136.89.171/es/proyecto/499-instalaciones-lara---contacto/')";
        } else {
            echo "window.location.replace('http://185.136.89.171/plesk-site-preview/instalacioneslara.es/https/185.136.89.171/ca/proyecto/499-instalaciones-lara---contacto/')";
        }

        echo "}";
        echo "     }  </script>       ";
    }

    /**
     * Cargamos los datos del boton "mas informacion"
     */
    function masInformacion()
    {
        if (Controlador::ValorPost('motivo') == '') {
            $idShow = Controlador::ValorGet('sid');
            $type = Controlador::valorGet('type');

            if ($idShow) {
                switch ($type) {
                    case 'producto':
                        $producto = ProductosMapper::getByID($idShow, false, true);
                        if (isset($producto->id) and $producto->nombre != '')
                            $motivo = 'Producto ID: ' . $producto->id . ' Nombre: ' . $producto->nombre;
                        break;

                    case 'proyecto':
                        $proyecto = ProyectosProductosMapper::getByID($idShow, true, true);
                        if (isset($proyecto['id']))
                            $motivo = $proyecto['nombre'] . ' (ID ' . $proyecto['id'] . ')';
                        break;

                    case 'apartado':
                    default:
                        // El apartado no puede ser el de contacto
                        if (Controlador::ValorGet('id') != $idShow) {
                            $apartado = ApartadosIdiomasMapper::getByIdIdioma($idShow, true, true);
                            if (isset($apartado->id))
                                $motivo = $apartado->titulo . ' (ID ' . $apartado->id . ')';
                        }
                }

                // Sobreescribimos el motivo
                if (isset($motivo) and $motivo != '')
                    $this->motivo = Controlador::htmlDecode(LANG_SOLICITO_EN_CONTACTO . $motivo) . "\n\n";
            }
        }
    }


    //empezamos la funcion tiene_spam para saber si el usuario ha introducido en el campo motivo alguna palabra que hemos añadido usandoelepanel 
    function tiene_Spam($motiv)
    {
        //recuperamos todos los motes prohibidos 
        $Listado_Mote_Spam = ControlSpamMapper::getAll();
        // var_dump($Listado_Mote_Spam);  
        $i = 0;
        foreach ($Listado_Mote_Spam as $item) { //Recorro todo el contenido de mi arreglo
            // echo '<br> motiv: '. $motiv;
            $pro = $Listado_Mote_Spam[$i]->MoteSpam; //capturo el valor actual del array.
            // echo '<br>posicion 0'. $i.' palabra '.$pro;
            $cadena_buscada   = 0;
            $position = strpos($motiv, $Listado_Mote_Spam[$i]->MoteSpam); // strpos primer parametro contiene el texto introducido) y el segundo parametre son los textos a buscar(motespam)
            if ($position === false) {
                // echo 'devuleve false';
                // echo 'palabara no encontrada';
                $cadena_buscada   = 0;
            } else { // Si encuentro coincidencias, capturo la palabra y mi variable y cierro el bucle
                // $palabra = $Listado_Mote_Spam[$i]->MoteSpam;
                $cadena_buscada = 1;
                return true;
            }
            $i++;
        };

        //se comprube si se ha encontrado el SPAM
        if ($cadena_buscada == 1) {
            return true;
        } else {
            return false;
        }
    }


    function enviar_mail()
    {



        //Buscamos si han enviado una url para descartar el contacto

        if (prohibir_enlace_contacto) {
            $contiene_web = preg_replace("/((http|https|www)[^\s]+)/", 'no_enviar_ERROR_contiene_enlace', $_POST['motivo']);
            $contiene_web_enlace = preg_replace("/((http|https|www)[^\s]+)/", 'no_enviar_ERROR_contiene_enlace', $_POST['nombre']);
            $contiene_web_enlace_localidad = preg_replace("/((http|https|www)[^\s]+)/", 'no_enviar_ERROR_contiene_enlace', $_POST['localidad']);
            // var_dump($_POST); Para mirar todos los POSTS




            if ($contiene_web != Controlador::ValorPost('motivo') ||  $contiene_web_enlace  != Controlador::ValorPost('nombre') ||  $contiene_web_enlace_localidad != Controlador::ValorPost('localidad')) {
                $this->mensaje = 'Mensaje no enviado, no introduzca direcciones web en los comentarios';
                $this->error = true;
                $this->show_default();
                return;
            }
        }


        if ($_POST['telefono'][0] == 8) {
            'no deja enviar';
            $this->mensaje = 'No introduzca un teléfono que empiece por 8';
            $this->error = true;
            $this->show_default();
            return;
        }




        //Comprobamos si hay alguna palabra SPAM en el MOTIVO
        //igualamos la funcion a una variable que en este caso es $spam y miramos que nos ha introducido el usuario 
        //si ha utilizado algun moteprohibido (que hemos añadido mediante el epanel se le inidicara con un mensaje
        //tambien se genera un log para saber cuando lo ha introducido (fecha)
        //sino tiene spam enviaremos el mensaje.
        $spam = $this->tiene_Spam(Controlador::ValorPost('motivo'));


        if ($spam == true) {




            function save_file()
            {
                $GenerarFicheroSpam = '<?php
            // 22022 ESTE ES UN ARCHIVO AUTOGENERADO DESDE EL PANEL
            // SI ANADES COSAS Y LO ACTUALIZAS DESDE EL PANEL, SERAN ELIMINADAS' . PHP_EOL;

                //miramos que nos devuelve el POST de los controladores
                $motivo =  Controlador::ValorPost('motivo');



                $fechaActual = date('d-m-YH:i:s');
                $GenerarFicheroSpam .= 'define(\'' . $fechaActual . ' ' . 'Mensaje no permitido:' . '\', ' . $motivo . ');' . PHP_EOL;

                // Finalizamos y guardamos el archivo
                $GenerarFicheroSpam .= '?>';
                echo $GenerarFicheroSpam;
                @mkdir('../config/');
                @chmod('../config/', 0777);
                return file_put_contents('../log/form_contactos/' . $fechaActual . ".txt", $GenerarFicheroSpam);
            }




            save_file();
            $this->mensaje = LANG_MENSAJE_ENVIADO;
            $this->error = true;
            $this->show_default();
            return;
        }




        //RECOGEMOS LA IP 
        function get_client_ip()
        {
            $ipaddress = '';
            if (getenv('HTTP_CLIENT_IP'))
                $ipaddress = getenv('HTTP_CLIENT_IP');
            else if (getenv('HTTP_X_FORWARDED_FOR'))
                $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
            else if (getenv('HTTP_X_FORWARDED'))
                $ipaddress = getenv('HTTP_X_FORWARDED');
            else if (getenv('HTTP_FORWARDED_FOR'))
                $ipaddress = getenv('HTTP_FORWARDED_FOR');
            else if (getenv('HTTP_FORWARDED'))
                $ipaddress = getenv('HTTP_FORWARDED');
            else if (getenv('REMOTE_ADDR'))
                $ipaddress = getenv('REMOTE_ADDR');
            else
                $ipaddress = 'UNKNOWN';
            return $ipaddress;
        }



        $datos = array(
            'nombre' => Controlador::ValorPost('nombre'),
            'email' => Controlador::ValorPost('email'),
            'telefono' => Controlador::ValorPost('telefono'),
            'localidad' =>  Controlador::ValorPost('localidad'),
            'motivo' => Controlador::ValorPost('motivo'),
            'alegal' => Controlador::ValorPost('alegal', true),
            'extra' => Controlador::ValorPost('extra'),
            'telefonocliente' => Controlador::ValorPost('telefonocliente'),
        );


          //SI NOS HAN INTRODUCIDO EL TELEFONO SE LE GUARDARA EL CAMPO EN UN TXT
          if ($datos['telefonocliente'] != "") {
            // GENERAMOS EL FCIHERO PARA GUARDAR EL LOG
            function save_file()
            {
                $GenerarFicheroSpam = '<?php
            // 22022 ESTE ES UN ARCHIVO AUTOGENERADO DESDE EL PANEL
            // SI ANADES COSAS Y LO ACTUALIZAS DESDE EL PANEL, SERAN ELIMINADAS' . PHP_EOL;

                //IGUALAMOS EL CAMPO TELEFONO COMO LA IP 
                $telefonocliente =   get_client_ip();



                $fechaActual = date('d-m-YH:i:s');
                $GenerarFicheroSpam .= 'define(\'' . $fechaActual . ' ' . 'IP no permitido:' . '\', ' . $telefonocliente . ');' . PHP_EOL;

                // Finalizamos y guardamos el archivo
                $GenerarFicheroSpam .= '?>';
                echo $GenerarFicheroSpam;
                @mkdir('../config/');
                @chmod('../config/', 0777);
                return file_put_contents('../log/form_contactoapartado/' . $fechaActual . ".txt", $GenerarFicheroSpam);
            }




            save_file();
            $this->mensaje = LANG_MENSAJE_ENVIADO;
            $this->error = true;
            $this->show_default();
            return;
        }

        //DESDE LA VISTA YA SE VERIFICA SI LOS DATOS ESTÁN VACÍOS, ESTA VERIFICACIÓN NO HARÍA FALTA AUNQU NO ESTÁ DE MÁS.
        if ($datos['nombre'] != "" && $datos['email'] != "" && $datos['telefono'] != ""  && $datos['alegal'] != "" && $datos['telefonocliente'] == "" ) {


            $dtoContacto = new ContactoInsercionDTO();

            $dtoContacto->nombre = Controlador::ValorPost('nombre');
            $dtoContacto->telefono = Controlador::ValorPost('telefono');
            $dtoContacto->localidad = Controlador::ValorPost('localidad');
            $dtoContacto->email = Controlador::ValorPost('email');
            $dtoContacto->motivo = Controlador::ValorPost('motivo');
            $dtoContacto->recibir_informacion = Controlador::ValorPost('aceptar_recibir_informacion');
            $dtoContacto->fecha_hora = date('Y-m-d H:i');
            $dtoContacto->idioma = $_SESSION['idioma'];

            if (strpos($dtoContacto->motivo, 'http://')) {
                // echo 'texto capturado';
                die();
            } elseif (strpos($dtoContacto->motivo, 'https://')) {
                // echo 'texto capturado2';
                die();
            } else {




                // Enviamos el email a los administradores
                //enviaMailConPlantilla(LANG_CONTACTAR, 'contacto', $datos, array(), array(), $attatched);
                //Envio email extra definidos manualmente
                //enviaMailConPlantilla(LANG_CONTACTAR, 'contacto', $datos, array(), array(), $attatched);
                $mailsTMP = array($dtoContacto->email);


                enviaMailConPlantilla(LANG_CONTACTAR, 'contacto', $datos, array(), array(), '', array(), $mailsTMP);



                ContactoInsercionMapper::insert($dtoContacto);


                $this->mensaje = LANG_MENSAJE_ENVIADO;
                define('mensaje', $this->mensaje);



                $this->show_default();
            }
        } else {
            $this->mensaje = LANG_DATOS_INCORRECTOS;
            define('mensaje', $this->mensaje);
            $this->error = true;
            $this->show_default();
        }
    }
}

    $ctrl = new Contacto();
    $ctrl->execute();

