<?php

class Agenda {

    private $con;
    private $codigo_usuario;
    private $usuarioSession;
    private $nombre;
    private $apellido;
    private $apellido2;
    private $direccion;
    private $poblacion;
    private $provincia;
    private $telefono;
    private $email;
    private $contacto;
    private $organizacion;
    private $nif;
    private $activo;
    private $mostrar;

    private $codigo_awasign_pendientes_firmas;

    public function __construct($con) {
        $this->con = $con;
    }

    public function set_codigo_usuario ($codigo_usuario) {
        $this->codigo_usuario = $codigo_usuario;
        return $this;
    }
    public function get_codigo_usuario () {
        return $this->codigo_usuario;
    }

    public function set_usuario_session ($usuarioSession) {
        $this->usuarioSession = $usuarioSession;
        return $this;
    }
    public function get_usuario_session () {
        return $this->usuarioSession;
    }

    public function set_nombre ($nombre) {
        $this->nombre = $nombre;
        return $this;
    }
    public function get_nombre () {
        return $this->nombre;
    }

    public function set_apellido ($apellido) {
        $this->apellido = $apellido;
    }
    public function get_apellido () {
        return $this->apellido;
    }

    public function set_apellido2 ($apellido2) {
        $this->apellido2 = $apellido2;
    }
    public function get_apellido2 () {
        return $this->apellido2;
    }

    public function set_direccion ($direccion) {
        $this->direccion = $direccion;
    }
    public function get_direccion () {
        return $this->direccion;
    }

    public function set_poblacion ($poblacion) {
        $this->poblacion = $poblacion;
    }
    public function get_poblacion () {
        return $this->poblacion;
    }

    public function set_provincia ($provincia) {
        $this->provincia = $provincia;
    }
    public function get_provincia () {
        return $this->provincia;
    }

    public function set_telefono ($telefono) {
        $this->telefono = $telefono;
    }
    public function get_telefono () {
        return $this->telefono;
    }

    public function set_email ($email) {
        $this->email = $email;
    }
    public function get_email () {
        return $this->email;
    }

    public function set_tipo_contacto ($contacto) {
        $this->contacto = $contacto;
    }
    public function get_tipo_contacto () {
        return $this->contacto;
    }

    public function set_tipo_organizacion ($organizacion) {
        $this->organizacion = $organizacion;
    }
    public function get_tipo_organizacion () {
        return $this->organizacion;
    }

    public function set_nif ($nif) {
        $this->nif = $nif;
    }
    public function get_nif () {
        return $this->nif;
    }

    public function set_activo ($activo) {
        $this->activo = $activo;
    }
    public function get_activo () {
        return $this->activo;
    }

    public function set_mostrar ($mostrar) {
        $this->mostrar = $mostrar;
    }
    public function get_mostrar () {
        return $this->mostrar;
    }

    public function set_codigo_awasign_pendientes_firmas ($codigo_awasign_pendientes_firmas) {
        $this->codigo_awasign_pendientes_firmas = $codigo_awasign_pendientes_firmas;
        return $this;
    }
    public function get_codigo_awasign_pendientes_firmas () {
        return $this->codigo_awasign_pendientes_firmas;
    }

    public function select_relaciones_contactos_grupos ($id, $label, $alias, $selected = NULL, $required = NULL) {
        global $sin_asignar_lg;
        global $campo_obligatorio_lg;
        $sql = "SELECT CODIGOCON FROM ETIQUETAS_GRUPOS WHERE ALIAS = '$alias'";
        $res = $this->con->query($sql);
        $fila = $res->fetch_array();
        $codigo = $fila['CODIGOCON'];
        $sql = "SELECT C.CODIGO, C.MOSTRAR
        FROM CONTACTOS C
        INNER JOIN CONTACTOS_RELACIONES R ON R.CONTACTO = C.CODIGO 
        WHERE R.GRUPO = $codigo";
        $res = $this->con->query($sql);
        $html = '<label for="' . $id . '">' . $label . '</label>';
        $html .= '<select class="custom-select" id="' . $id . '" name="' . $id . '" ' . $required . '>';
            if($res->num_rows) {
                $html .= '<option value="">' . $sin_asignar_lg . '</option>';
                while($fila = $res->fetch_array())
                {
                    $select = $selected == $fila['CODIGO'] ? 'selected' : '';
                    $html .= '<option value="' . $fila['CODIGO'] . '" ' . $select . '>' . $fila['MOSTRAR'] . '</option>';
                }
            } else {
                $html .= '<option value="">' . $sin_asignar_lg . '</option>';
            }
        $html .= '</select>';
        $html .= '<div class="invalid-tooltip">' . $campo_obligatorio_lg . '</div>';
        return $html;
    }

    public function grupos_agenda () {
        $html = '';
        $n = 0;
        $contacto = $this->get_codigo_usuario();
        if($contacto) {
            $sql = "SELECT G.*, R.* 
            FROM CONTACTOS_GRUPOS G 
            LEFT JOIN CONTACTOS_RELACIONES R ON G.CODIGO = R.GRUPO AND R.CONTACTO = $contacto 
            WHERE G.CODIGO <> -2 AND G.CODIGO <> 0 ORDER BY DESCRIPCION ASC";
            $res = $this->con->query($sql);
            while($fila = $res->fetch_array()){
                $n++;
                $checked = $fila['GRUPO'] != NULL ? 'checked' : '';
                $html .= '<div class="custom-control custom-checkbox col-sm-6 col-md-3">';
                    $html .= '<input type="checkbox" name="contacto_grupo[]" class="custom-control-input" id="check' . $n . '" value="' . $fila['CODIGO'] . '" ' . $checked . '>';
                    $html .= '<label class="custom-control-label" for="check' . $n . '">' .  $fila['DESCRIPCION'] . '</label>';
                $html .= '</div>';
            }
        } else {
            $sql = "SELECT G.* FROM CONTACTOS_GRUPOS G WHERE G.CODIGO <> -2 AND G.CODIGO <> 0 ORDER BY DESCRIPCION ASC";
            $res = $this->con->query($sql);
            while($fila = $res->fetch_array()){
                $n++;
                $html .= '<div class="custom-control custom-checkbox col-sm-6 col-md-3">';
                    $html .= '<input type="checkbox" name="contacto_grupo[]" class="custom-control-input" id="check' . $n . '" value="' . $fila['CODIGO'] . '">';
                    $html .= '<label class="custom-control-label" for="check' . $n . '">' .  $fila['DESCRIPCION'] . '</label>';
                $html .= '</div>';
            }
        }
        return $html;
    }

    public function insert_contacto () {
        $Schema = new Schema($this->con);
        $now = date('Y-m-d H:i:s');
        $codigo_usuario = $this->get_codigo_usuario();
        $usuarioSession = $this->get_usuario_session();
        $tipo_contacto = $this->get_tipo_contacto();
        $tipo_organizacion = $this->get_tipo_organizacion();
        $nombre = $this->get_nombre();
        $apellido = $this->get_apellido();
        $apellido2 = $this->get_apellido2();
        $nif = $this->get_nif();
        $mostrar = $nombre . " " . $apellido . " " . $apellido2;
        $direccion = $this->get_direccion();
        $poblacion = $this->get_poblacion();
        $provincia = $this->get_provincia();
        $telefono = $this->get_telefono();
        $email = $this->get_email();
        $res = $Schema->executeQuery('SELECT CODIGO FROM CONTACTOS WHERE EMAIL1 = ?', 's', [$email]);
        if(!$res->num_rows) {
            $sql = 'INSERT INTO CONTACTOS(CODIGO, USUARIO, ACTIVO, NOMBRE, APELLIDO1, APELLIDO2, NIF, MOSTRAR, DIRECCION_PER, POBLACION_PER, PROVINCIA_PER, TLFNO1, EMAIL1, CONTACTO, ORGANIZACION, ALTA)
            VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
            $Schema->executeQuery($sql, 'isissssssssisiis', [$codigo_usuario, $usuarioSession, 1, $nombre, $apellido, $apellido2, $nif, $mostrar, $direccion, $poblacion, $provincia, $telefono, $email, $tipo_contacto, $tipo_organizacion, $now]);
            return TRUE;
        }
        return FALSE;
    }

    public function update_contacto () {
        $Schema = new Schema($this->con);
        $codigo_usuario = $this->get_codigo_usuario();
        $activo = $this->get_activo();
        $condition = '';
        $type = 'i';
        $values = [$activo];

        if(isset($this->nombre)) {
            $condition .= ', NOMBRE = ?';
            $type .= 's';
            array_push($values, $this->get_nombre());
        }
        if(isset($this->apellido)) {
            $condition .= ', APELLIDO1 = ?';
            $type .= 's';
            array_push($values, $this->get_apellido());
        }
        if(isset($this->apellido2)) {
            $condition .= ', APELLIDO2 = ?';
            $type .= 's';
            array_push($values, $this->get_apellido2());
        }
        if(isset($this->nif)) {
            $condition .= ', NIF = ?';
            $type .= 's';
            array_push($values, $this->get_nif());
        }
        if(isset($this->mostrar)) {
            $condition .= ', MOSTRAR = ?';
            $type .= 's';
            array_push($values, $this->get_mostrar());
        }
        if(isset($this->direccion)) {
            $condition .= ', DIRECCION_PER = ?';
            $type .= 's';
            array_push($values, $this->get_direccion());
        }
        if(isset($this->poblacion)) {
            $condition .= ', DIRECCION_PER = ?';
            $type .= 's';
            array_push($values, $this->get_poblacion());
        }
        if(isset($this->provincia)) {
            $condition .= ', PROVINCIA_PER = ?';
            $type .= 's';
            array_push($values, $this->get_provincia());
        }
        if(isset($this->provincia)) {
            $condition .= ', PROVINCIA_PER = ?';
            $type .= 's';
            array_push($values, $this->get_provincia());
        }
        if(isset($this->telefono)) {
            $condition .= ', TLFNO1 = ?';
            $type .= 'i';
            array_push($values, $this->get_telefono());
        }
        if(isset($this->email)) {
            $condition .= ', EMAIL1 = ?';
            $type .= 's';
            array_push($values, $this->get_email());
        }
        if(isset($this->email)) {
            $condition .= ', CONTACTO = ?';
            $type .= 'i';
            array_push($values, $this->get_tipo_contacto());
        }
        if(isset($this->organizacion)) {
            $condition .= ', ORGANIZACION = ?';
            $type .= 'i';
            array_push($values, $this->get_tipo_organizacion());
        }

        $condition .= ' WHERE CODIGO = ?';
        $type .= 'i';
        array_push($values, $codigo_usuario);

        $sql = 'UPDATE CONTACTOS SET ACTIVO = ? ' . $condition;
        $Schema->executeQuery($sql, $type, $values);
    }

    public function update_grupo_para_contacto ($grupos) {
        $codigo_usuario = $this->get_codigo_usuario();
        $sqlDelete = "DELETE FROM CONTACTOS_RELACIONES WHERE CONTACTO = ?";
        $stmt = $this->con->prepare($sqlDelete);
        $stmt->bind_param('i', $codigo_usuario);
        $stmt->execute();
        foreach($grupos as $g){
            $g = Statics::SafeInput($this->con, $g);
            $sqlGR = "INSERT INTO CONTACTOS_RELACIONES VALUES(?,?)";
            $stmt = $this->con->prepare($sqlGR);
            $stmt->bind_param('ii', $codigo_usuario, $g);
            $stmt->execute();
        }
    }

    public function select_campo ($campo) {
        $codigo_usuario = $this->get_codigo_usuario();
        $sql = 'SELECT ' . $campo . ' FROM CONTACTOS WHERE CODIGO = ?';
        $stmt = $this->con->prepare($sql);
        $stmt->bind_param('i', $codigo_usuario);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_array();
        return $row[$campo];
    }

    public function get_contacto_data () {
        $Schema = new Schema($this->con);
        $codigo_contacto = $this->get_codigo_usuario();
        $sql = 'SELECT * FROM CONTACTOS WHERE CODIGO = ?';
        $res = $Schema->executeQuery($sql, 'i', [$codigo_contacto]);
        if($res->num_rows) {
            $row = $res->fetch_array();
            return $row;
        } else {
            return FALSE;
        }
    }

    public function insert_awasign_pendientes_firmas () {
        $Schema = new Schema($this->con);

        $now = date('Y-m-d H:i:s');
        $codigo = $this->get_codigo_awasign_pendientes_firmas();
        $usuarioSession = $this->get_usuario_session();
        $expire = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($now)));
        $contacto = $this->get_codigo_usuario();
        $email = $this->get_email();
        $sql = "INSERT INTO AWASIGN_PENDIENTES_FIRMAS(CODIGO, USUARIO, FECHA, CADUCIDAD, CONTACTO, CORREO_DESTINO) VALUES(?,?,?,?,?,?)";
        $Schema->executeQuery($sql, 'ssssis', [$codigo, $usuarioSession, $now, $expire, $contacto, $email]);
    }

    public function select_aseguradora($selected = FALSE) {
        global $sin_asignar_2_lg;
        global $aseguradora_lg;
        $Schema = new Schema($this->con);
        $html = '<label for="tipo_seguro">' . $aseguradora_lg . '</label>';
        $html .= '<div class="form-group"><select class="custom-select" name="aseguradora">';
            $res_aseguradora = $Schema->executeQuery("SELECT CODIGOCON FROM ETIQUETAS_GRUPOS WHERE ALIAS = ?", 's', ['ASEGURADORAS']);
            if($res_aseguradora->num_rows) {
                $row_aseguradora = $res_aseguradora->fetch_array();
                $res_aseguradoras = $Schema->executeQuery('SELECT C.CODIGO, C.MOSTRAR
                FROM CONTACTOS C
                INNER JOIN CONTACTOS_RELACIONES R ON R.CONTACTO = C.CODIGO 
                WHERE R.GRUPO = ?', 'i', [$row_aseguradora['CODIGOCON']]);
                if($res_aseguradoras->num_rows) {
                    while($rows = $res_aseguradoras->fetch_array()) {
                        $select = $rows['CODIGO'] == $selected ? 'selected' : FALSE;
                        $html .= '<option value="' . $rows['CODIGO'] . '" ' . $select . '>' . $rows['MOSTRAR'] . '</option>';
                    }
                }
            } else {
                $html .= '<option value="">' . $sin_asignar_2_lg . '</option>';
            }
        $html .= '</select></div>';
        return $html;
    }
}