<?php

require_once ('aplicacion.php');
Controlador::loadModule('Captcha');
define('zona', 'newsletter');

class Clientes extends Aplicacion {

    function execute() {
        require_once ('../model/clientes.php');
        require_once ('../model/clientes_en_grupos.php');
        require_once ('../model/grupos_clientes.php');
        include_once ('../mailer/mailsmtp.php');

        if (isset($_POST['add_to_newsletter']) or isset($_POST['mail_newsletter'])) {
            $this->inserta_email($_POST['mail_newsletter'], $_POST['aceptar_condiciones_newsletter']);
        } else if (isset($_REQUEST['activado'])) {
            $this->usuario_activado();
        } elseif (isset($_POST['baja'])) {
            $this->baja($_POST['id'], $_POST['hash'], 1);
        } elseif (isset($_GET['sol']) and $_GET['sol'] == 'baja') {
            $this->baja($_GET['id'], $_GET['hash'], 0);
        } else {
            $this->show_default();
        }

        //$this->show('../view/newsletter.php', true);
        $this->showFromPlantilla('newsletter.php', '', true);
    }

    function createRandomPassword() {

        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";

        srand((double) microtime() * 1000000);

        $i = 0;

        $pass = '';

        while ($i <= 9) {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }

        return $pass;
    }

    function show_default() {
        $this->form_alta = true;
    }

    function mostrar_form_baja() {
        $this->mostrar_form = true;
    }

    /*
      Funciones de insercion
     */

    function inserta_email($email, $condiciones) {
        if (preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email) && $condiciones) {

            /* 
            $attempt = Captcha::checkAttempt('newsletter');

            if ($attempt > 1) {
                $this->mensaje = Captcha::getAttemptError('newsletter');
            } elseif (Captcha::validateCaptcha(Controlador::ValorPost('captcha_newsletter'))) { */
                //$email = date ('YmdHis').'@emosistemas.com';
                $dto = new ClienteDTO();

                $pass = $this->createRandomPassword();
                $dto->user = $email;
                $dto->pass = ClientesMapper::hashPass($pass);
                $dto->nombre = '';
                $dto->apellidos = '';
                $dto->fecha_nacimiento = '';
                $dto->cif = '';
                $dto->id_direccion = 0;
                $dto->telefono = '';
                $dto->movil = '';
                $dto->email = $dto->user;
                $dto->estado = 3;
                $dto->referido = '';
                $dto->consentimiento = 1;

                $exist = ClientesMapper::getByUser($dto->user);

                if (!$exist) {
                    $dto->id = ClientesMapper::insert($dto);
                } else {
                    $dto = $exist;
                }
                
                // Lo ponemos en el grupo No Registrados
                $aGrupo = Controlador::ValorGet('grupo');
                if ($aGrupo) {
                    $grupo = GruposClientesMapper::getByID($aGrupo);
                    if (!isset($grupo->id) or !$grupo->suscribible_desde_newsletter) $aGrupo = false;
                }
                
                if (!$aGrupo) $aGrupo = 2;
                
                // Comprobamos si ya existe en el grupo
                $enGrupo = ClientesEnGruposMapper::getByIDyCliente($aGrupo, $dto->id);

                if (!isset($enGrupo->id)) {
                    $tmp = new ClientesEnGruposDTO();
                    $tmp->id_cliente = $dto->id;
                    $tmp->id_grupo = $aGrupo;
                    ClientesEnGruposMapper::insert($tmp);

                    $this->enviar_mail($email, 0); // Enviamos email de alta
                    $this->mensaje = EMAIL_SUSCRITO_CORRECTAMENTE;
                    //header('Location: '.Aplicacion::dourl('catalogo.php?seccion=catalogo&mi_cesta=true','1'));                    
                } else {
                    $this->mensaje = ERROR_EMAIL_YA_EXISTE;
                }
            } else {
                $this->mensaje = ERROR_DATOS_INCORRECTOS;
                $this->show_default();
            }

            // ! Email correcto
        /*} else {
            $this->mensaje = ERROR_NEWSLETTER_DIRECCION_CONDICIONES;
            $this->show_default();
        }
        */
    }

    function baja($user, $hash, $paso = 0) {
        /*
          PASO:
          0: Mostrar formulario
          1: Dar de baja
         */

        $cliente = ClientesMapper::getByUserAndPass($user, $hash); // Cargamos el cliente

        if ($cliente->user == $user and $cliente->pass == $hash) {
            // Usuario comprobado
            if ($cliente->estado == 3) {
                // Es un usuario de NewsLetter

                switch ($paso) {
                    case 0: // Mostramos el formulario
                        $this->mostrar_form_baja();
                        break;

                    case 1: // Damos de baja
                        $this->enviar_mail($user, 1); // Enviamos el email de la baja
                        ClientesMapper::delete($cliente);
                        $this->mensaje = BAJA_EXITOSA;
                        break;
                }
            } else {
                // Usuario Normal
                $this->mensaje = MENSAJE_BAJA_CLIENTES_REGISTRADOS;
            }
        } else {
            // Hash no comprobado
            $this->mensaje = HASH_NO_CERTIFICADO_BAJA;
        }
    }

    /**
     * 
     * @param type $user
     * @param type $tipo 0: Alta | 1: Baja
     */
    function enviar_mail($user, $tipo) {
        // Emails Administradores
        $cliente = ClientesMapper::getByUser($user);

        if ($cliente->user == $user) {

            //$url = http_root."/controladores/registro.php?var=".$cliente->id."&hash=".md5($cliente->nombre.$cliente->apellidos."&idioma=".$_SESSION['idioma']);
            // Preparamos los datos
            switch ($tipo) {
                case 0: // Alta
                    $url_baja = http_controlador . "newsletter.php?sol=baja&id=" . $cliente->user . "&hash=" . $cliente->pass;
                    $asunto = ASUNTO_ALTA_NEWSLETTER;
                    $parametros = array(
                        'cuerpo1' => MENSAJE_MAIL_ALTA_1 . $user . MENSAJE_MAIL_ALTA_2 . '<a href="' . http_root . '">' . http_root . '.</a>' . MENSAJE_MAIL_ALTA_2_2 . '<a href=' . $url_baja . '>' . MENSAJE_MAIL_ALTA_3 . '</a>',
                        'cuerpo2' => MENSAJE_MAIL_ALTA_4
                    );
                    break;

                case 1: // Baja
                    $asunto = ASUNTO_BAJA_NEWSLETTER;
                    $parametros = array(
                        'cuerpo1' => MENSAJE_MAIL_BAJA_1 . $user . MENSAJE_MAIL_BAJA_2,
                    );
                    break;
            }

            // Enviamos los emails
            enviaMailConPlantilla($asunto, 'newsletter', $parametros, $cliente);
        }
    }

}

$ctrl = new Clientes();
$ctrl->execute();
?>
