<?php
require_once 'vendor/autoload.php';
 require_once 'dashboard.php'; 

use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\VoiceGrant;

$accountSid  = 'AC8bac449b32a1fe6070f736d142cbac1f';
$apiKeySid   = 'SK376e8cce2cdba3d10ab30fdcae209b93';     
$apiKeySecret= 'xbs1EsKlGXMqrAizpOudfPFLcl1vYBVM';   
$appSid      = 'APedefbaf42f7a84fd6ee4d1be02f6ca1a';


$identity = 'Jonathan';
$ttl = 3600;

$token = new AccessToken(
    $accountSid,
    $apiKeySid,
    $apiKeySecret,
    $ttl,
    $identity
);
$voiceGrant = new VoiceGrant();
$voiceGrant->setOutgoingApplicationSid($appSid);
$voiceGrant->setIncomingAllow(true);
$token->addGrant($voiceGrant);
// $date = DateTime::createFromFormat('d-m-Y', date('d-m-Y'));
// $compareDate = DateTime::createFromFormat('d-m-Y', '30-01-2026');

// if ($date < $compareDate) {
//     $jwt = $token->toJWT();
// }
 $jwt = $token->toJWT();

?>
<!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%);*/
/*}*/
.chat-window-form button {
    position: absolute;
    right: 13px;
    top: 21px;
    transform: translateY(-50%);
}
.image-upload-button{
    position: absolute;
    right: 60px;
    top: 9px;
}
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" enctype="multipart/form-data">
                            <div class="input-form-div" style="display:flex; align-items:center; gap:12px;">
                                <input type="text" id="message-input" placeholder="Write a message..." autocomplete="off" style="flex-grow:1; padding:8px;" />
                                
                                <label class="image-upload-button" for="image-upload" style="cursor:pointer;">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4m14-7l-5-5m0 0l-5 5m5-5v12" stroke="#1890FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </label>
                                <input type="file" id="image-upload" accept="image/*" style="display:none;" />
                                
                                <button type="submit" aria-label="Send message" style="background:none; border:none; cursor:pointer;">
                                    <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>
    
    <!--Notification Sound-->
    <audio id="msgNotification" src="ping-msg.mp3" preload="auto"></audio>

 <script  type="text/javascript"> 
 
 
 // Cache contacts to avoid repeated AJAX calls
    let contactsCache = null;
    
    async function getContactName(phoneNumber) {
        if (!contactsCache) {
            try {
                const response = await fetch('./Chatwoot/get_contacts.php');
                contactsCache = await response.json();
            } catch (err) {
                console.error("Failed to load contacts cache:", err);
                return phoneNumber; // fallback
            }
        }
    
        // Clean number for comparison (remove + if present)
        const cleanNum = phoneNumber.replace(/^\+/, '');
    
        const contact = contactsCache.find(c => 
            c.from_number && c.from_number.replace(/^\+/, '') === cleanNum
        );
    
        if (contact && contact.name && contact.name.trim() !== "") {
            return contact.name.trim();
        }
    
        return phoneNumber; // fallback to number if no name
    }
     function playNotificationSound() {
                const audio = document.getElementById("msgNotification");
                if (audio) {
                    audio.currentTime = 0;
                    audio.play().catch(err => {
                        console.warn("Autoplay blocked until user interacts:", err);
                    });
                }
             }
     
    function Check_New_SmsPING_SOUND() {
            var response = '';
            $.ajax({
                type: "GET",
                url: "Get_Latest_sms.php",
                success: function(text) {
                    response = text;
                    if (response && response.length > 0 && response[0].Ping_sound === '0') {
                        var id = response[0].id;
                        playNotificationSound();
                        Update_Ping_SMS(id);
                    }
                }
            });
        }
    
     
     function Update_Ping_SMS(id){
             $.ajax({
                url: "Update_Ping_SMS.php",
                type: "POST",    
                data: {
                    Ping_id: id,
                },
                success: function(response) {
                
                },
                error: function() {
                    alert("error");
                }    
            });    
         }
  
 ///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
    }
    
            let device;
            let callConnection = null;
            const token = "<?php echo $jwt; ?>";
            
            // ──── Shared variables for the calling screen ────
        const callingInterface = document.getElementById('calling-interface-overlay');
        const callNumberSpan   = document.getElementById('call-number');
        const callStatus       = document.getElementById('call-status');
        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');
        const chatFormDiv      = document.querySelector('.chat-window-form');
        
        async function makeCall(phoneNumber) {
            let params = {
                To: phoneNumber,
                CallerId: "+13322308524"   // ← your Twilio number
            };
        
            try {
                callStatus.textContent = "Calling... " + phoneNumber;
        
                callConnection = await device.connect({ params });
        
                // Listen for end of call
                callConnection.on("disconnect", () => {
                    resetCallingUI("Call ended");   // ← we'll define reset below
                });
        
            } catch (err) {
                console.error("Call failed:", err);
                callStatus.textContent = "Call failed: " + (err.message || "Unknown error");
                setTimeout(() => resetCallingUI(), 2000);
            }
        }
        
        function resetCallingUI(message = "Call ended") {
                if (callConnection) {
                    callConnection.disconnect();
                    callConnection = null;
                }
                if (callingInterface) callingInterface.style.display = 'none';
                if (chatFormDiv)      chatFormDiv.style.display = '';
                if (callStatus)       callStatus.textContent = message;
            
                if (answerBtn)   answerBtn.style.display   = 'none';
                if (declineBtn)  declineBtn.style.display  = 'none';
                if (endCallBtn)  endCallBtn.style.display  = 'none';
                if (muteBtn)     muteBtn.style.display     = 'none';
                if (unmuteBtn)   unmuteBtn.style.display   = 'none';
            }
  ///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 => {
                // Skip this specific sender
                if (item.Sender === '+13322308524') {
                    return; 
                }

                const displayName = item.contact_name ? item.contact_name : item.Sender;
                
                // Check if unseen
                const isUnseen = item.Seen === "0" || item.Seen === 0;

                // Create div
                const div = document.createElement('div');
                div.className = 'no-profile-img';
                div.dataset.sender = item.Sender;

                // ✅ Apply blue background if unseen
                if (isUnseen) {
                    div.style.backgroundColor = '#ADD8E6'; 
                    div.style.color = 'white';
                }

                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>
                    </div>
                `;

                div.addEventListener('click', () => {
                    chatWindow.dataset.activeSender = item.Sender;
                    chatWindow.style.display = 'block';

                    const chatbotContent = document.querySelector('.inner-chatbot-div3-content');
                    if (chatbotContent) chatbotContent.style.display = 'flex';

                    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) {
           
        // Save the current input state
        const messageInput = document.getElementById('message-input');
        const inputValue = messageInput.value;
        const isFocused = document.activeElement === messageInput;
    
        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;
                        
                            // Build message content (text + optional image)
                            let messageContent = "";
                            if (msg.Body && msg.Body.trim() !== "") {
                                messageContent += `<p class="msg-recsend${isSent ? ' sender' : ''}">${msg.Body}</p>`;
                            }
                            if (msg.Image && msg.Image.trim() !== "") {
                                // If your DB stores only filename, prepend your upload path here:
                                const imageUrl = msg.Image.startsWith("http") ? msg.Image : "/haven/images/" + msg.Image;
                                messageContent += `<img src="${imageUrl}" alt="Image" style="max-width:200px; border-radius:8px; margin-top:5px;">`;
                            }
                        
                            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>
                                            ${messageContent}
                                        </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>
                                        ${messageContent}
                                    </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';
    
                        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";
                        }
    
                        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);
    
                        if (isOutgoingCall) {
                            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 {
                            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 = '';
    
                // Restore input state
                messageInput.value = inputValue;
                if (isFocused) {
                    messageInput.focus();
                    // Move cursor to the end of the text
                    messageInput.setSelectionRange(inputValue.length, inputValue.length);
                }
    
                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', function(e) {
        e.preventDefault();
    
        const receiver = chatWindow.dataset.activeSender;
    
        const message = $('#message-input').val().trim();
        const file = $('#image-upload')[0].files[0];
        if (!message && !file) return;
    
        // File validation
        if (file) {
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
            const maxSize = 5 * 1024 * 1024; // 5MB
            if (!allowedTypes.includes(file.type)) {
                alert('Only JPEG, PNG, or GIF images are allowed.');
                return;
            }
            if (file.size > maxSize) {
                alert('File size exceeds 5MB limit.');
                return;
            }
        }
    
        // Sanitize message
        const sanitizedMessage = message ? message.replace(/[<>]/g, '') : '';
    
        const formData = new FormData();
        formData.append('receiver', receiver);
        if (sanitizedMessage) formData.append('body', sanitizedMessage);
        if (file) formData.append('file', file);
    
        $.ajax({
            type: "POST",
            url: "send_message.php",
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            beforeSend: function() {
                $('#message-input').prop('disabled', true);
                $('button[type="submit"]').prop('disabled', true);
            },
            success: function(data) {
                
                if (data.status === 'success') {
                    $('.chat-window-form')[0].reset();
                     // Reset file label back to upload icon
                $('#image-upload').siblings('label').html(`
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" 
                         viewBox="0 0 24 24" fill="none">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4m14-7l-5-5m0 0l-5 5m5-5v12" 
                              stroke="#1890FF" stroke-width="2" stroke-linecap="round" 
                              stroke-linejoin="round"/>
                    </svg>
                `);
                    loadChatMessages(receiver);
                } else {
                    alert('Failed to send message: ' + (data.message || 'Unknown error'));
                }
            },
            error: function() {
                alert('Error sending message. Please try again.');
            },
            complete: function() {
                $('#message-input').prop('disabled', false);
                $('button[type="submit"]').prop('disabled', false);
            }
        });
    });

    // Display selected file name
    $('#image-upload').on('change', function() {
        const fileName = this.files[0]?.name;
        if (fileName) {
            $(this).siblings('label').text(fileName);
        } else {
            // If no file selected, show upload icon
            $(this).siblings('label').html(`
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" 
                     viewBox="0 0 24 24" fill="none">
                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4m14-7l-5-5m0 0l-5 5m5-5v12" 
                          stroke="#1890FF" stroke-width="2" stroke-linecap="round" 
                          stroke-linejoin="round"/>
                </svg>
            `);
        }
    });


    loadSenders();
    setInterval(loadSenders, 5000);
    setInterval(() => {
        const activeSender = chatWindow.dataset.activeSender;
        if (activeSender) {
            loadChatMessages(activeSender);
        }
    }, 5000);
    
                        //TWILLIO CALLING START
        
            // UI Elements
            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');
        
            // Initialize Device
            async function initializeDevice() {
                device = new Twilio.Device(token, {
                    logLevel: 1,
                    codecPreferences: ["opus", "pcmu"],
                });
        
                addDeviceListeners(device);
        
                try {
                    await device.register();
                } catch (err) {
                    $("#log").css('color', 'red').text("Registration failed: " + err.message);
                }
            }
        
            function addDeviceListeners(device) {
                device.on("registered", () => {
                    $("#log").css('color','green').text("Ready you can place calls now");
                });
        
                device.on("error", (error) => {
                    $("#log").css('color','red').text("Error: " + error.message);
                });
        
                device.on("incoming", handleIncomingCall);
            }
        
            // ================= Outgoing Call =================
            async function makeCall(phoneNumber) {
                    let params = {
                        To: phoneNumber,
                        CallerId: "+13322308524"
                    };
                
                    try {
                        callStatus.textContent = "Calling... " + phoneNumber;
                        
                        callConnection = await device.connect({ params });
                
                        // Now you have a Call object, safe to bind events
                        callConnection.on("disconnect", () => resetUI("Call ended"));
                
                    } catch (err) {
                        console.error("Call failed:", err);
                        resetUI("Call failed");
                    }
                }

            if (msgBoxCallIcon) {
                msgBoxCallIcon.addEventListener('click', async () => {
                    const chatHeader = document.getElementById('chat-header-number-only');
                    if (!chatHeader) return;
            
                    let phoneNumber = chatHeader.textContent.trim();
            
                    // Resolve display name
                    const displayName = await getContactName(phoneNumber);
            
                    // Update UI with name
                    callNumberSpan.textContent = displayName;
                    callNumberSpan.style.display = 'block';
            
                    // Also update header if visible
                    const chatHeaderName = document.getElementById('chat-header-number');
                    if (chatHeaderName) chatHeaderName.textContent = displayName;
            
                    // Show overlay
                    callingInterface.style.display = 'block';
                    if (chatFormDiv) chatFormDiv.style.display = 'none';
            
                    // Show outgoing buttons
                    answerBtn.style.display = 'none';
                    declineBtn.style.display = 'none';
                    endCallBtn.style.display = 'inline-block';
                    muteBtn.style.display = 'inline-block';
                    unmuteBtn.style.display = 'none';
            
                    // Start the call
                    await makeCall(phoneNumber);
                });
            }
        
            // ================= Incoming Call =================
            async function handleIncomingCall(conn) {
                callConnection = conn;
            
                callingInterface.style.display = 'block';
                if (chatFormDiv) chatFormDiv.style.display = 'none';
            
                let callerNumber = conn.parameters.From || conn.parameters.Caller || "Unknown Caller";
                const displayName = await getContactName(callerNumber);
            
                callNumberSpan.textContent = displayName;
                callNumberSpan.style.display = 'block';
                callStatus.textContent = "Incoming call...";
            
                // Show Answer/Decline
                answerBtn.style.display = 'inline-block';
                declineBtn.style.display = 'inline-block';
                endCallBtn.style.display = 'none';
                muteBtn.style.display = 'none';
                unmuteBtn.style.display = 'none';
            
                answerBtn.onclick = async () => {
                    conn.accept();
                    callStatus.textContent = "In call with " + displayName;
            
                    answerBtn.style.display = 'none';
                    declineBtn.style.display = 'none';
                    endCallBtn.style.display = 'inline-block';
                    muteBtn.style.display = 'inline-block';
                };
            
                declineBtn.onclick = () => {
                    conn.reject();
                    resetUI("Call declined");
                };
            
                conn.on("cancel", () => resetUI("Call cancelled"));
                conn.on("disconnect", () => resetUI("Call ended"));
            }
        
            // ================= Common Controls =================
            muteBtn.onclick = () => {
                if (callConnection) {
                    callConnection.mute(true);
                    muteBtn.style.display = 'none';
                    unmuteBtn.style.display = 'inline-block';
                }
            };
        
            unmuteBtn.onclick = () => {
                if (callConnection) {
                    callConnection.mute(false);
                    muteBtn.style.display = 'inline-block';
                    unmuteBtn.style.display = 'none';
                }
            };
        
            endCallBtn.onclick = () => {
                if (callConnection) {
                    callConnection.disconnect();
                }
                resetUI("Call ended");
            };
        
            function resetUI(status) {
                callConnection = null;
                callingInterface.style.display = 'none';
                if (chatFormDiv) chatFormDiv.style.display = '';
                if (callStatus) callStatus.textContent = status;
        
                answerBtn.style.display = 'none';
                declineBtn.style.display = 'none';
                endCallBtn.style.display = 'none';
                muteBtn.style.display = 'none';
                unmuteBtn.style.display = 'none';
            }
        
            // Start everything
            initializeDevice();

});


///////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  ----------------------------------------------
async function callContact(phoneNumber) {
    // Get the contact name first (this is the key fix!)
    const displayName = await getContactName(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');

    // Show name instead of number
    callNumberSpan.textContent = displayName;
    callNumberSpan.style.display = 'block';

    callingInterface.style.display = 'block';
    if (chatFormDiv) chatFormDiv.style.display = 'none';

    // Mobile view fix
    if (window.matchMedia("(max-width: 767px)").matches) {
        document.querySelector(".inner-chatbot-div3").style.position = "absolute";
    }

    try {
        const conn = await device.connect({
            params: {
                To: phoneNumber,
                CallerId: "+13322308524"
            }
        });

        callConnection = conn;
        callStatus.textContent = `Calling ${displayName}...`;

        endCallBtn.style.display = 'inline-block';
        muteBtn.style.display = 'inline-block';
        unmuteBtn.style.display = 'none';

        muteBtn.onclick = () => {
            conn.mute(true);
            muteBtn.style.display = 'none';
            unmuteBtn.style.display = 'inline-block';
        };

        unmuteBtn.onclick = () => {
            conn.mute(false);
            muteBtn.style.display = 'inline-block';
            unmuteBtn.style.display = 'none';
        };

        endCallBtn.onclick = () => {
            conn.disconnect();
            resetUI();
        };

        conn.on('disconnect', () => resetUI());
    } catch (err) {
        console.error('Call failed:', err);
        callStatus.textContent = "Call failed";
    }

    function resetUI() {
        callingInterface.style.display = 'none';
        if (chatFormDiv) chatFormDiv.style.display = '';
        callStatus.textContent = "Call ended";
        muteBtn.style.display = 'none';
        unmuteBtn.style.display = 'none';
        endCallBtn.style.display = 'none';
    }
}


//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) {
    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;

    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);
            
       document.querySelectorAll('.msg-box-call-icon').forEach(icon => {
                    icon.addEventListener('click', async function () {
                        const phoneNumber = this.getAttribute('data-number');
                        if (!phoneNumber) return;
                
                        const displayName = await getContactName(phoneNumber);
                
                        callNumberSpan.textContent = displayName;
                        callNumberSpan.style.display = 'block';
                        callStatus.textContent = `Calling ${displayName}...`;
                
                        callingInterface.style.display = 'block';
                        if (chatFormDiv) chatFormDiv.style.display = 'none';
                
                        answerBtn.style.display   = 'none';
                        declineBtn.style.display  = 'none';
                        endCallBtn.style.display  = 'inline-block';
                        muteBtn.style.display     = 'inline-block';
                        unmuteBtn.style.display   = 'none';
                
                        // Now this should work because makeCall is global
                        await makeCall(phoneNumber);
                    });
                });
            }

    });
}

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

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




///////////////
$(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>
		 <!-- Local Twilio Client SDK -->
<script src="js/twilio.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.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>