<?php
session_start();
include_once "../config.php";
require_once '../database1.php';
require_once "../check_admin.php";


if(!isset($_GET['id']) || !is_numeric($_GET['id']))
{
    exit;
}

$id = $_GET['id'];


//require_once "check_admin.php";
require_once '../database1.php';
class ChatPage extends database
{
    public function getChat($id)
    {
        return $this->fetchRow('tb_chat_customer', ['cl_id' => $id]);
    }

    public function updateAgent($id, $userID)
    {
        return $this->update('tb_chat_customer', ['cl_agent_id' => $userID, 'cl_status' => 'Chat Started'], ['cl_id' => $id]);
    }

    public function getProduct($id)
    {
        return $this->fetchRow('tb_product', ['cl_id' => $id]);
    }
}	

$obj = new ChatPage();
$chat = $obj->getChat($id);

if($chat['cl_product_id'] == 0)
{
    //die('Product not found');
}

$productID = $chat['cl_product_id'];

$product = $obj->getProduct($productID);
if(!$product)
{
     //die('Product not found');
}

if($chat['cl_agent_id'] != 0 && $chat['cl_agent_id'] != $userID)
{
    die('Please go back. This chat is already attended by another agent.');
}

/*if($chat['cl_agent_id'] == 0)
{
    $res = $obj->updateAgent($id, $userID);
    if(!$res)
    {
        exit;
    }
}*/



$templateType = 'add';
include '../header.php';
?>

<script src="<?php echo MAIN_DOMAIN ?>/ckeditor/ckeditor.js"></script>
            <!-- MAIN CONTENT-->
            <div class="main-content">
                <div class="section__content section__content--p30">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="">
                                    <div class="row">
                                         <div class="col-sm-12">
                                             <h2 class="title-1 pull-left">Chatroom - Product <a target="_blank" href="<?php echo MAIN_DOMAIN ?>/veikals/product/<?php echo $product['cl_slug'] ?>"><?php echo $product['cl_name'] ?></a> <br/><br/> Product ID : <?php echo $product['cl_id'] ?></h2>
                                            
                                            <button type="button" class="btn btn-primary pull-right" id="close_chat">Close this Chat</button>
                                            <?php
                                            if($chat['cl_agent_id'] == 0)
                                            { ?>
                                            <button type="button" class="btn btn-primary pull-right" id="start_chat" style="margin-right: 10px">Start Chat</button>
                                            <?php } ?>
                                         </div>
                                        <div class="col-sm-12" id="close_chat_message" style="padding-top: 15px"></div>
                                    </div>
                                </div>
								<?php if($msg !=''){echo '<span class="col-md-6 alert alert-danger pull-left">' . $msg .  '</span>';}?>
                            </div>
                        </div>
                        
                        <div class="row m-t-25 m-row">
					
                            <div class="col-lg-12">
                                <div class="card">
                                    
                                    <div class="card-body card-block">
                                        <div class="well" style="margin-bottom: 15px">
                                            Name : <?php echo htmlspecialchars($chat['cl_name']) ?><br/>
                                            Email : <?php echo htmlspecialchars($chat['cl_email']) ?><br/>
                                            Message : <?php echo htmlspecialchars($chat['cl_message']) ?><br/>
                                            Status : <?php echo htmlspecialchars($chat['cl_status']) ?><br/>
                                            IP : <?php echo htmlspecialchars($chat['cl_ip']) ?><br/>
                                        </div>
    									<form method="post"  >
                                            <div class="row">
                                                <?php
                                            if($chat['cl_agent_id'] != 0)
                                            { ?>
                                                <div class="col-12 col-sm-9">
                                                    <div class="col-xs-12" id="chat_body">

                                                    </div>
                                                        <textarea class="form-control chat_textarea"></textarea>
                                                        <div class="error_area"></div>
                                                        <button type="button" class="btn btn-primary mt-1" id="chat_submit">Submit</button>
                                                </div>
                                                <?php
                                            }
                                            ?>
                                                <div class="col-12 col-sm-3
                                                     <?php
                                            if($chat['cl_agent_id'] == 0)
                                            { 
                                                echo 'offset-sm-9';
                                            } ?>
                                                     " id="chat_list">
                                                     <div class="col-12" id="unfinished_chats">
                                                        
                                                    </div>
                                                    <div class="col-12" id="unattended_chats">
                                                        
                                                    </div>

                                                   
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                          
                        </div>
                        
                    <script>
							$(document).ready(function(){
								$('.active').removeClass('active');
								$('#chat-menu').addClass('active');

                                
							}); 

                            
						</script>   

                     

                        <SCRIPT>
                            function setChatList(htmlUnattended, htmlUnFinished)
                            {   
                                
                                    jQuery('#unattended_chats').html('<div class="col-sm-12 " style="padding: 15px;margin-bottom:15px;border-bottom:1px solid gray">Unattended Chats</div>' + htmlUnattended);
                                     jQuery('#unfinished_chats').html('<div class="col-sm-12 " style="padding: 15px;margin-bottom:15px;border-bottom:1px solid gray">Current Chats</div>' + htmlUnFinished);
                            }

                            function setChatBody(html)
                            {
                                 jQuery('#chat_body').html(html);
                            }

                            function getChatList()
                            {
                                var htmlUnattended = '';
                                var htmlUnFinished = ''
                                jQuery.get('ajax/get_chats', function(res){
                                    
                                    

                                    


                                    jQuery(res.unattendedChats).each(function(i, value){
                                        var d = new Date(value.cl_created_at);

                                        var curr_day = d.getDate();
                                        if(curr_day < 10)
                                        {
                                            curr_day = '0' + curr_day;
                                        }
                                        var curr_month = d.getMonth();
                                        if(curr_month < 10)
                                        {
                                            curr_month = '0' + curr_month;
                                        }

                                        var curr_year = d.getFullYear();
                                        if(curr_year < 10)
                                        {
                                            curr_year = '0' + curr_year;
                                        }

                                        var curr_hour = d.getHours();
                                        if(curr_hour < 10)
                                        {
                                            curr_hour = '0' + curr_hour;
                                        }

                                        var curr_min = d.getMinutes();
                                        if(curr_min < 10)
                                        {
                                            curr_min = '0' + curr_min;
                                        }

                                        var curr_sec = d.getSeconds();
                                        htmlUnattended+= '<a href="chat?id=' + value.cl_id + '" class="each_chat col-12 alert alert-primary" style="display:block">' + value.cl_message + ' - on ' + curr_day + '-' + curr_month + '-' + curr_year + ' ' + curr_hour + ':' + curr_min + '</a>';

                                        
                                    });

                                    jQuery(res.unfinishedChats).each(function(i, value){
                                        var d = new Date(value.cl_created_at);

                                        var curr_day = d.getDate();
                                        if(curr_day < 10)
                                        {
                                            curr_day = '0' + curr_day;
                                        }
                                        var curr_month = d.getMonth();
                                        if(curr_month < 10)
                                        {
                                            curr_month = '0' + curr_month;
                                        }

                                        var curr_year = d.getFullYear();
                                        if(curr_year < 10)
                                        {
                                            curr_year = '0' + curr_year;
                                        }

                                        var curr_hour = d.getHours();
                                        if(curr_hour < 10)
                                        {
                                            curr_hour = '0' + curr_hour;
                                        }

                                        var curr_min = d.getMinutes();
                                        if(curr_min < 10)
                                        {
                                            curr_min = '0' + curr_min;
                                        }
                                        
                                        var curr_sec = d.getSeconds();
                                        htmlUnFinished+= '<a href="chat?id=' + value.cl_id + '" class=" each_chat col-12 alert alert-primary" style="display:block">' + value.cl_message + ' - on ' + curr_day + '-' + curr_month + '-' + curr_year + ' ' + curr_hour + ':' + curr_min + '</a>';
                                    });

                                    setChatList(htmlUnattended, htmlUnFinished);
                                },'json');
                                
                               
                            }


                            function getChat()
                            {
                                var html = '';
                                $.get('ajax/get_current_chat', {id:<?php echo $id ?>}, function(res){
                                    $(res).each(function(i, value){
                                        if(value.cl_user_type == 'User')
                                        {
                                            html+='<div class="col-sm-12 each_message efix_agent pull-left"><div class="chat_message_container pull-left"><div class="chat_message pull-left">' + value.cl_message + '</div><div class="minutes_ago_text">5 mins ago</div></div></div>';
                                        }
                                        else
                                        {
                                            html+='<div class="col-sm-12 each_message efix_customer pull-right"><div class="chat_message_container pull-right"><div class="chat_message pull-left">' + value.cl_message + '</div><div class="minutes_ago_text">5 mins ago</div></div></div>';
                                        }
                                    });

                                    setChatBody(html);
        
                                }, 'json');


                            }

                            jQuery(document).ready(function(){
                                getChatList();
                                getChat();
                                setInterval(function() {
                                        getChatList();
                                }, 5000);


                                setInterval(function() {
                                        getChat();
                                }, 3000);
                            });




                            jQuery(document).ready(function(){
                                  jQuery('#chat_submit').click(function(){
                                    var message = jQuery('.chat_textarea').val();
                                    jQuery('#chat_submit').attr('disabled', 'disabled');
                                    jQuery.post('ajax/send_message?id=<?php echo $id ?>', {message:message}, function(){
                                      $('.error_area').html('');
                                      jQuery('.chat_textarea').val('');
                                        jQuery('#chat_submit').removeAttr('disabled');
                                    },'json').fail(function(xhr){
                                      jQuery('#chat_submit').removeAttr('disabled');
                                     
                                        $('.error_area').html('');
                                        var html = '';
                                        var res = xhr.responseJSON;
                                        if (typeof res === 'undefined') {
                                          jQuery('.error_area').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                        }
                                       
                                          if(typeof res.error_text === 'undefined')
                                          {
                                            jQuery('.error_area').html('<div class="alert alert-danger">Something went wrong</div>').show();
                                            window.location.href = '#body_part';
                                            return;
                                          }
                                          else
                                          {
                                            jQuery('.error_area').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
                                            window.location.href = '#body_part';
                                            return;
                                          }
                                        
                                    }, 'json');
                                  })

                                  jQuery('#close_chat').click(function(){
                                    jQuery('#close_chat').attr('disabled', 'disabled');
                                    jQuery('#close_chat_message').html('<div class="col-sm-12 alert alert-warning">Closing Chat.......</div>');
                                    jQuery.get('ajax/close_chat?id=<?php echo $id ?>', function(){
                                        jQuery('#close_chat').removeAttr('disabled'); 
                                        jQuery('#close_chat_message').html('<div class="col-sm-12 alert alert-success">Chat Closed. Redirecting.....</div>');
                                        window.location.href = 'chatroom'
                                    },'json').fail(function(xhr){
                                        jQuery('#close_chat').removeAttr('disabled');
                                        jQuery('#close_chat_message').html('<div class="col-sm-12 alert alert-danger">Something went wrong. Please try again</div>');
                                    }, 'json');
                                  });
                                })
                                
                                
                                
                                
                                jQuery(document).on('click', '#start_chat', function(){
                                    jQuery('#start_chat').attr('disabled', 'disabled').text('Please wait....');
                                    
                                    jQuery.get('ajax/start_chat?id=<?php echo $id ?>', function(){
                                        
                                        jQuery('#close_chat_message').html('<div class="col-sm-12 alert alert-success">Chat Started. Refreshing page...</div>');
                                        location.reload();
                                    },'json').fail(function(xhr){
                                        jQuery('#start_chat').removeAttr('disabled').text('Start Chat');
                                        jQuery('#close_chat_message').html('<div class="col-sm-12 alert alert-danger">Something went wrong. Please try again</div>');
                                    }, 'json');
                                  });
                               
                        </SCRIPT> 
                       

  <?php
  include '../footer.php';
  ?>