<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    require_once "webService/funciones.php";
    
    //session_start();
    //print_r ($_SESSION);
    
    global $dbh;
    
    class chatAjax extends CI_Controller {
        
        function chatBoxSession($chatbox) {
            global $dbh;
            $items = '';
            
            if (isset($_SESSION['chatHistory'][$chatbox])) {
                $items = $_SESSION['chatHistory'][$chatbox];
            }
            
            return $items;
        }
        
        function startChatSession() {
            global $dbh;
            $items = '';
            if (!empty($_SESSION['openChatBoxes'])) {
                foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
                    $items .= $this->chatBoxSession($chatbox);
                }
            }
            
            
            if ($items != '') {
                $items = substr($items, 0, -1);
            }
            
            header('Content-type: application/json');
            ?>
{
    "username": "<?php echo $_SESSION['username'];?>",
    "items": [
    <?php echo $items;?>
    ]
}

<?php
    exit(0);
    }
    
    public function sendChat() {
        global $dbh;
        $fromName = $_SESSION['username'];
        $from = $_SESSION['user_id'];;
        $toName = $_POST['to'];
        $to = $_POST['toID'];
        $ton= $_POST['to'];
        $message = $_POST['message'];
        $fromId = $_POST['fromId'];
        
        $fecha = date('Y-m-d H:i:s', time());
        
        $cliente = $to . '/' . $fromId;
        
        $_SESSION['openChatBoxes'][$cliente] = $fecha;
        
        if (!isset($_SESSION['chatHistory'][$cliente])) {
            $_SESSION['chatHistory'][$cliente] = '';
        }
        
        //$_SESSION['chatHistory'][$to] .= "{\"s\": \"1\",\"f\": \"{$to}\",\"fn\": \"{$ton}\",\"m\": \"{$messagesan}\"},";
        
        //$_SESSION['chatHistory'][$chat[$to]] .= "{\"cn\": \"{$toName}\",\"s\": \"0\",\"f\": \"{$from}\",\"fn\": \"{$fromName}\",\"m\": \"{$message}\",\"d\": \"{$fecha}\"},";
        
        
        unset($_SESSION['tsChatBoxes'][$cliente]);
        
        //Enviar mensaje push.
        $sqlToken = "SELECT t.* FROM usuario u JOIN token t ON u.id=t.idUsuario WHERE u.id=$to";
        $queryToken = mysqli_query($dbh,$sqlToken);
        $token = "";
        while ($rowToken = mysqli_fetch_array($queryToken)) {
            if ($token != "")
                $token = $token . ",";
            $token = $token . $rowToken['token'];
        }
        
        if ($token != "")
        {
            $x = enviaPush($token, $message, $fromId);
            echo $x;
        }
        
        $message = $this->sanitize($message);
        $message = htmlentities($message);
        
        //$sql = "insert into chat (chat.from,chat.to,message,sent) values ('".mysqli_real_escape_string($dbh,$from)."', '".mysqli_real_escape_string($dbh,$to)."','".mysqli_real_escape_string($dbh,$message)."',NOW())";
        
        $sql = "INSERT INTO chatNvo (usuario, propiedad, mensaje, fecha, leido, envioUsuario) VALUES (".mysqli_real_escape_string($dbh,$to).", ". mysqli_real_escape_string($dbh,$fromId) .", \"" . mysqli_real_escape_string($dbh,$message) . "\", NOW(), 0, 0)";
        $query = mysqli_query($dbh,$sql);
        
        echo "1";
        exit(0);
    }
    
    function closeChat()
    {
        global $dbh;
        unset($_SESSION['openChatBoxes'][$_POST['chatbox']]);
        
        echo "1";
        exit(0);
    }
    
    
    function chatHeartbeat()
    {
        
        //print_r ($_SESSION);
        
        global $dbh;
        //$sql = "select c.*, u.nombre from chat c join usuario u on c.to=u.id where (c.to = '".mysqli_real_escape_string($dbh,$_SESSION['username'])."' AND c.recd = 0) order by c.id ASC";
        
        
        //Se mandan toda la conversación.
        if ((!isset($_SESSION['chatLastRead'])) || ($_SESSION['chatLastRead'] == -1))
        {
            //Se envia:
            //          nombre
            //          nombreCliente
            //          chat.* ->
            //                  id
            //                  from
            //                  to
            //                  message
            //                  sent
            //                  recd
            
            //Se traen los últimos 100 mensajes para construir los chats iniciales
            $sql = "select * from (select c.*, REPLACE(u.nombre, '@', '') as nombre, REPLACE(u2.nombre, '@', '') as nombreCliente " .
            "from chat c join usuario u on c.from=u.id left join usuario u2 on (c.to=u2.id and u2.supervisor=0) " .
            "where ((not(u2.id is null)) or (c.to=1)) " .
            "order by c.id DESC LIMIT 100) tab1 order by id ASC";
            
            $sql = "SELECT cn.id, if (cn.envioUsuario=1,cn.usuario,cn.propiedad) as 'from', if (cn.envioUsuario=0,cn.usuario,cn.propiedad) as 'to', cn.mensaje as message, cn.fecha as sent, cn.leido as recd, if (cn.envioUsuario=1,REPLACE(CONCAT(cl.id, ' ', cl.nombre, ' ', cl.apellidos, ' para ',ta.id, ' ', ta.tipo), '@', ''),ta.tipo) as nombre, if (cn.envioUsuario=1,'', REPLACE(CONCAT(cl.id, ' ', cl.nombre, ' ', cl.apellidos, ' para ',ta.id, ' ', ta.tipo), '@', '')) as nombreCliente " .
                "FROM chatNvo cn join tipoAsesor ta on ((ta.id * -1) = cn.propiedad) join usuario us on us.id=cn.usuario join cliente cl on cl.id=us.cliente " .
                "WHERE propiedad<0 " .
                "LIMIT 100";
            $_SESSION['chatHistory'] = array();
        }
        else
        {
            $chatLastRead = $_SESSION['chatLastRead'];
            $sql = "select c.*, u.nombre, REPLACE(u2.nombre, '@', '') as nombreCliente " .
            "from chat c join usuario u on c.from=u.id left join usuario u2 on (c.to=u2.id and u2.supervisor=0) " .
            "where (c.id > $chatLastRead) and ((not(u2.id is null)) or (c.to=1)) and (1=0)" .
            "order by c.id ASC";
            
            $sql = "SELECT cn.id, if (cn.envioUsuario=1,cn.usuario,cn.propiedad) as 'from', if (cn.envioUsuario=0,cn.usuario,cn.propiedad) as 'to', cn.mensaje as message, cn.fecha as sent, cn.leido as recd, if (cn.envioUsuario=1,REPLACE(CONCAT(cl.id, ' ', cl.nombre, ' ', cl.apellidos, ' para ',ta.id, ' ', ta.tipo), '@', ''),ta.tipo) as nombre, if (cn.envioUsuario=1,'', REPLACE(CONCAT(cl.id, ' ', cl.nombre, ' ', cl.apellidos, ' para ',ta.id, ' ', ta.tipo), '@', '')) as nombreCliente " .
            "FROM chatNvo cn join tipoAsesor ta on ((ta.id * -1) = cn.propiedad) join usuario us on us.id=cn.usuario join cliente cl on cl.id=us.cliente " .
            "WHERE (propiedad<0) and (cn.id > $chatLastRead) ";
            //echo $sql;
        }
        
        $query = mysqli_query($dbh,$sql);
        $items = '';
        
        $chatBoxes = array();
        
        //echo $sql;
        
        while ($chat = mysqli_fetch_array($query))
        {
            //print_r($chat);
            
            if ($chat['nombreCliente'] == "")
            {
                $cliente = $chat['from'] . '/' . $chat['to'];
            }
            else
            {
                $cliente = $chat['to'] . '/' . $chat['from'];
            }
            
            
            if (!isset($_SESSION['openChatBoxes'][$cliente]) && isset($_SESSION['chatHistory'][$cliente])) {
                $items = $_SESSION['chatHistory'][$cliente];
            }
            
            //$chat['message'] = $this->sanitize($chat['message']);
            
            if ($chat['nombreCliente'] == "")
            {
                $items .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['from']}\",\"t\": \"{$chat['to']}\",\"fn\": \"{$chat['nombre']}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            else
            {
                $items .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['to']}\",\"t\": \"{$chat['from']}\",\"fn\": \"{$chat['nombre']}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            
            if (!isset($_SESSION['chatHistory'][$cliente])) {
                $_SESSION['chatHistory'][$cliente] = '';
            }
            
            $nombre = $chat['nombre'];
            $nombre = str_replace (" ", "_", $nombre);
            $nombre = str_replace (".", "", $nombre);
            if ($chat['nombreCliente'] == "")
            {
                $_SESSION['chatHistory'][$cliente] .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['from']}\",\"t\": \"{$chat['to']}\",\"fn\": \"{$nombre}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            else
            {
                $_SESSION['chatHistory'][$cliente] .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['to']}\",\"t\": \"{$chat['from']}\",\"fn\": \"{$nombre}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            
            unset($_SESSION['tsChatBoxes'][$cliente]);
            $_SESSION['openChatBoxes'][$cliente] = $chat['sent'];
            
            $_SESSION['chatLastRead'] = $chat['id'];
        }
        
        
        /*
        //Se mandan toda la conversación.
        if ((!isset($_SESSION['chatLastRead'])) || ($_SESSION['chatLastRead'] == -1))
        {
            //Se envia:
            //          nombre
            //          nombreCliente
            //          chat.* ->
            //                  id
            //                  from
            //                  to
            //                  message
            //                  sent
            //                  recd
            
            //Se traen los últimos 100 mensajes para construir los chats iniciales
            $sql = "select * from (select c.*, REPLACE(u.nombre, '@', '') as nombre, REPLACE(u2.nombre, '@', '') as nombreCliente " .
                    "from chat c join usuario u on c.from=u.id left join usuario u2 on (c.to=u2.id and u2.supervisor=0) " .
                    "where ((not(u2.id is null)) or (c.to=1)) " .
                    "order by c.id DESC LIMIT 100) tab1 order by id ASC";
        }
        else
        {
            $chatLastRead = $_SESSION['chatLastRead'];
            $sql = "select c.*, u.nombre, REPLACE(u2.nombre, '@', '') as nombreCliente " .
                    "from chat c join usuario u on c.from=u.id left join usuario u2 on (c.to=u2.id and u2.supervisor=0) " .
                    "where (c.id > $chatLastRead) and ((not(u2.id is null)) or (c.to=1)) " .
                    "order by c.id ASC";
        }
            
        $query = mysqli_query($dbh,$sql);
        $items = '';
        
        $chatBoxes = array();
        
        //echo $sql;
        
        while ($chat = mysqli_fetch_array($query))
        {
            //print_r($chat);
            
            if ($chat['nombreCliente'] == "")
            {
                $cliente = 'from';
            }
            else
            {
                $cliente = 'to';
            }
            
            if (!isset($_SESSION['openChatBoxes'][$chat[$cliente]]) && isset($_SESSION['chatHistory'][$chat[$cliente]])) {
                $items = $_SESSION['chatHistory'][$chat[$cliente]];
            }
            
            //$chat['message'] = $this->sanitize($chat['message']);
            
            if ($chat['nombreCliente'] == "")
            {
                $items .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['from']}\",\"fn\": \"{$chat['nombre']}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            else
            {
                $items .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['to']}\",\"fn\": \"{$chat['nombre']}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            
            if (!isset($_SESSION['chatHistory'][$chat[$cliente]])) {
                $_SESSION['chatHistory'][$chat[$cliente]] = '';
            }
            
            $nombre = $chat['nombre'];
            $nombre = str_replace (" ", "_", $nombre);
            $nombre = str_replace (".", "", $nombre);
            if ($chat['nombreCliente'] == "")
            {
                $_SESSION['chatHistory'][$chat[$cliente]] .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['from']}\",\"fn\": \"{$nombre}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            else
            {
                $_SESSION['chatHistory'][$chat[$cliente]] .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['to']}\",\"fn\": \"{$nombre}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            
            unset($_SESSION['tsChatBoxes'][$chat[$cliente]]);
            $_SESSION['openChatBoxes'][$chat[$cliente]] = $chat['sent'];
            
            $_SESSION['chatLastRead'] = $chat['id'];
        }
        */
        /*
         if (!empty($_SESSION['openChatBoxes'])) {
         foreach ($_SESSION['openChatBoxes'] as $chatbox => $time) {
         if (!isset($_SESSION['tsChatBoxes'][$chatbox])) {
         $now = time()-strtotime($time);
         $time = date('g:iA M dS', strtotime($time));
         
         $message = "Sent at $time";
         if ($now > 180) {
         $items .= "{\"s\": \"2\",\"f\": \"$chatbox\",\"fn\": \"$chatbox\",\"m\": \"{$message}\"},";
         
         
         if (!isset($_SESSION['chatHistory'][$chatbox])) {
         $_SESSION['chatHistory'][$chatbox] = '';
         }
         
         $_SESSION['chatHistory'][$chatbox] .= "{\"s\": \"2\",\"f\": \"$chatbox\",\"fn\": \"$chatbox\",\"m\": \"{$message}\"},";
         
         $_SESSION['tsChatBoxes'][$chatbox] = 1;
         }
         }
         }
         }
         */
        
        //$sql = "update chat set recd = 1 where chat.to = '".mysqli_real_escape_string($dbh,$_SESSION['username'])."' and recd = 0";
        
        //$sql = "update chat set recd = 1 where chat.to = '".mysqli_real_escape_string($dbh,$_SESSION['user_id'])."' and recd = 0";
        //$query = mysqli_query($dbh,$sql);
        
        if ($items != '') {
            $items = substr($items, 0, -1);
        }
        header('Content-type: application/json');
        ?>
{
    "items": [
    <?php echo $items;?>
    ]
}

<?php
    exit(0);
    }
    
    function abreChat()
    {
        //print_r ($_SESSION);
        
        global $dbh;
        //$sql = "select c.*, u.nombre, u2.nombre as nombreCliente from chat c join usuario u on c.from=u.id left join usuario u2 on (c.to=u2.id and u2.supervisor=0) where (c.id > $chatLastRead) and ((not(u2.id is null)) or (c.to=1)) order by c.id ASC";
        
        /*
        $sql = "select c.*, REPLACE(u.nombre, '@', '') as nombre, REPLACE(u2.nombre, '@', '') as nombreCliente from chat c join usuario u on c.from=u.id left join usuario u2 on (c.to=u2.id and u2.supervisor=0) where ((c.FROM = ". $_GET['usrId'] . ") and (c.TO=1)) OR (c.TO = ". $_GET['usrId'] . ") order by c.id ASC";
        */
        
        //Se abre el chat del usuario... peroooooo aqui se necesita saber hacia quien
        $sql = "SELECT cn.id, if (cn.envioUsuario=1,cn.usuario,cn.propiedad) as 'from', if (cn.envioUsuario=0,cn.usuario,cn.propiedad) as 'to', cn.mensaje as message, cn.fecha as sent, cn.leido as recd, if (cn.envioUsuario=1,REPLACE(CONCAT(cl.id, ' ', cl.nombre, ' ', cl.apellidos, ' para ',ta.id, ' ', ta.tipo), '@', ''),ta.tipo) as nombre, if (cn.envioUsuario=1,'', REPLACE(CONCAT(cl.id, ' ', cl.nombre, ' ', cl.apellidos, ' para ',ta.id, ' ', ta.tipo), '@', '')) as nombreCliente " .
        "FROM chatNvo cn join tipoAsesor ta on ((ta.id * -1) = cn.propiedad) join usuario us on us.id=cn.usuario join cliente cl on cl.id=us.cliente " .
        "WHERE (propiedad<0) AND (us.id =". $_GET['usrId'] . ") AND (cn.propiedad =". $_GET['asesorId'] . ")" .
        "LIMIT 100";

        
        
        $query = mysqli_query($dbh,$sql);
        $items = '';
        
        //echo $sql;
        
        while ($chat = mysqli_fetch_array($query))
        {
            //$chat['message'] = $this->sanitize($chat['message']);
            
            if ($chat['nombreCliente'] == "")
            {
                $items .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['from']}\",\"t\": \"{$chat['to']}\",\"fn\": \"{$chat['nombre']}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            else
            {
                $items .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['to']}\",\"t\": \"{$chat['from']}\",\"fn\": \"{$chat['nombre']}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            
            if ($chat['nombreCliente'] == "")
            {
                $cliente = $chat['from'] . '/' . $chat['to'];
            }
            else
            {
                $cliente = $chat['to'] . '/' . $chat['from'];
            }

            if (!isset($_SESSION['chatHistory'][$cliente])) {
                $_SESSION['chatHistory'][$cliente] = '';
            }
            
            $nombre = $chat['nombre'];
            $nombre = str_replace (" ", "_", $nombre);
            $nombre = str_replace (".", "", $nombre);
            if ($chat['nombreCliente'] == "")
            {
                //$_SESSION['chatHistory'][$cliente] .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['from']}\",\"t\": \"{$chat['to']}\",\"fn\": \"{$nombre}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }
            else
            {
                //$_SESSION['chatHistory'][$cliente] .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['to']}\",\"t\": \"{$chat['from']}\",\"fn\": \"{$nombre}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
            }

            
            //$items .= "{\"cn\": \"{$chat['nombreCliente']}\",\"s\": \"0\",\"f\": \"{$chat['to']}\",\"fn\": \"{$chat['nombre']}\",\"m\": \"{$chat['message']}\",\"d\": \"{$chat['sent']}\"},";
        }
        
        if ($items != '') {
            $items = substr($items, 0, -1);
        }
        header('Content-type: application/json');
        ?>
{
    "items": [
    <?php echo $items;?>
    ]
}

<?php
    exit(0);
    }
    
    function sanitize($text) {
        global $dbh;
        //$text = htmlspecialchars($text, ENT_QUOTES);
        $text = str_replace("\n\r","\n",$text);
        $text = str_replace("\r\n","\n",$text);
        $text = str_replace("\n","<br>",$text);
        $text = str_replace("\\","\\\\",$text);
        $text = str_replace("/","\\/",$text);
        return $text;
    }
    
    public function index()
    {
        global $dbh;
        define ('DBPATH','localhost');
        define ('DBUSER','haztuapp_default');
        define ('DBPASS','default_1');
        define ('DBNAME','haztuapp_default');

        
        $this->load->driver('session');
        
        $dbh = mysqli_connect(DBPATH,DBUSER,DBPASS);
        mysqli_select_db($dbh,DBNAME);
        
        if ($_GET['action'] == "chatheartbeat") { $this->chatHeartbeat(); }
        if ($_GET['action'] == "sendchat") { $this->sendChat(); }
        if ($_GET['action'] == "closechat") { $this->closeChat(); }
        if ($_GET['action'] == "startchatsession") { $this->startChatSession(); }
        if ($_GET['action'] == "abreChat") { $this->abreChat(); }
        
        if (!isset($_SESSION['chatHistory'])) {
            $_SESSION['chatHistory'] = array();
        }
        
        if (!isset($_SESSION['openChatBoxes'])) {
            $_SESSION['openChatBoxes'] = array();
        }
    }
    }
