<?php
include "Twilio/autoload.php";
include('dashboard.php');

use Twilio\Jwt\ClientToken;
// put your Twilio API credentials here
$accountSid = 'AC8bac449b32a1fe6070f736d142cbac1f';
$authToken = '8e489af7dfa15b610298953e184de89d';
// put your TwiML Application Sid here
$appSid = 'APedefbaf42f7a84fd6ee4d1be02f6ca1a';
$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming('Jonathan');
 $token = $capability->generateToken();

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatbot</title>
    <link rel="stylesheet" href="./style.css">
</head>
<style>
.main-wrapper{
    display: flex;
    justify-content: space-between;
    margin: 8px;
}
.chat-window-form button {
    position: absolute;
    right: 13px;
       top: 50%;
    transform: translateY(-50%);
}
form.chat-window-form {
    position: relative;
    bottom: 16px;
    width: 100%;
    margin-top: 60px;
    height:100%;
}
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        background-color: #F6F6F3;
    }

    section#Chatbot {
        padding: 0 16px;
        width: 80% ;
      right: 0%;
       position: absolute;
      top: 90px;
      height: 88%;
}
    }

    .conatainer {
        width: 100%;
        margin: auto;
        padding: 16px 0;
    }

    .inner-chatbot-div2 {
        width: 100%;
        max-width: 20%;
        background: #fff;
        padding: 16px;
        border-radius: 8px;
        box-shadow: #25354417 0px 3px 8px;
        height:100% !important;
    }
    .tabs-content{
        overflow:auto;
        height:100%;
    }

    .inner-chatbot-head {
        display: flex;
        justify-content: space-between;
    }

    .no-profile-img {
        display: flex;
        align-items: center;
        column-gap: 8px;
        margin-bottom: 22px;
        position: relative;
        cursor: pointer;
    }

    .no-profile h4 {
        margin-bottom: 6px;
        color: #131313;
        letter-spacing: -0.25px;
        line-height: 14px;
        font-size: 14px;
        font-weight: 400;
        font-family: Lexend Deca;
    }

    .no-profile p {
        color: #BABABA;
        letter-spacing: -0.25px;
        line-height: 14px;
        font-size: 14px;
        font-weight: 300;
        font-family: Lexend Deca;
    }

    .no-profile-img img {
        position: relative;
    }

    .chatbot-main-div {
        display: flex;
        gap:16px;
        height: 100%;
        
    }
.chatbot-main-div p{
    margin-bottom:0;
}
.chatbot-main-div h1,h2,h3,h4,h5,h6{
    margin:0;
}
    .active-green-svg {
        position: absolute;
        left: 38px;
        top: 0;
    }

    .no-profile-img a {
        text-decoration: none;
    }

    .inner-chatbot-div3 {
        width: 100%;
        max-width: 80%;
        background-color: #fff;
        padding: 16px;
        border-radius: 8px;
        box-shadow: #25354417 0px 3px 8px;
        z-index:0;

    }

    .tabs-nav {
        display: flex;
        list-style: none;
        gap: 20px;
        font-size:16px;
    }

    .tab.active {
        font-weight: 600;
        color: #131313;
    }

    .tabs-content {
        padding: 20px 0;
    }

    .tab-pane {
        display: none;
        opacity: 0;
        transform: translateY(20px);
        transition: opacity 0.5s ease, transform 0.5s ease;
    }

    .tab-pane.active {
        display: block;
        opacity: 1;
        transform: translateY(0);
    }

    .chatbot-profile-header {
        position: relative;
        display: flex;
        gap: 10px;
        align-items: center;
    }

    .messege-call-chat {
        left: 25px;
        top: -6px;
    }

    .profile-call-video {
        display: flex;
        position: relative;
        cursor: pointer;
    }

    .profile-call-video-photo {
        position: absolute;
        left: -20px;
    }

    .profile-call-video-avtar img {
        border-right: 1px solid #C3C3C4;
        padding-right: 16px;
    }

    .msg-box-call-icon {
        margin: 0 14px;
        cursor: pointer;
    }

    .chatbot-profile-header h3 {
        letter-spacing: -0.25px;
        font-size: 22px;
        line-height: 19px;
        font-weight: 400;
        color: #131313;
        margin:0;
    }

    .inner-chatbot-div3-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        display: none;
        padding-bottom: 8px;
    border-bottom: 1px solid #e5e5e5;
    }

.subList .subList__item{
        width: 100% !important;
}
.subList .subList__item a{
    width: 100%;
    text-transform: capitalize !important;
}


    .main-chat-profile {
        display: flex;
        gap: 16px;
        align-items: top;
        margin:6px 0;
    }

    .sender-name {
        color: #919191;
        margin: 6px 0 !important;
        font-size: 12px;
    }

    .chat-reciver-content {
        display: flex;
        justify-content: end;
        gap: 16px;
    }

    .reciver-name {
        color: #919191;
         margin: 6px 0 !important;
        font-size: 12px;
        text-align: end;
    }

    .msg-recsend {
        background-color: #e5e5e5;
        padding: 10px;
        border-radius: 8px;
        max-width: 300px;
        word-wrap: break-word;
    }

    .msg-recsend.sender {
        background-color: #a2e2a2;
    }

    .chat-bubble.missed-call {
        display: flex;
        align-items: center;
        padding: 10px;
        max-width: 300px;
        gap: 10px;
        background: #e5e5e5;
    border-radius: 8px;
    }

    .chat-bubble .icon {
        font-size: 20px;
        margin-right: 10px;
    }

    .chat-bubble .message .title {
        font-weight: bold;
        display: block;
    }

    .chat-bubble .message .timestamp {
        font-size: 12px;
        color: #555;
    }
    .active-green-svg,.profile-call-video-photo,.profile-call-video-avtar,.msg-box-videocall-icon{
        display: none;
    }
    .no-profile p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 152px;
}
.chatbot-profile-img{
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
}
.chatbot-profile-img h3{
    margin:0;
}
.inner-chatbot-div2 .tab{
    cursor: pointer;
}
/*.no-profile-img.unseen {*/
/*    background-color: #d4f8e8;*/
/*    box-shadow: 0 0 8px #3ad64d30;*/
/*    border: 0px solid #3ad64d;*/
/*}*/
    .call-logs-div {
    display: flex;
    gap: 16px;
    align-items: center;
    margin-top: 16px;
    color: #333;
}
p.caller-timing {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    margin-top: 4px;
}
.missedcall-timing svg{
   transform: rotate(184deg);
}
.call-logs-div:first-child{
    margin-top:0;
}
    #message-input {
      width: 100%;
      padding: 20px 10px;
      font-size: 16px;
      border:1px solid #DEE2E6;
      border-radius:12px;
      outline:none;
    }
    #message-input::placeholder{
        font-size: 14px;
        color: #DBDBDB;
    }
    .input-form-div {
    position: relative;
}

.no-profile h4 {
  text-transform: capitalize;
}
.missedcall-name{
    color:#FA320A;
}
.chatbot-main-div p, h2, h4, a, li {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif !important;
}

.chat-window{
    height: 92%;
}
.chat-window::-webkit-scrollbar {
    display: none;
}
.navList .subList__item:first-child{
    padding-top: 0;
}
.chatbot-main-div {
    position: relative;
    overflow: hidden;
}

.contact-number-main {
    display: flex;
    gap: 16px;
    align-items: center;
}

span.action-label {
    display: flex;
}
.contact-entry-div:first-child{
    margin-top:0;
}
.contact-entry-div{
    display: flex;
    justify-content: space-between;
    color: #131313;
    align-items: center;
    margin-top:16px;
}
span.action-label-main {
    display: flex;
    align-items: center;
    font-size:13px;
}
.action-icon {
    cursor: pointer;
    position: relative;
    height:fit-content;
}

.dropdown-menu-action {
    position: absolute;
    right: 0;
    top: 20px;
    background-color: white;
    border: 1px solid #ccc;
    min-width: 120px;
    padding: 0 8px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
     opacity: 0;
    visibility: hidden;
    transition: opacity 0.7s ease, visibility 0.7s;
    z-index:9;
}
.action-icon:hover .dropdown-menu-action {
    opacity: 1;
    visibility: visible;
    color:;
}

.dropdown-item-action{
    margin:8px 0;
}
.dropdown-menu-action a{
    text-decoration: none;
    color:#253544;
}

.input-form-div {
    position: absolute;
    bottom: 0;
    width: 100%;
}
.chat-window {
    position: relative;
    overflow-y: auto;
}

form.chat-window-form {
    position:absolute !important;
    height:unset !important;
    bottom:0;
    padding-bottom:unset !important;
}
.chat-window-form div{
    background-color: #fff !important;
}
.chat-window:not(:has(.chat-sender-content)) .chat-window-form {
    height: 100%;
    position: absolute !important;
}
.chat-window:has(div:nth-child(8)) .chat-window-form {
    position: sticky !important;
}
.col-sm-12.text-align {
    width: unset;
}
.back-to-chatbar svg:first-of-type {
  display: none;
}
#contacts-list{
    height:100%;
    overflow:auto;
}
.chat-sender-content{
    display:flex;
    gap:16px
}
.modal-content {
    width: 300px;
    height: 212px;
    padding: 20px;
}
#editModal{
    justify-content: center;
    align-items: center;
    background:#25354438;
    z-index:999999;
}
.modal-content h3{
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 16px;
}
#editContactForm button{
    width: 100%;
    background: #253544;
    color: #fff;
    border-radius: 4px;
    padding: 4px;
}
#editContactForm input{
    width: 100%;
    padding: 4px;
    border-radius: 4px;
    outline: none;
    border: 1px solid #253544;
}
.chatbot-profile-header #log {
    font-size: 16px;
    max-width: 400px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

@media (max-width: 1460px) and (min-width: 1224px) {
    .inner-chatbot-div2{
        max-width: 26%;
    }
    .inner-chatbot-div3{
        max-width: 74%;
    }
    }

@media (max-width: 1253px) {
    .inner-chatbot-div2{
        max-width: 30%;
    }
    .inner-chatbot-div3{
        max-width: 70%;
    }
.chatbot-main-div{
    gap:8px;
}
}

    @media (max-width: 1000px) and (min-width: 768px) {
    .inner-chatbot-div2{
        max-width: 39%;
    }
    .inner-chatbot-div3{
        max-width: 61%;
    }
    .chatbot-profile-header h3{
        font-size: 18px
    }
p.msg-recsend {
    margin-bottom: 12px;
}
    }
    

@media (max-width: 1700px) {
    .inner-chatbot-div2{
        max-width: 24%;
    }
    .inner-chatbot-div3{
        max-width: 76%;
    }
    }

@media (max-width: 1400px) {
    .inner-chatbot-div2{
        max-width: 28%;
    }
    .inner-chatbot-div3{
        max-width: 72%;
    }
}
@media (max-width: 1200px) {
    .inner-chatbot-div2{
        max-width: 34%;
    }
    .inner-chatbot-div3{
        max-width: 66%;
    }
    .chatbot-profile-header #log{
    font-size: 16px;
    max-width: 199px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;  
}
}
@media (max-width: 1000px) {
    .inner-chatbot-div2{
        max-width: 40%;
    }
    .inner-chatbot-div3{
        max-width: 60%;
    }
        .chatbot-profile-header #log{
    font-size: 14px;
        max-width: 100px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;  
}
}

@media (max-width: 872px) {
    .inner-chatbot-div2{
        max-width: 44%;
    }
    .inner-chatbot-div3{
        max-width: 56%;
    }
        .chatbot-profile-header #log{
        max-width: 74px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;  
} 
}
@media (min-width:918px) and (max-width:1024px)  {
    section#Chatbot{
        width:79% !important;
    }
}
@media (max-width:918px) and (min-width:767px) {
    section#Chatbot{
        width:78% !important;
    }
}
@media (max-width:768px) {
    .tabs-nav {
        gap: 24px;
    }

    .inner-chatbot-div3 .inner-chatbot-div3-content .chatbot-profile-header .chatbot-profile-img svg {
        height: 28px;
        width: 28px;
    }

    .inner-chatbot-div3 #chat-header-number {
        font-size: 16px;
    }

    .inner-chatbot-div3 .col-sm-12 #log {
        font-size: 16px !important;
    }

    .inner-chatbot-div3 .col-sm-12 {
        padding-left: 4px;
        padding-right: 4px;
    }

    .back-to-chatbar svg:first-of-type {
        display: block;
    }

    .back-to-chatbar {
        display: flex;
        align-items: center;
        gap: 4px;
    }

    .back-to-chatbar svg:first-child {
        height: 22px !important;
        width: 22px !important;
    }

    .chatbot-profile-header #log {
        max-width: 150px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: unset;
    }

    #call-number {
        font-size: 20px !important;
    }
    #calling-interface-overlay > div {
    padding: 20px !important;
    min-width:270px !important;
    }
    #call-status{
        font-size:16px !important;
        margin-bottom: 16px;
    }
    #end-call-btn{
        padding:6px 16px !important;
    }
    #mute-show{
        padding:6px 16px !important;
    }
    #unmute-show{
        padding:6px 16px !important;
    }
}


@media (max-width:600px) {
     .chatbot-profile-header #log{
        max-width: 150px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;  
        font-size:14px;
}
.inner-chatbot-div3 #chat-header-number{
    font-size:14px;
}
}
@media (max-width:452px) {
     .chatbot-profile-header #log{
        max-width: 100px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;  
}
}

@media (max-width:380px) {
    .chatbot-profile-header #log {
        max-width: 46px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

/*developer css*/
.chat-window {
    display: none;
}
#calling-interface-overlay {
    position: absolute; 
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.3);
    z-index: 999999;
}
#calling-interface-overlay > div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.18);
    padding: 40px;
    min-width: 300px;
    min-height: 200px;
    text-align: center;
}

/* ✅ Simple styling */
.modal {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center;
}
.modal-content {
  background: #fff; padding: 20px; border-radius: 8px; width: 300px;
}
.close {
  float: right; font-size: 20px; cursor: pointer;
}
/*developer css*/

</style>

<body>
    <section id="Chatbot">
        <div class="conatainer">
            <div class="chatbot-main-div">
                <!--<div class="inner-chatbot-div1"></div>-->
                <div class="inner-chatbot-div2">
                    <div class="inner-chatbot-head">
                        <ul class="tabs-nav">
                            <li class="tab active" data-tab="tab1">
                                Chats
                            </li>
                            <li class="tab" data-tab="tab2">
                                Calls
                            </li>
                             <li class="tab" data-tab="tab3">
                                Contacts
                            </li>
                        </ul>
                    </div>
                    <div class="tabs-content">
                        <div class="tab-pane active" id="tab1">
                           <div id="sender-list"></div>
                        </div>
                        
                        <div class="tab-pane" id="tab2">
                            <div class="call-logs" id="callLogsContainer">
                                <!-- Logs will be appended here dynamically -->
                            </div>
                        </div>

                     <div class="tab-pane" id="tab3">
                           <div id="contacts-list"></div>
                     </div>
                    </div>
                </div>
                <div class="inner-chatbot-div3">
                    <div class="inner-chatbot-div3-content">
                        <div class="chatbot-profile-header">                
                            <div class="chatbot-profile-img">
                            <div class="back-to-chatbar">
                                <svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 24 24" fill="none">
                            <path d="M6 12H18M6 12L11 7M6 12L11 17" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                             <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" viewBox="0 0 35 35"
                                    fill="none">
                                    <path
                                        d="M17.5 30.1C13.125 30.1 9.2575 27.86 7 24.5C7.0525 21 14 19.075 17.5 19.075C21 19.075 27.9475 21 28 24.5C26.8433 26.2229 25.2805 27.6349 23.4495 28.6115C21.6184 29.588 19.5752 30.0992 17.5 30.1ZM17.5 5.25C18.8924 5.25 20.2277 5.80312 21.2123 6.78769C22.1969 7.77226 22.75 9.10761 22.75 10.5C22.75 11.8924 22.1969 13.2277 21.2123 14.2123C20.2277 15.1969 18.8924 15.75 17.5 15.75C16.1076 15.75 14.7723 15.1969 13.7877 14.2123C12.8031 13.2277 12.25 11.8924 12.25 10.5C12.25 9.10761 12.8031 7.77226 13.7877 6.78769C14.7723 5.80312 16.1076 5.25 17.5 5.25ZM17.5 0C15.2019 0 12.9262 0.452651 10.803 1.33211C8.67984 2.21157 6.75066 3.50061 5.12563 5.12563C1.84374 8.40752 0 12.8587 0 17.5C0 22.1413 1.84374 26.5925 5.12563 29.8744C6.75066 31.4994 8.67984 32.7884 10.803 33.6679C12.9262 34.5474 15.2019 35 17.5 35C22.1413 35 26.5925 33.1563 29.8744 29.8744C33.1563 26.5925 35 22.1413 35 17.5C35 7.8225 27.125 0 17.5 0Z"
                                        fill="#C3C3C4" />
                                </svg>
                         </div>
                               
                                <div class="active-green-svg messege-call-chat">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8"
                                        fill="none">
                                        <circle cx="4" cy="4" r="3.5" fill="#3AD64D" stroke="white" />
                                    </svg>
                                </div>
                            </div>
                            <!--mobile number and name-->
                           <h3 id="chat-header-number"></h3>
                           <!--mobile number -->
                           <h3 id="chat-header-number-only" style="display:none;"></h3>
                           	<!-- <div class="col-sm-12"></div> -->
            				<div class="col-sm-12 text-align">
            					<div id="log" style="color:green;font-weight:bold;font-size:18px; text-align: center;">Loading pigeons...</div>
            				</div>
                        </div>
                        <div class="profile-call-video">
                            <div class="profile-call-video-photo">
                                <img src="./img/Rectangle 1 (2).png" alt="">
                            </div>
                            <div class="profile-call-video-avtar">
                                <img src="./img/Vector (1).png" alt="">
                            </div>
                            <div class="msg-box-call-icon">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"
                                        fill="none">
                                        <path
                                            d="M17.5 12.8833L13.1083 12.375L11.0083 14.475C8.64283 13.2716 6.72005 11.3488 5.51667 8.98333L7.625 6.875L7.11667 2.5H2.525C2.04167 10.9833 9.01667 17.9583 17.5 17.475V12.8833Z"
                                            fill="#131313" />
                                    </svg>
                            </div>
                            <div class="msg-box-videocall-icon">
                                <a href="">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="21" height="20" viewBox="0 0 21 20"
                                        fill="none">
                                        <path
                                            d="M8 10.8333V12.4999C8 12.736 8.08 12.9341 8.24 13.0941C8.4 13.2541 8.59778 13.3338 8.83333 13.3333C9.06889 13.3327 9.26694 13.2527 9.4275 13.0933C9.58805 12.9338 9.66778 12.736 9.66666 12.4999V10.8333H11.3333C11.5694 10.8333 11.7675 10.7533 11.9275 10.5933C12.0875 10.4333 12.1672 10.2355 12.1667 9.99992C12.1661 9.76436 12.0861 9.56658 11.9267 9.40658C11.7672 9.24658 11.5694 9.16658 11.3333 9.16658H9.66666V7.49992C9.66666 7.26381 9.58666 7.06603 9.42666 6.90658C9.26666 6.74714 9.06889 6.66714 8.83333 6.66658C8.59778 6.66603 8.4 6.74603 8.24 6.90658C8.08 7.06714 8 7.26492 8 7.49992V9.16658H6.33333C6.09722 9.16658 5.89944 9.24658 5.74 9.40658C5.58055 9.56658 5.50055 9.76436 5.5 9.99992C5.49944 10.2355 5.57944 10.4335 5.74 10.5941C5.90055 10.7546 6.09833 10.8344 6.33333 10.8333H8ZM3.83333 16.6666C3.375 16.6666 2.98278 16.5035 2.65666 16.1774C2.33055 15.8513 2.16722 15.4588 2.16666 14.9999V4.99992C2.16666 4.54159 2.33 4.14936 2.65666 3.82325C2.98333 3.49714 3.37555 3.33381 3.83333 3.33325H13.8333C14.2917 3.33325 14.6842 3.49659 15.0108 3.82325C15.3375 4.14992 15.5006 4.54214 15.5 4.99992V8.74992L18.125 6.12492C18.2639 5.98603 18.4167 5.95131 18.5833 6.02075C18.75 6.0902 18.8333 6.22214 18.8333 6.41658V13.5833C18.8333 13.7777 18.75 13.9096 18.5833 13.9791C18.4167 14.0485 18.2639 14.0138 18.125 13.8749L15.5 11.2499V14.9999C15.5 15.4583 15.3369 15.8507 15.0108 16.1774C14.6847 16.5041 14.2922 16.6671 13.8333 16.6666H3.83333Z"
                                            fill="black" />
                                    </svg>
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="chat-window" data-active-sender="" style="display:none;">
                        <!-- Messages will be appended here dynamically -->
                        <form class="chat-window-form">
                            <div class="input-form-div" style="display:flex; align-items:center;">
                                <input type="text" id="message-input" placeholder="Write a message..." autocomplete="off" style="flex-grow:1; padding:8px;" />
                                <button type="submit" aria-label="Send message" style="background:none; border:none; cursor:pointer; margin-left:8px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                                        <path d="M2.01 21L23 12L2.01 3L2 10L17 12L2 14L2.01 21Z" fill="#1890FF"/>
                                    </svg>
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!--UI for calling as per mobile phone-->
                    <div id="calling-interface-overlay" style="display:none; position:absolute; top:0; left:0; width:100%; height:100%; background:#25354438; z-index:1000;border-radius: 4px;">
                      <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); background: #fff; border-radius: 16px; box-shadow: 0 8px 24px rgba(0,0,0,0.18); padding:40px; min-width:300px; min-height:200px; text-align:center;">
                          
                          <!-- Caller number -->
                          <span id="call-number" style="display:none; font-size:24px; font-weight:bold; margin-bottom:10px;"></span>
                          
                          <!-- Call status -->
                          <div id="call-status" style="font-size:18px; color:#1890FF; margin-bottom:28px;">Calling...</div>
                          
                          <!-- Incoming call buttons -->
                          <button id="answer-call-btn" style="padding:10px 24px; background:#28a745; color:#fff; border:none; border-radius:6px; margin-bottom:8px; margin-right:8px; display:none;">Answer</button>
                          <button id="decline-call-btn" style="padding:10px 24px; background:#dc3545; color:#fff; border:none; border-radius:6px; margin-bottom:8px; margin-right:8px; display:none;">Decline</button>
                          
                          <!-- Outgoing / In-call buttons -->
                          <button id="end-call-btn" style="padding:10px 24px; background:#FA320A; color:#fff; border:none; border-radius:6px; margin-bottom:8px; margin-right:8px; display:none;">End Call</button>
                          <button id="mute-show" style="padding:10px 18px; background:gray; color:#fff; border:none; border-radius:6px; margin-bottom:8px; margin-right:8px; display:none;">Mute</button>
                          <button id="unmute-show" style="padding:10px 18px; background:gray; color:#fff; border:none; border-radius:6px; margin-bottom:8px; display:none;">Unmute</button>
                      </div>
                    </div>

                </div>
            </div>
            <div class="inner-chatbot-div4"></div>
           
           
              <!-- ✅ Popup Modal  For  Edit the contact details -->
            <div id="editModal" class="modal" style="display:none;">
              <div class="modal-content">
                <span class="close" onclick="closeEditModal()">&times;</span>
                <h3>Edit Contact</h3>
                <form id="editContactForm">
                  <!--<label>Name:</label>-->
                  <input type="text" placeholder="Name" id="editName" required><br><br>
                  <!--<label>Number:</label>-->
                  <input type="text" id="editNumber" required><br><br>
                  <button type="submit">Save</button>
                </form>
              </div>
            </div>
           
        </div>
        </div>
    </section>
 <script  type="text/javascript"> 
 
 ///function for date format start
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return "";
    
        // Case 1: YYYY-MM-DD HH:MM:SS
        let isoMatch = dateTimeStr.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
        if (isoMatch) {
            let [, yyyy, mm, dd, hh, min, ss] = isoMatch;
            return `${mm}/${dd}/${yyyy} ${hh}:${min}:${ss}`;
        }
    
        // Case 2: DD-MM-YYYY hh:mm:ssam/pm
        let customMatch = dateTimeStr.match(/^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2}):(\d{2})(am|pm)$/i);
        if (customMatch) {
            let [, dd, mm, yyyy, hh, min, ss, period] = customMatch;
            hh = parseInt(hh, 10);
            if (period.toLowerCase() === "pm" && hh < 12) hh += 12;
            if (period.toLowerCase() === "am" && hh === 12) hh = 0;
            return `${mm}/${dd}/${yyyy} ${("0"+hh).slice(-2)}:${min}:${ss}`;
        }
    
        // Fallback: try native Date()
        let date = new Date(dateTimeStr.replace(" ", "T"));
        if (!isNaN(date.getTime())) {
            return ("0" + (date.getMonth() + 1)).slice(-2) + "/" +
                   ("0" + date.getDate()).slice(-2) + "/" +
                   date.getFullYear() + " " +
                   ("0" + date.getHours()).slice(-2) + ":" +
                   ("0" + date.getMinutes()).slice(-2) + ":" +
                   ("0" + date.getSeconds()).slice(-2);
        }
    
        return dateTimeStr; // If all fails
    }
  ///function for date format End
document.addEventListener('DOMContentLoaded', () => {
    const tabs = document.querySelectorAll(".tab");
    const panes = document.querySelectorAll(".tab-pane");
    const chatWindow = document.querySelector('.chat-window');
    const messageInput = document.getElementById('message-input');
    const chatForm = document.querySelector('.chat-window-form');
    const chatHeaderNumber = document.getElementById('chat-header-number'); 
    const chatHeaderNumber_only = document.getElementById('chat-header-number-only'); 

    tabs.forEach(tab => {
        tab.addEventListener("click", () => {
            tabs.forEach(t => t.classList.remove("active"));
            panes.forEach(p => p.classList.remove("active"));
            tab.classList.add("active");
            const target = document.getElementById(tab.dataset.tab);
            target.classList.add("active");
        });
    });

    function loadSenders() {
        fetch('fetch_senders.php')
            .then(response => response.json())
            .then(data => {
                const container = document.getElementById('sender-list');
                container.innerHTML = '';
                data.forEach(item => {
                    
                     if (item.Sender === '+13322308524') {
                            return; 
                        }
                    const displayName = item.contact_name ? item.contact_name : item.Sender;
                    const unseenClass = item.Seen === "0" || item.Seen === 0 ? "unseen" : "";
                    const div = document.createElement('div');
                    div.className = `no-profile-img ${unseenClass}`;
                    div.dataset.sender = item.Sender;
                    div.innerHTML = `
                        <svg width="35" height="35" viewBox="0 0 46 46" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <circle cx="23" cy="23" r="23" fill="#E0E0E0"/>
                            <circle cx="23" cy="18" r="8" fill="#BDBDBD"/>
                            <ellipse cx="23" cy="33" rx="12" ry="7" fill="#BDBDBD"/>
                        </svg>
                        <div class="no-profile">
                            <h4>${displayName}</h4>
                            <p>${item.Body}</p>
                        </div>`;
                    div.addEventListener('click', () => {
                        chatWindow.dataset.activeSender = item.Sender;
                        chatWindow.style.display = 'block';
                        
                         // Show the chatbot content section
                    const chatbotContent = document.querySelector('.inner-chatbot-div3-content');
                    if (chatbotContent) chatbotContent.style.display = 'flex';

                        // Update the header for conversation name/number
                        if(chatHeaderNumber) {
                            chatHeaderNumber.textContent = displayName;
                            chatHeaderNumber_only.textContent = item.Sender;
                        }
                        markAsSeen(item.Sender);
                        loadChatMessages(item.Sender);
                        loadSenders();
                    });
                    container.appendChild(div);
                });
            })
            .catch(err => console.error('Failed to load senders:', err));
    }

   const myNumber = "+13322308524";

    function loadChatMessages(sender) {
        fetch('fetch_chat.php?sender=' + encodeURIComponent(sender))
            .then(response => response.json())
            .then(data => {
                const threshold = 80; // px near bottom
                const wasAtBottom = (
                    chatWindow.scrollHeight - chatWindow.scrollTop - chatWindow.clientHeight < threshold
                );
    
                chatWindow.innerHTML = ''; // Clear old messages
    
                data.forEach(msg => {
                   
                    const msgDiv = document.createElement('div');
    
                    if (msg.chat_type === 'message') {
                        const isSent = msg.Sender === myNumber;
                        if (!isSent) {
                            // Received message (left side)
                            msgDiv.className = 'chat-sender-content';
                            msgDiv.innerHTML = `
                                <div class="main-chat-profile">
                                    <div class="main-chat-profile-svg">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" viewBox="0 0 46 46" fill="none">
                                            <circle cx="23" cy="23" r="23" fill="#E0E0E0"/>
                                            <circle cx="23" cy="18" r="8" fill="#BDBDBD"/>
                                            <ellipse cx="23" cy="33" rx="12" ry="7" fill="#BDBDBD"/>
                                        </svg>
                                    </div>
                                    <div class="recived-msg-profile">
                                        <p class="sender-name">${formatDateTime(msg.Date_time)}</p>
                                        <p class="msg-recsend">${msg.Body}</p>
                                    </div>
                                </div>`;
                        } else {
                            // Sent message (right side)
                            msgDiv.className = 'chat-reciver-content';
                            msgDiv.innerHTML = `
                                <div class="recived-msg-profile">
                                    <p class="reciver-name" style="text-align:right;">${formatDateTime(msg.Date_time)}</p>
                                    <p class="msg-recsend sender">${msg.Body}</p>
                                </div>
                                <div class="main-chat-profile">
                                    <div class="main-chat-profile-svg">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" viewBox="0 0 46 46" fill="none">
                                            <circle cx="23" cy="23" r="23" fill="#E0E0E0"/>
                                            <circle cx="23" cy="18" r="8" fill="#BDBDBD"/>
                                            <ellipse cx="23" cy="33" rx="12" ry="7" fill="#BDBDBD"/>
                                        </svg>
                                    </div>
                                </div>`;
                        }
                    } else if (msg.chat_type === 'call') {
                            const isOutgoingCall = msg.Sender === myNumber;
                            msgDiv.className = isOutgoingCall ? 'chat-reciver-content' : 'chat-sender-content';
                        
                            // Call status icons
                            let iconSVG = "";
                            let statusLabel = "";
                            if (msg.Type.toLowerCase() === "missed") {
                                iconSVG = `
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 
                                        viewBox="0 0 24 24" fill="none">
                                        <path d="M7 17L17 7M17 7H8M17 7V16" 
                                            stroke="#FA320A" stroke-width="2" 
                                            stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>`;
                                statusLabel = "Missed Call";
                            } else if (msg.Type.toLowerCase() === "completed") {
                                iconSVG = `
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 
                                        viewBox="0 0 24 24" fill="none">
                                        <path d="M7 17L17 7M17 7H8M17 7V16" 
                                            stroke="#3AD64D" stroke-width="2" 
                                            stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>`;
                                statusLabel = "Call Completed";
                            } else {
                                iconSVG = `
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 
                                        viewBox="0 0 24 24" fill="none">
                                        <circle cx="12" cy="12" r="8" 
                                            stroke="#bababa" stroke-width="2" fill="none"/>
                                    </svg>`;
                                statusLabel = msg.Type.charAt(0).toUpperCase() + msg.Type.slice(1) + " Call";
                            }
                        
                            // Duration
                            let durationText = "";
                            if (msg.Duration !== null && msg.Duration !== undefined) {
                                const d = parseInt(msg.Duration, 10);
                                if (d > 0) {
                                    const mins = Math.floor(d / 60);
                                    const secs = d % 60;
                                    durationText = (mins > 0 ? `${mins}m ` : "") + `${secs}s`;
                                } else {
                                    durationText = "0s";
                                }
                            }
                        
                            const displayName = isOutgoingCall ? "Me" : (msg.Sender || msg.Receiver);
                        
                            // ✅ Conditional avatar placement
                            if (isOutgoingCall) {
                                // Outgoing → text then avatar
                                msgDiv.innerHTML = `
                                    <div class="recived-msg-profile" style="text-align:right;">
                                        <p class="reciver-name" style="margin:0;">${formatDateTime(msg.Date_time)}</p>
                                        <div class="call-bubble" style="max-width: 300px; background:#e5e5e5; padding:10px; border-radius:8px; margin-top:5px; display: inline-flex; align-items: center; gap: 10px;">
                                            <div class="icon">${iconSVG}</div>
                                            <div>
                                                <strong>${statusLabel}</strong>
                                                <div style="font-size: 12px; color: #555;">${msg.Date_time}</div>
                                                <div style="font-size: 12px; color: #333;">Duration: ${durationText}</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="main-chat-profile">
                                        <div class="main-chat-profile-svg">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" 
                                                viewBox="0 0 46 46" fill="none">
                                                <circle cx="23" cy="23" r="23" fill="#E0E0E0"/>
                                                <circle cx="23" cy="18" r="8" fill="#BDBDBD"/>
                                                <ellipse cx="23" cy="33" rx="12" ry="7" fill="#BDBDBD"/>
                                            </svg>
                                        </div>
                                    </div>
                                `;
                            } else {
                                // Incoming → avatar then text
                                msgDiv.innerHTML = `
                                    <div class="main-chat-profile">
                                        <div class="main-chat-profile-svg">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" 
                                                viewBox="0 0 46 46" fill="none">
                                                <circle cx="23" cy="23" r="23" fill="#E0E0E0"/>
                                                <circle cx="23" cy="18" r="8" fill="#BDBDBD"/>
                                                <ellipse cx="23" cy="33" rx="12" ry="7" fill="#BDBDBD"/>
                                            </svg>
                                        </div>
                                    </div>
                                    <div class="recived-msg-profile">
                                        <p class="sender-name" style="margin:0;">${formatDateTime(msg.Date_time)}</p>
                                        <div class="call-bubble" style="max-width: 300px; background:#e5e5e5; padding:10px; border-radius:8px; margin-top:5px; display: inline-flex; align-items: center; gap: 10px;">
                                            <div class="icon">${iconSVG}</div>
                                            <div>
                                                <strong>${statusLabel}</strong>
                                                <div style="font-size: 12px; color: #555;">${msg.Date_time}</div>
                                                <div style="font-size: 12px; color: #333;">Duration: ${durationText}</div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }
                        }


                    chatWindow.appendChild(msgDiv);
                });
    
                // Append message input form
                chatWindow.appendChild(chatForm);
                chatForm.style.display = '';
    
                if (wasAtBottom) {
                    chatWindow.scrollTop = chatWindow.scrollHeight;
                }
            })
            .catch(err => console.error('Failed to load messages:', err));
    }




    function markAsSeen(sender) {
        fetch('mark_seen.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'sender=' + encodeURIComponent(sender)
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                console.log('Marked as seen:', sender);
            } else {
                console.warn('Mark as seen error:', data.message);
            }
        });
    }

    // Send message form handler
    chatForm.addEventListener('submit', (e) => {
        e.preventDefault();
        
        const message = messageInput.value.trim();
        if (!message) return;
        const receiver = chatWindow.dataset.activeSender;
        if (!receiver) {
            alert('Please select a conversation first.');
            return;
        }
        fetch('send_message.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `receiver=${encodeURIComponent(receiver)}&body=${encodeURIComponent(message)}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                messageInput.value = '';
                loadChatMessages(receiver);
            } else {
                alert('Failed to send message: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(() => {
            alert('Error sending message. Please try again.');
        });
    });

    loadSenders();
    setInterval(loadSenders, 5000);
    setInterval(() => {
        const activeSender = chatWindow.dataset.activeSender;
        if (activeSender) {
            loadChatMessages(activeSender);
        }
    }, 5000);
    
                        //TWILLIO CALLING START
                          Twilio.Device.setup("<?php echo $token; ?>");
                			Twilio.Device.ready(function (device) {
                				$("#log").text("Ready");
                			});
                			Twilio.Device.error(function (error) {
                				$('#log').css('color','red');
                				$("#log").text("Error: " + error.message);
                			});
                			Twilio.Device.connect(function (conn) {
                			 let call_sid = conn.customParameters.get('call_sid');
                			    $('#call_sid').val(call_sid);
                				$('#log').css('color','green');
                				$("#log").text("Successfully established call");
                			   });
                
                			Twilio.Device.disconnect(function (conn) {
                				$('#log').css('color','green');
                				$("#log").text("Call ended");
                				loadChatMessages(sender);
                				//  location.reload();
                				//isOngoing = false;
                			});
                			
    //for get the number using the calling button svg
        const msgBoxCallIcon = document.querySelector('.msg-box-call-icon');
        const callingInterface = document.getElementById('calling-interface-overlay');
        const callNumberSpan = document.getElementById('call-number');
        const callStatus = document.getElementById('call-status');
        const chatFormDiv = document.querySelector('.chat-window-form');
        const answerBtn = document.getElementById('answer-call-btn');
        const declineBtn = document.getElementById('decline-call-btn');
        const endCallBtn = document.getElementById('end-call-btn');
        const muteBtn = document.getElementById('mute-show');
        const unmuteBtn = document.getElementById('unmute-show');
        
        let callConnection = null; // <-- shared connection

        // =============== Outgoing Call =================
        if (msgBoxCallIcon) {
            msgBoxCallIcon.addEventListener('click', () => {
                const chatHeader = document.getElementById('chat-header-number-only');
                if (chatHeader) {
                    let phoneNumber = chatHeader.textContent.trim();
        
                    // Show overlay
                    if (callingInterface && callNumberSpan) {
                            callNumberSpan.textContent = phoneNumber;
                            callingInterface.style.display = 'block';
                        }
                    if (chatFormDiv) chatFormDiv.style.display = 'none';
        
                    // Show only Outgoing buttons
                    answerBtn.style.display = 'none';
                    declineBtn.style.display = 'none';
                    endCallBtn.style.display = 'inline-block';
                    muteBtn.style.display = 'inline-block';
                    unmuteBtn.style.display = 'none';
        
                    // Initiate call
                    let params = {
                        "tocall": phoneNumber,
                        "callerid": "+13322308524"
                    };
                    callConnection = Twilio.Device.connect(params);
                    if (callStatus) callStatus.textContent = "Calling... " + phoneNumber;
                }
            });
        }
        
        // =============== Incoming Call =================
        Twilio.Device.incoming(function (conn) {
            callConnection = conn; // store active connection
        
            // Show overlay
            callingInterface.style.display = 'block';
            if (chatFormDiv) chatFormDiv.style.display = 'none';
        
            // Caller number
            callNumberSpan.textContent = conn.parameters.From || "Unknown Caller";
            callStatus.textContent = "Incoming call...";
        
            // Show Answer/Decline
            answerBtn.style.display = 'inline-block';
            declineBtn.style.display = 'inline-block';
        
            // Hide End/Mute/Unmute until answered
            endCallBtn.style.display = 'none';
            muteBtn.style.display = 'none';
            unmuteBtn.style.display = 'none';
        
            // Answer call
            answerBtn.onclick = function () {
                conn.accept();
                callStatus.textContent = "In Call...";
        
                // Swap buttons
                answerBtn.style.display = 'none';
                declineBtn.style.display = 'none';
                endCallBtn.style.display = 'inline-block';
                muteBtn.style.display = 'inline-block';
                unmuteBtn.style.display = 'none';
            };
        
            // Decline call
            declineBtn.onclick = function () {
                conn.reject();
                callingInterface.style.display = 'none';
                if (chatFormDiv) chatFormDiv.style.display = '';
            };
        
            // Call disconnect (after end or remote hangup)
            conn.on('disconnect', function () {
                callConnection = null;
                callingInterface.style.display = 'none';
                if (chatFormDiv) chatFormDiv.style.display = '';
                callStatus.textContent = "Call ended";
        
                // Reset buttons for next call
                answerBtn.style.display = 'none';
                declineBtn.style.display = 'none';
                endCallBtn.style.display = 'none';
                muteBtn.style.display = 'none';
                unmuteBtn.style.display = 'none';
            });
        });
        
        // =============== Common Handlers =================
        // Mute / Unmute
        muteBtn.onclick = function () {
            if (callConnection) {
                callConnection.mute(true);
                muteBtn.style.display = 'none';
                unmuteBtn.style.display = 'inline-block';
            }
        };
        unmuteBtn.onclick = function () {
            if (callConnection) {
                callConnection.mute(false);
                muteBtn.style.display = 'inline-block';
                unmuteBtn.style.display = 'none';
            }
        };
        
        // End Call
        endCallBtn.onclick = function () {
            if (callConnection) {
                callConnection.disconnect();
            }
            callingInterface.style.display = 'none';
            if (chatFormDiv) chatFormDiv.style.display = '';
        };
        
        // When call disconnects (outgoing or incoming)
        Twilio.Device.disconnect(function () {
            callConnection = null; // reset
            callingInterface.style.display = 'none';
            if (chatFormDiv) chatFormDiv.style.display = '';
            if (callStatus) callStatus.textContent = "Call ended";
        });

});


///////Show the contact list
 function loadContacts() {
    $.getJSON("./Chatwoot/get_contacts.php", function (data) {
        let html = "";
        $.each(data, function (index, contact) {
            let name = contact.name && contact.name.trim() !== "" ? contact.name : "Unknown";

            html += `
            <div class="contact-entry-div">
                <div class="contact-number-main">
                    <div class="contact-number-avtar">
                        <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35"
                            viewBox="0 0 35 35" fill="none">
                            <path d="M17.5 30.1C13.125 30.1 9.2575 27.86 7 24.5C7.0525 21 14 19.075 17.5 19.075C21 19.075 27.9475 21 28 24.5C26.8433 26.2229 25.2805 27.6349 23.4495 28.6115C21.6184 29.588 19.5752 30.0992 17.5 30.1ZM17.5 5.25C18.8924 5.25 20.2277 5.80312 21.2123 6.78769C22.1969 7.77226 22.75 9.10761 22.75 10.5C22.75 11.8924 22.1969 13.2277 21.2123 14.2123C20.2277 15.1969 18.8924 15.75 17.5 15.75C16.1076 15.75 14.7723 15.1969 13.7877 14.2123C12.8031 13.2277 12.25 11.8924 12.25 10.5C12.25 9.10761 12.8031 7.77226 13.7877 6.78769C14.7723 5.80312 16.1076 5.25 17.5 5.25ZM17.5 0C15.2019 0 12.9262 0.452651 10.803 1.33211C8.67984 2.21157 6.75066 3.50061 5.12563 5.12563C1.84374 8.40752 0 12.8587 0 17.5C0 22.1413 1.84374 26.5925 5.12563 29.8744C6.75066 31.4994 8.67984 32.7884 10.803 33.6679C12.9262 34.5474 15.2019 35 17.5 35C22.1413 35 26.5925 33.1563 29.8744 29.8744C33.1563 26.5925 35 22.1413 35 17.5C35 7.8225 27.125 0 17.5 0Z" fill="#C3C3C4"></path>
                        </svg>
                    </div>
                    <div class="contact-number-details">
                        <p class="contact-numbers-name">${name}</p>
                        <p class="contact-number-person">${contact.from_number}</p>
                    </div>
                </div>

                <div class="action-icon">
                    <span class="action-label-main">Action
                        <svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px"
                            viewBox="0 0 24 24" fill="none">
                            <path fill-rule="evenodd" clip-rule="evenodd"
                                d="M12.7071 14.7071C12.3166 15.0976 11.6834 15.0976 11.2929 14.7071L6.29289 9.70711C5.90237 9.31658 5.90237 8.68342 6.29289 8.29289C6.68342 7.90237 7.31658 7.90237 7.70711 8.29289L12 12.5858L16.2929 8.29289C16.6834 7.90237 17.3166 7.90237 17.7071 8.29289C18.0976 8.68342 18.0976 9.31658 17.7071 9.70711L12.7071 14.7071Z"
                                fill="#000000" />
                        </svg>
                    </span>
                    <div class="dropdown-menu-action">
                           <div class="dropdown-item-action" onclick="sendMessageToContact('${contact.from_number}')">
                                Send Message
                            </div>
                        <div class="dropdown-item-action" onclick="deleteContact('${contact.from_number}')">Delete
                        </div>
                        <div class="dropdown-item-action" 
                             onclick="openEditModal('${name}','${contact.from_number}')">
                             Edit
                        </div>
                        <div class="dropdown-item-action" onclick="callContact('${contact.from_number}')">
                            Call
                        </div>              
                    </div>
                </div>
            </div>`;
        });

        $("#contacts-list").html(html);
    });
}

// For Edit the contact details start
        let currentContactNumber = "";
    
        function openEditModal(name, number) {
            currentContactNumber = number; 
            $("#editName").val(name);
            $("#editNumber").val(number);
            $("#editModal").css("display", "flex");
        }

        function closeEditModal() {
            $("#editModal").hide();
             // ✅ Check if screen width <= 767px
              if (window.matchMedia("(max-width: 767px)").matches) {
                document.querySelector(".inner-chatbot-div3").style.display = "none";
                loadContacts();
              }
        }
        
        $("#editContactForm").on("submit", function(e) {
            e.preventDefault();
        
            let updatedName = $("#editName").val();
            let updatedNumber = $("#editNumber").val();
        
            $.ajax({
                url: "Update_Contact.php",
                method: "POST",
                data: {
                    old_number: currentContactNumber,
                    name: updatedName,
                    number: updatedNumber
                },
                success: function(response) {
                    closeEditModal();
                    Swal.fire({
                          title: "Updated!",
                          text: response,
                          icon: "success"
                        });
                    loadContacts();
                },
                error: function() {
                    alert("Failed to update contact!");
                }
            });
        });


//For edit the cotact details END


//call contact start  ----------------------------------------------
function callContact(phoneNumber) {

    const callingInterface = document.getElementById('calling-interface-overlay');
    const callNumberSpan = document.getElementById('call-number');
    const callStatus = document.getElementById('call-status');
    const muteBtn = document.getElementById('mute-show');
    const unmuteBtn = document.getElementById('unmute-show');
    const endCallBtn = document.getElementById('end-call-btn');
    const chatFormDiv = document.querySelector('.chat-window-form');
    const chatFormWhole = document.querySelector('.inner-chatbot-div3');

    let callConnection = null;

    if (callingInterface && callNumberSpan) {
        callNumberSpan.textContent = phoneNumber;
        callingInterface.style.display = 'block';
    }
     
    if (chatFormWhole) chatFormWhole.style.display = 'none';

    // ✅ Check if screen width <= 767px
              if (window.matchMedia("(max-width: 767px)").matches) {
                document.querySelector(".inner-chatbot-div3").style.position = "absolute";
                loadContacts();
              }

    let params = {
        "tocall": phoneNumber,
        "callerid": "+13322308524"
    };
    callConnection = Twilio.Device.connect(params);

    if (callStatus) callStatus.textContent = "Calling...";

    if (muteBtn && unmuteBtn) {
        muteBtn.onclick = function () {
            if (callConnection) {
                callConnection.mute(true);
                muteBtn.style.display = 'none';
                unmuteBtn.style.display = 'inline-block';
            }
        };
        unmuteBtn.onclick = function () {
            if (callConnection) {
                callConnection.mute(false);
                muteBtn.style.display = 'inline-block';
                unmuteBtn.style.display = 'none';
            }
        };
    }

    // End call button logic
      if (endCallBtn) {
          endCallBtn.onclick = function () {
            if (callConnection) {
              callConnection.disconnect();
        
              // ✅ Check if screen width <= 767px
              if (window.matchMedia("(max-width: 767px)").matches) {
                document.querySelector(".inner-chatbot-div3").style.position = "relative";
                loadContacts();
              }
            }
        
            if (callingInterface) callingInterface.style.display = "none";
            if (chatFormWhole) chatFormWhole.style.display = '';
            if (chatFormDiv) chatFormDiv.style.display = '';
          };
        }


    // Twilio event handlers for status/UI management
    Twilio.Device.connect(function(conn) {
        if (callStatus) callStatus.textContent = "In Call...";
    });
    Twilio.Device.disconnect(function(conn) {
        if (callingInterface) callingInterface.style.display = 'none';
        if (chatFormWhole) chatFormWhole.style.display = "";
        if (chatFormDiv) chatFormDiv.style.display = '';
        if (callStatus) callStatus.textContent = "Call ended";
    });
    Twilio.Device.error(function(err) {
        if (callStatus) callStatus.textContent = "Error: " + err.message;
    });
}

//call contact end----------------------------------------

// delete contact
function deleteContact(phoneNumber) {
    if (confirm(`Are you sure you want to delete contact: ${phoneNumber}?`)) {
        $.ajax({
            url: './Chatwoot/delete_contact.php',
            type: 'POST',
            data: { phoneNumber: phoneNumber },
            success: function (res) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: 'Contact deleted successfully.',
                    confirmButtonColor: '#3085d6'
                });
                loadContacts(); 
            },
            error: function () {
                alert('Error deleting contact');
            }
        });
    }
}

//send msg from the contacts
function sendMessageToContact(phoneNumber) {
    // Show chat section
    const chatWindow = document.querySelector('.chat-window');
    const chatbotContent = document.querySelector('.inner-chatbot-div3-content');
    const chatHeaderNumber = document.getElementById('chat-header-number');
    const chatHeaderNumber_only = document.getElementById('chat-header-number-only');

    if (chatbotContent) chatbotContent.style.display = 'flex';
    if (chatWindow) chatWindow.style.display = 'block';

    // Set headers
    if (chatHeaderNumber) chatHeaderNumber.textContent = phoneNumber;
    if (chatHeaderNumber_only) chatHeaderNumber_only.textContent = phoneNumber;

    // Mark active sender
    if (chatWindow) chatWindow.dataset.activeSender = phoneNumber;

    // Clear previous messages and show input box
    chatWindow.innerHTML = '';
    const chatForm = document.querySelector('.chat-window-form');
    if (chatForm) {
        chatWindow.appendChild(chatForm);
        chatForm.style.display = '';
    }

    // Optionally, load previous chat messages if available
    loadChatMessages(phoneNumber);
}


//load call logs
function loadCallLogs() {
    $.ajax({
        url: "get_call_logs.php",
        method: "GET",
        dataType: "json",
        success: function(data) {
                let html = "";
                data.forEach(function(call) {
                    let statusIcon = "";
                    let statusClass = "";
                    let statusColor = "";
                    let displayName = "";
                    let phoneNumber = "";
            
                    // ✅ Outgoing vs Incoming
                    if (call.caller === "+13322308524") {
                        displayName = call.receiver_name || call.receiver;
                        phoneNumber = call.receiver;
                    } else {
                        displayName = call.caller_name || call.caller;
                        phoneNumber = call.caller;
                    }
            
                    // ✅ Call status color
                    if (call.CallStatus.toLowerCase() === "missed") {
                        statusColor = "#FA320A";
                        statusClass = "missedcall-name";
                    } else if (call.CallStatus.toLowerCase() === "completed") {
                        statusColor = "#3AD64D";
                    } else if (call.CallStatus.toLowerCase() === "busy") {
                        statusColor = "#FFC107";
                    }
            
                    statusIcon = `
                        <svg xmlns="http://www.w3.org/2000/svg" width="14px" height="14px"
                            viewBox="0 0 24 24" fill="none">
                            <path d="M7 17L17 7M17 7H8M17 7V16" 
                                stroke="${statusColor}" 
                                stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    `;
            
                    // ✅ embed phone number as data attribute
                    html += `
                    <div class="main-wrapper">
                    <div class="call-logs-div">
                         <div class="inner-logs-svg">
                            <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35"
                                viewBox="0 0 35 35" fill="none">
                                <path
                                    d="M17.5 30.1C13.125 30.1 9.2575 27.86 7 24.5C7.0525 21 14 19.075 17.5 19.075C21 19.075 27.9475 21 28 24.5C26.8433 26.2229 25.2805 27.6349 23.4495 28.6115C21.6184 29.588 19.5752 30.0992 17.5 30.1ZM17.5 5.25C18.8924 5.25 20.2277 5.80312 21.2123 6.78769C22.1969 7.77226 22.75 9.10761 22.75 10.5C22.75 11.8924 22.1969 13.2277 21.2123 14.2123C20.2277 15.1969 18.8924 15.75 17.5 15.75C16.1076 15.75 14.7723 15.1969 13.7877 14.2123C12.8031 13.2277 12.25 11.8924 12.25 10.5C12.25 9.10761 12.8031 7.77226 13.7877 6.78769C14.7723 5.80312 16.1076 5.25 17.5 5.25ZM17.5 0C15.2019 0 12.9262 0.452651 10.803 1.33211C8.67984 2.21157 6.75066 3.50061 5.12563 5.12563C1.84374 8.40752 0 12.8587 0 17.5C0 22.1413 1.84374 26.5925 5.12563 29.8744C6.75066 31.4994 8.67984 32.7884 10.803 33.6679C12.9262 34.5474 15.2019 35 17.5 35C22.1413 35 26.5925 33.1563 29.8744 29.8744C33.1563 26.5925 35 22.1413 35 17.5C35 7.8225 27.125 0 17.5 0Z"
                                    fill="#C3C3C4"></path>
                            </svg>
                        </div>
                        <div class="recived-msg-profile">
                            <p class="caller-name ${statusClass}">${displayName}</p>
                            <p class="caller-timing ${statusClass}">
                                ${statusIcon} ${call.Date_time} (${call.CallStatus})
                            </p>
                        </div>
                        </div>
                        <div class="msg-box-call-icon" data-number="${phoneNumber}">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"
                                 viewBox="0 0 20 20" fill="none">
                                <path d="M17.5 12.8833L13.1083 12.375L11.0083 14.475C8.64283 13.2716 6.72005 
                                         11.3488 5.51667 8.98333L7.625 6.875L7.11667 2.5H2.525C2.04167 
                                         10.9833 9.01667 17.9583 17.5 17.475V12.8833Z"
                                      fill="#131313" />
                            </svg>
                        </div>
                    </div>`;
                });
            
                $("#callLogsContainer").html(html);
            
                // ✅ Add click listeners to all icons
                document.querySelectorAll('.msg-box-call-icon').forEach(icon => {
                    icon.addEventListener('click', function () {
                        let phoneNumber = this.getAttribute('data-number');
                        makeTwilioCall(phoneNumber);
                    });
                });
            }

    });
}

function makeTwilioCall(phoneNumber) {

    const callingInterface = document.getElementById('calling-interface-overlay');
    const callNumberSpan = document.getElementById('call-number');
    const callStatus = document.getElementById('call-status');
    const muteBtn = document.getElementById('mute-show');
    const unmuteBtn = document.getElementById('unmute-show');
    const endCallBtn = document.getElementById('end-call-btn');
    const chatFormDiv = document.querySelector('.chat-window-form');
    const chatFormWhole = document.querySelector('.inner-chatbot-div3');

    let callConnection = null;

    if (callingInterface && callNumberSpan) {
        callNumberSpan.textContent = phoneNumber;
        callingInterface.style.display = 'block';
    }
     
     if (chatFormWhole) chatFormWhole.style.display = 'block';

    // ✅ Check if screen width <= 767px
              if (window.matchMedia("(max-width: 767px)").matches) {
                document.querySelector(".inner-chatbot-div3").style.position = "absolute";
                loadContacts();
              }

    let params = {
        "tocall": phoneNumber,
        "callerid": "+13322308524"
    };
    callConnection = Twilio.Device.connect(params);

    if (callStatus) callStatus.textContent = "Calling...";

    if (muteBtn && unmuteBtn) {
        muteBtn.onclick = function () {
            if (callConnection) {
                callConnection.mute(true);
                muteBtn.style.display = 'none';
                unmuteBtn.style.display = 'inline-block';
            }
        };
        unmuteBtn.onclick = function () {
            if (callConnection) {
                callConnection.mute(false);
                muteBtn.style.display = 'inline-block';
                unmuteBtn.style.display = 'none';
            }
        };
    }

    // End call button logic
      if (endCallBtn) {
          endCallBtn.onclick = function () {
            if (callConnection) {
              callConnection.disconnect();
        
              // ✅ Check if screen width <= 767px
              if (window.matchMedia("(max-width: 767px)").matches) {
                document.querySelector(".inner-chatbot-div3").style.position = "relative";
                loadContacts();
              }
            }
        
            if (callingInterface) callingInterface.style.display = "none";
            if (chatFormWhole) chatFormWhole.style.display = '';
            if (chatFormDiv) chatFormDiv.style.display = '';
          };
        }


    // Twilio event handlers for status/UI management
    Twilio.Device.connect(function(conn) {
        if (callStatus) callStatus.textContent = "In Call...";
    });
    Twilio.Device.disconnect(function(conn) {
        if (callingInterface) callingInterface.style.display = 'none';
        if (chatFormWhole) chatFormWhole.style.display = "";
        if (chatFormDiv) chatFormDiv.style.display = '';
        if (callStatus) callStatus.textContent = "Call ended";
    });
    Twilio.Device.error(function(err) {
        if (callStatus) callStatus.textContent = "Error: " + err.message;
    });
}

// run once on page load
$(document).ready(function () {
    loadContacts();
    loadCallLogs();

    setInterval(loadContacts, 10000);
     setInterval(loadCallLogs, 10000);
});




///////////////
$(document).ready(function () {
 
    if (window.innerWidth <= 768) {
        $('#sender-list').on('click', '.no-profile-img', function () {
            $('.inner-chatbot-div3').css('display', 'block');
        });
 
        $(document).on('click', '.dropdown-item-action', function () {
            $('.inner-chatbot-div3').css('display', 'block');
        });
 
        $(document).on('click', '.chatbot-profile-img', function () {
            $('.inner-chatbot-div3').css('display', 'none');
        });
    }
});
</script>
	<script src="//media.twiliocdn.com/sdk/js/client/v1.13/twilio.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</body>

</html>