<?php
// Set agar cookie session tidak mati saat browser ditutup
ini_set('session.cookie_lifetime', 2592000);
ini_set('session.gc_maxlifetime', 2592000);
session_start();

// ==============================================================
// SISTEM AUTO-LOGIN (ANTI-LOGOUT) UNTUK APK
// ==============================================================
if (!isset($_SESSION['user_id'])) {
    if (isset($_COOKIE['omni_uid']) && isset($_COOKIE['omni_role'])) {
        $_SESSION['user_id']  = $_COOKIE['omni_uid'];
        $_SESSION['role']     = $_COOKIE['omni_role'];
        $_SESSION['name']     = $_COOKIE['omni_name'];
        $_SESSION['username'] = isset($_COOKIE['omni_uname']) ? $_COOKIE['omni_uname'] : '';
    } else {
        header("Location: login.php");
        exit;
    }
}

$host = 'localhost';
$user = 'majapahi_omnich';
$pass = 'A1b2c3d4.,@';
$db   = 'majapahi_omnich';
$conn = new mysqli($host, $user, $pass, $db);

// ==============================================================
// FIX: SINKRONISASI & KALKULASI ZONA WAKTU OTOMATIS
// ==============================================================
date_default_timezone_set('Asia/Jakarta');

// Menghitung selisih (offset) antara waktu PHP (WIB) dengan waktu bawaan Database
$res_db_time = $conn->query("SELECT NOW() as db_time");
$db_time_str = $res_db_time->fetch_assoc()['db_time'];
$diff_seconds = time() - strtotime($db_time_str);
// Membulatkan ke jam terdekat untuk mencegah offset meleset beberapa detik
$offset_seconds = round($diff_seconds / 3600) * 3600; 

// Fungsi Helper untuk menyesuaikan waktu database ke WIB di layar
function fixTime($tanggal_db) {
    global $offset_seconds;
    return strtotime($tanggal_db) + $offset_seconds;
}
// ==============================================================


$is_admin = (isset($_SESSION['role']) && $_SESSION['role'] === 'admin');

$active_phone = isset($_GET['phone']) ? $conn->real_escape_string($_GET['phone']) : '';
$tab = (isset($_GET['tab']) && $_GET['tab'] == 'closed') ? 'closed' : 'open';

$nomor_tujuan = isset($_GET['nomor_tujuan']) ? $conn->real_escape_string($_GET['nomor_tujuan']) : '';
$pesan_teks   = isset($_GET['pesan_teks']) ? $_GET['pesan_teks'] : '';

if (empty($active_phone) && !empty($nomor_tujuan)) {
    $active_phone = $nomor_tujuan;
    $cs_name = $conn->real_escape_string($_SESSION['name']);
    
    $cek_kontak = $conn->query("SELECT id, assigned_to, status FROM contacts WHERE phone_number = '$active_phone'");
    
    if ($cek_kontak && $cek_kontak->num_rows > 0) {
        $ktk = $cek_kontak->fetch_assoc();
        if (empty($ktk['assigned_to']) || $ktk['status'] == 'closed') {
            $conn->query("UPDATE contacts SET assigned_to = '$cs_name', status = 'open' WHERE phone_number = '$active_phone'");
        }
    } else {
        $conn->query("INSERT INTO contacts (phone_number, name, status, assigned_to) VALUES ('$active_phone', 'Pelanggan Baru', 'open', '$cs_name')");
    }
}

if ($active_phone) {
    $conn->query("UPDATE messages SET is_read = 1 WHERE phone_number = '$active_phone' AND type = 'in'");
}

// FIX QUERY: Menambahkan last_msg_time agar jam di daftar kontak kiri selalu update
$contacts_sql = "SELECT c.*, 
    (SELECT COUNT(*) FROM messages m WHERE m.phone_number = c.phone_number AND m.is_read = 0 AND m.type = 'in') as unread_count,
    (SELECT type FROM messages m WHERE m.phone_number = c.phone_number ORDER BY created_at DESC LIMIT 1) as last_msg_type,
    (SELECT created_at FROM messages m WHERE m.phone_number = c.phone_number ORDER BY created_at DESC LIMIT 1) as last_msg_time,
    (SELECT TIMESTAMPDIFF(MINUTE, MAX(created_at), NOW()) FROM messages m WHERE m.phone_number = c.phone_number) as wait_time
    FROM contacts c 
    WHERE c.status = '$tab' 
    ORDER BY (SELECT MAX(created_at) FROM messages m WHERE m.phone_number = c.phone_number) DESC";
$contacts = $conn->query($contacts_sql);

$quick_replies = [];
$qr_query = $conn->query("SELECT * FROM quick_replies ORDER BY id ASC");
if ($qr_query) { while($row = $qr_query->fetch_assoc()) { $quick_replies[] = $row; } }

$fwd_contacts = [];
$fc_query = $conn->query("SELECT * FROM forward_contacts ORDER BY name ASC");
if ($fc_query) { while($row = $fc_query->fetch_assoc()) { $fwd_contacts[] = $row; } }

$available_devices = [];
$dev_query = $conn->query("SELECT DISTINCT device_number FROM messages WHERE device_number IS NOT NULL AND device_number != ''");
if ($dev_query) { while($row = $dev_query->fetch_assoc()) { $available_devices[] = $row['device_number']; } }

$messages = []; 
$active_name = "Pelanggan Baru"; 
$active_device = ""; 
$active_status = "open";
$active_notes = "";
$active_label = "";
$active_assigned_to = "";
$chat_history_dates = [];

if ($active_phone) {
    $res_contact = $conn->query("SELECT name, status, notes, label, assigned_to FROM contacts WHERE phone_number = '$active_phone'");
    if($res_contact->num_rows > 0) {
        $contact_data = $res_contact->fetch_assoc();
        $active_name = $contact_data['name'];
        $active_status = $contact_data['status'];
        $active_notes = isset($contact_data['notes']) ? $contact_data['notes'] : '';
        $active_label = isset($contact_data['label']) ? $contact_data['label'] : '';
        $active_assigned_to = isset($contact_data['assigned_to']) ? $contact_data['assigned_to'] : '';
    }
    
    $res_dev = $conn->query("SELECT device_number FROM messages WHERE phone_number = '$active_phone' AND device_number IS NOT NULL ORDER BY created_at DESC LIMIT 1");
    if($res_dev->num_rows > 0) $active_device = $res_dev->fetch_assoc()['device_number'];
    
    $msg_query = $conn->query("SELECT * FROM messages WHERE phone_number = '$active_phone' ORDER BY created_at ASC");
    while($row = $msg_query->fetch_assoc()) $messages[] = $row;

    $history_query = $conn->query("SELECT DATE(created_at) as chat_date, COUNT(*) as total_msg FROM messages WHERE phone_number = '$active_phone' AND DATE(created_at) < CURDATE() GROUP BY DATE(created_at) ORDER BY chat_date DESC LIMIT 5");
    if($history_query) { while($h = $history_query->fetch_assoc()) { $chat_history_dates[] = $h; } }
}

function formatTanggalIndo($tanggal_db) {
    $waktu_asli = fixTime($tanggal_db); // Menerapkan offset otomatis
    $hari_ini = date('Y-m-d');
    $kemarin = date('Y-m-d', strtotime('-1 days'));
    $tanggal_pesan = date('Y-m-d', $waktu_asli);

    if ($tanggal_pesan == $hari_ini) {
        return "Hari Ini";
    } elseif ($tanggal_pesan == $kemarin) {
        return "Kemarin";
    } else {
        $bulanIndo = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
        $tanggal = date('j', $waktu_asli);
        $bulan = $bulanIndo[(int)date('m', $waktu_asli) - 1];
        $tahun = date('Y', $waktu_asli);
        return $tanggal . ' ' . $bulan . ' ' . $tahun;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>OmniDesk | A&S WebDeveloper</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --wa-bg-app: #d1d7db;
            --wa-bg-panel: #ffffff;
            --wa-bg-header: #f0f2f5;
            --wa-bg-chat: #efeae2;
            --wa-bg-search: #f0f2f5;
            --wa-border: #e9edef;
            --wa-text-main: #111b21;
            --wa-text-muted: #667781;
            --wa-teal: #00a884;
            --wa-teal-dark: #008069;
            --wa-bubble-in: #ffffff;
            --wa-bubble-out: #d9fdd3;
            --wa-hover: #f5f6f6;
            --wa-active: #f0f2f5;
            --wa-icon: #54656f;
            --btn-blue: #1e88e5;
        }
        body { background-color: var(--wa-bg-app); height: 100vh; margin: 0; font-family: 'Inter', sans-serif; display: flex; align-items: center; justify-content: center; color: var(--wa-text-main); }
        body::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 127px; background-color: var(--wa-teal-dark); z-index: -1; }
        .app-container { width: 100%; max-width: 1600px; height: 100vh; background: var(--wa-bg-panel); display: flex; }
        @media (min-width: 1440px) { .app-container { height: calc(100vh - 40px); box-shadow: 0 10px 30px rgba(11,20,26,.08); border-radius: 12px; overflow: hidden;} }
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-thumb { background: rgba(11,20,26,.2); border-radius: 10px; }
        ::-webkit-scrollbar-track { background: transparent; }
        
        .contact-panel { width: 30%; min-width: 340px; max-width: 420px; display: flex; flex-direction: column; background: var(--wa-bg-panel); border-right: 1px solid var(--wa-border); z-index: 10;}
        .panel-header { background: var(--wa-bg-header); height: 64px; padding: 10px 16px; display: flex; align-items: center; justify-content: space-between; }
        .header-icon-btn { background: transparent; border: none; color: var(--wa-icon); font-size: 1.2rem; padding: 8px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: background 0.2s; }
        .header-icon-btn:hover { background: rgba(11,20,26,.1); }
        
        .search-area { background: var(--wa-bg-panel); padding: 8px 12px; border-bottom: 1px solid var(--wa-border); display: flex; align-items: center; gap: 8px;}
        .search-box { background: var(--wa-bg-search); border-radius: 8px; display: flex; align-items: center; padding: 0 12px; height: 35px; flex-grow: 1;}
        .search-box input { background: transparent; border: none; font-size: 0.9rem; font-weight: 400; outline: none; width: 100%; color: var(--wa-text-main); margin-left: 10px;}
        
        .btn-new-chat { background: var(--wa-teal-dark); color: white; border: none; border-radius: 8px; height: 35px; width: 35px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: 0.2s; cursor: pointer; }
        .btn-new-chat:hover { background: #016e5a; }

        .tab-menu { display: flex; background: var(--wa-bg-panel); border-bottom: 1px solid var(--wa-border); }
        .tab-btn { flex: 1; text-align: center; padding: 12px 0; text-decoration: none; color: var(--wa-text-muted); font-size: 0.85rem; font-weight: 500; border-bottom: 3px solid transparent; transition: all 0.2s;}
        .tab-btn:hover { color: var(--wa-teal-dark); background: var(--wa-hover); }
        .tab-btn.active { color: var(--wa-teal-dark); border-bottom: 3px solid var(--wa-teal-dark); }
        
        .contact-list { flex-grow: 1; overflow-y: auto; background: var(--wa-bg-panel); }
        .contact-item { display: flex; align-items: center; padding: 0 12px 0 15px; height: 72px; text-decoration: none; color: var(--wa-text-main); cursor: pointer; transition: background 0.15s;}
        .contact-item:hover { background: var(--wa-hover); }
        .contact-item.active { background: var(--wa-active); }
        .avatar-circle { width: 49px; height: 49px; border-radius: 50%; background: #dfe5e7; color: white; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; font-weight: 500; margin-right: 15px; flex-shrink: 0; overflow: hidden; }
        .contact-details { flex-grow: 1; border-bottom: 1px solid var(--wa-border); height: 100%; display: flex; flex-direction: column; justify-content: center; padding-right: 5px; overflow: hidden;}
        .contact-item:last-child .contact-details { border-bottom: none; }
        .contact-name-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2px;}
        .contact-name { font-size: 1.05rem; font-weight: 500; color: var(--wa-text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .contact-time { font-size: 0.75rem; color: var(--wa-text-muted); font-weight: 400;}
        .contact-msg-row { display: flex; justify-content: space-between; align-items: center; }
        .contact-msg { font-size: 0.85rem; color: var(--wa-text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 400;}
        .unread-badge { background: #25d366; color: white; border-radius: 10px; min-width: 20px; height: 20px; padding: 0 6px; font-size: 0.75rem; display: flex; align-items: center; justify-content: center; font-weight: 600; }
        
        .user-footer { padding: 12px 16px; border-top: 1px solid var(--wa-border); background: var(--wa-bg-header); display: flex; justify-content: space-between; align-items: center;}
        
        .chat-panel { flex-grow: 1; display: flex; flex-direction: column; background: var(--wa-bg-chat); position: relative; min-width: 0; }
        .chat-header { background: var(--wa-bg-header); padding: 10px 16px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--wa-border); z-index: 10; height: 64px; gap: 8px;}
        .chat-history { flex-grow: 1; padding: 20px 8%; overflow-y: auto; background-color: var(--wa-bg-chat); background-image: url('https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png'); background-size: 400px; opacity: 0.9;}
        
        .message-row { display: flex; margin-bottom: 2px; width: 100%; position: relative; align-items: flex-start; padding: 4px 0; border-radius: 0; transition: background 0.2s ease;}
        .message-row.in { justify-content: flex-start; }
        .message-row.out { justify-content: flex-end; }
        .bubble { max-width: 65%; padding: 6px 7px 8px 9px; font-size: 0.9rem; box-shadow: 0 1px 0.5px rgba(11,20,26,.13); line-height: 19px; position: relative; color: var(--wa-text-main); border-radius: 7.5px;}
        .bubble.in { background: var(--wa-bubble-in); border-top-left-radius: 0; }
        .bubble.in::before { content: ""; position: absolute; top: 0; left: -8px; width: 0; height: 0; border: 8px solid transparent; border-top-color: var(--wa-bubble-in); border-left: 0; border-bottom: 0; }
        .bubble.out { background: var(--wa-bubble-out); border-top-right-radius: 0; }
        .bubble.out::after { content: ""; position: absolute; top: 0; right: -8px; width: 0; height: 0; border: 8px solid transparent; border-top-color: var(--wa-bubble-out); border-right: 0; border-bottom: 0; }
        .msg-time { font-size: 0.68rem; color: var(--wa-text-muted); display: inline-block; float: right; margin-left: 15px; margin-top: 4px; font-weight: 500;}
        
        .chat-input-area { background: var(--wa-bg-header); padding: 10px 16px; display: flex; flex-direction: column; gap: 8px; z-index: 10;}
        .input-bar { background: var(--wa-bg-panel); border-radius: 8px; flex-grow: 1; display: flex; align-items: flex-end; padding: 8px 12px; min-height: 44px;}
        .input-bar textarea { border: none; background: transparent; width: 100%; outline: none; font-size: 0.95rem; color: var(--wa-text-main); font-family: 'Inter', sans-serif; resize: none; overflow-y: auto; padding: 2px 0 0 0; min-height: 24px; max-height: 120px; line-height: 1.4;}
        .quick-replies-bar { display: flex; overflow-x: auto; gap: 8px; padding-bottom: 4px; scrollbar-width: none; }
        .qr-btn { background: var(--wa-bg-panel); border: 1px solid var(--wa-border); color: var(--wa-icon); font-size: 0.8rem; font-weight: 500; padding: 6px 14px; border-radius: 16px; cursor: pointer; white-space: nowrap; transition: background 0.2s;}
        .qr-btn:hover { background: var(--wa-hover); color: var(--wa-teal-dark);}
        .date-divider { display: flex; justify-content: center; margin: 12px 0; width: 100%; clear: both; }
        .date-divider span { background: #e1f3fb; color: #54656f; font-size: 0.75rem; font-weight: 500; padding: 5px 14px; border-radius: 8px; box-shadow: 0 1px 1px rgba(0,0,0,0.05); text-transform: uppercase; letter-spacing: 0.5px; }

        .message-row.selected-row, .contact-item.selected-contact { background: rgba(0, 168, 132, 0.1) !important; }

        .custom-cb { 
            width: 22px; height: 22px; border-radius: 50%; border: 2px solid var(--wa-icon); 
            display: flex; align-items: center; justify-content: center; transition: all 0.2s; flex-shrink: 0;
        }
        .selected-row .custom-cb, .selected-contact .custom-cb { background: var(--wa-teal-dark); border-color: var(--wa-teal-dark); }
        .selected-row .custom-cb::after, .selected-contact .custom-cb::after { content: '✓'; color: white; font-weight: bold; font-size: 14px; }

        .contextual-action-bar {
            display: none; position: absolute; top: 0; left: 0; width: 100%; height: 64px;
            background: var(--wa-bg-header); z-index: 1000; align-items: center; justify-content: space-between;
            padding: 0 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.08); animation: slideDown 0.2s ease-out;
        }
        @keyframes slideDown { from { transform: translateY(-10px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

        body.dark-mode { 
            --wa-bg-app: #0a1014; --wa-bg-panel: #111b21; --wa-bg-header: #202c33; 
            --wa-bg-chat: #0b141a; --wa-bg-search: #202c33; --wa-border: #222e35; 
            --wa-text-main: #e9edef; --wa-text-muted: #8696a0; --wa-teal: #00a884; --wa-teal-dark: #00a884;
            --wa-bubble-in: #202c33; --wa-bubble-out: #005c4b; --wa-hover: #202c33; 
            --wa-active: #2a3942; --wa-icon: #aebac1;
        }
        body.dark-mode::before { display: none; }
        body.dark-mode .app-container { box-shadow: none; border: 1px solid var(--wa-border);}
        body.dark-mode .contact-name, body.dark-mode .brand-title { color: #e9edef; }
        body.dark-mode .contact-msg, body.dark-mode .contact-time, body.dark-mode .msg-time { color: #8696a0; }
        body.dark-mode .bubble { color: #e9edef; }
        body.dark-mode .input-bar textarea { color: #e9edef; }
        body.dark-mode .search-box input { color: #e9edef; }
        body.dark-mode .header-icon-btn { color: #aebac1; }
        body.dark-mode .chat-history { 
            background-color: #0b141a; 
            background-image: linear-gradient(rgba(11, 20, 26, 0.95), rgba(11, 20, 26, 0.95)), url('https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png');
            opacity: 1 !important; 
        }
        body.dark-mode .qr-btn { background: #202c33; border-color: #2a3942; color: #aebac1; }
        body.dark-mode .date-divider span { background: #182229; color: #8696a0; }

        @media (max-width: 768px) { 
            .app-container { height: 100vh; width: 100%; max-width: 100%; border-radius:0; box-shadow:none; border: none;}
            .contact-panel { width: 100%; min-width: 100%; display: <?= $active_phone ? 'none' : 'flex' ?>; border-right: none;} 
            .chat-panel { width: 100%; display: <?= $active_phone ? 'flex' : 'none' ?>; } 
            body::before { display: none; }
            .chat-header { padding: 8px 12px; }
            .header-icon-btn { width: 34px; height: 34px; padding: 6px; }
        }
    </style>
</head>
<body onload="mintaIzinNotifikasi()">

<div class="app-container">
    
    <div class="contact-panel" style="position: relative;">
        <?php if($is_admin): ?>
        <div id="deleteContactActionBar" class="contextual-action-bar" style="z-index: 2000;">
            <div class="d-flex align-items-center">
                <button onclick="cancelContactSelection()" class="header-icon-btn me-4" style="color: var(--wa-text-main);">
                    <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"></path></svg>
                </button>
                <span id="deleteContactCount" style="font-weight:500; font-size:1.15rem; color: var(--wa-text-main);">1</span>
            </div>
            <button onclick="executeContactDelete()" class="header-icon-btn" title="Hapus Permanen" style="color: var(--wa-text-main);">
                <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"></path></svg>
            </button>
        </div>
        <?php endif; ?>

        <div class="panel-header">
            <div class="d-flex align-items-center cursor-pointer" onclick="window.location.href='admin_panel.php'" title="Pengaturan Admin">
                <div class="avatar-circle" style="width: 40px; height: 40px; background: #607d8b; color:white; border-radius: 50%; display:flex; align-items:center; justify-content:center; font-weight:bold; margin-right: 10px; cursor: pointer;">
                    <?= strtoupper(substr($_SESSION['name'],0,1)) ?>
                </div>
                <div style="line-height: 1.1;">
                    <div style="font-weight: 600; font-size: 1rem;" class="brand-title">OmniWA A&S</div>
                    <span style="font-size: 0.7rem; color: var(--wa-text-muted);"><?= strtoupper($_SESSION['role']) ?></span>
                </div>
            </div>
            <div class="d-flex gap-1">
                <button class="header-icon-btn" data-bs-toggle="modal" data-bs-target="#modalCekKoneksi" title="Monitor Jaringan">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>
                </button>
                <button class="header-icon-btn" data-bs-toggle="modal" data-bs-target="#modalGroup" title="Broadcast Grup">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14h-2v-2h2v2zm0-4h-2V7h2v5z"></path></svg>
                </button>
                <button class="header-icon-btn" id="darkModeBtn" onclick="toggleDarkMode()" title="Mode Gelap/Terang">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M12 3a9 9 0 1 0 9 9c0-.46-.04-.92-.1-1.36a5.389 5.389 0 0 1-4.4 2.26 5.403 5.403 0 0 1-3.14-9.8c-.44-.06-.9-.1-1.36-.1z"></path></svg>
                </button>
            </div>
        </div>
        
        <div class="search-area">
            <div class="search-box">
                <svg viewBox="0 0 24 24" width="18" height="18" fill="var(--wa-icon)"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 12.01 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 12.01 14 9.5 14z"></path></svg>
                <input type="text" id="searchContact" placeholder="Cari pelanggan...">
            </div>
            <button class="btn-new-chat" data-bs-toggle="modal" data-bs-target="#modalNewChat" title="Mulai Pesan Baru">
                <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"></path></svg>
            </button>
        </div>
        
        <div class="tab-menu">
            <a href="?tab=open" class="tab-btn <?= $tab == 'open' ? 'active' : '' ?>">Pesan Aktif</a>
            <a href="?tab=closed" class="tab-btn <?= $tab == 'closed' ? 'active' : '' ?>">Selesai</a>
        </div>
        
        <div class="contact-list" id="contactListArea">
            <?php while($row = $contacts->fetch_assoc()): ?>
                <?php 
                    $is_sla_breached = ($tab == 'open' && $row['last_msg_type'] == 'in' && $row['wait_time'] >= 10);
                    $press_contact_events = ($is_admin && $tab == 'closed') ? 'onmousedown="startContactPress(event, this, \''.$row['phone_number'].'\')" onmouseup="cancelContactPress()" onmouseleave="cancelContactPress()" ontouchstart="startContactPress(event, this, \''.$row['phone_number'].'\')" ontouchend="cancelContactPress()" onclick="contactClick(event, this, \''.$row['phone_number'].'\')"' : '';
                ?>
                <a href="?phone=<?= $row['phone_number'] ?>&tab=<?= $tab ?>" class="contact-item <?= ($active_phone == $row['phone_number']) ? 'active' : '' ?>" <?= $press_contact_events ?>>
                    <?php if($is_admin && $tab == 'closed'): ?>
                        <div class="contact-checkbox-wrapper" style="display:none; align-items:center; margin-right: 15px;">
                            <input type="checkbox" class="contact-checkbox d-none" value="<?= $row['phone_number'] ?>">
                            <div class="custom-cb"></div>
                        </div>
                    <?php endif; ?>
                    <div class="avatar-circle" style="background: <?= empty($row['assigned_to']) ? '#dfe5e7' : 'var(--wa-teal-dark)' ?>; color: <?= empty($row['assigned_to']) ? 'var(--wa-icon)' : 'white' ?>;">
                        <?= strtoupper(substr($row['name'],0,1)) ?>
                    </div>
                    <div class="contact-details">
                        <div class="contact-name-row">
                            <div class="contact-name"><?= htmlspecialchars($row['name']) ?></div>
                            <div class="contact-time" style="color: <?= $row['unread_count'] > 0 ? '#25d366' : 'var(--wa-text-muted)' ?>; font-weight: <?= $row['unread_count'] > 0 ? '600' : '400' ?>;">
                                <!-- MENGGUNAKAN FUNGSI FIX ZONA WAKTU -->
                                <?= empty($row['last_msg_time']) ? '' : date('H:i', fixTime($row['last_msg_time'])) ?>
                            </div>
                        </div>
                        <div class="contact-msg-row">
                            <div class="contact-msg">
                                <?php if($is_sla_breached): ?>
                                    <span style="color: #ea0038; font-weight: 500;">⚠️ Nunggu (<?= $row['wait_time'] ?>m)</span>
                                <?php elseif(!empty($row['assigned_to'])): ?>
                                    <span style="color: var(--wa-teal-dark);">PIC: <?= htmlspecialchars($row['assigned_to']) ?></span>
                                <?php else: ?>
                                    <?= $row['last_msg_type'] == 'out' ? '✓ ' : '' ?>+<?= $row['phone_number'] ?>
                                <?php endif; ?>
                            </div>
                            <?php if($row['unread_count'] > 0): ?>
                                <div class="unread-badge"><?= $row['unread_count'] ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </a>
            <?php endwhile; ?>
        </div>

        <div class="user-footer">
            <div class="d-flex align-items-center gap-2">
                <div style="line-height: 1.2;">
                    <div style="font-size: 0.85rem; font-weight: 600; color: var(--wa-text-main);"><?= htmlspecialchars($_SESSION['username']) ?></div>
                    <div style="font-size: 0.65rem; color: var(--wa-text-muted);">A&S WebDeveloper</div>
                </div>
            </div>
            <div class="d-flex gap-2">
                <?php if($_SESSION['role'] == 'admin'): ?>
                    <a href="admin_panel.php" class="btn btn-sm btn-light border text-dark" style="font-size: 0.7rem; font-weight: 600;">Admin</a>
                <?php endif; ?>
                <a href="logout.php" class="btn btn-sm btn-light border text-danger" style="font-size: 0.7rem; font-weight: 600;">Logout</a>
            </div>
        </div>
    </div>

    <div class="chat-panel">
        
        <div id="deleteActionBar" class="contextual-action-bar">
            <div class="d-flex align-items-center">
                <button onclick="cancelSelection()" class="header-icon-btn me-4" style="color: var(--wa-text-main);">
                    <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"></path></svg>
                </button>
                <span id="deleteCount" style="font-weight:500; font-size:1.15rem; color: var(--wa-text-main);">1</span>
            </div>
            
            <div class="d-flex align-items-center gap-2">
                <button onclick="executeMultiForward()" class="header-icon-btn" title="Teruskan Pesan" style="color: var(--wa-text-main);">
                    <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M10 9V5l7 7-7 7v-4.1c-5 0-8.5 1.6-11 5.1 1-5 4-10 11-10z"></path></svg>
                </button>
                
                <?php if ($is_admin): ?>
                    <button onclick="executeDelete()" class="header-icon-btn ms-2" title="Hapus Pesan" style="color: var(--wa-text-main);">
                        <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"></path></svg>
                    </button>
                <?php endif; ?>
            </div>
        </div>

        <?php if($active_phone): ?>
            
            <div class="chat-header">
                <div class="d-flex align-items-center" style="min-width: 0; flex: 1;">
                    <button class="header-icon-btn d-md-none me-1 flex-shrink-0" onclick="window.location.href='dashboard.php?tab=<?= $tab ?>'" style="margin-left:-8px;">
                        <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"></path></svg>
                    </button>
                    
                    <div class="avatar-circle me-2 flex-shrink-0" style="width: 40px; height: 40px; font-size: 1rem; cursor:pointer;" data-bs-toggle="offcanvas" data-bs-target="#infoPelanggan">
                        <?= strtoupper(substr($active_name,0,1)) ?>
                    </div>
                    
                    <div style="line-height: 1.2; cursor:pointer; overflow: hidden; padding-right: 10px;" data-bs-toggle="offcanvas" data-bs-target="#infoPelanggan">
                        <div style="font-weight: 500; font-size: 1rem; color: var(--wa-text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?= htmlspecialchars($active_name) ?></div>
                        
                        <div id="statusPelanggan" style="font-size: 0.75rem; color: var(--wa-text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: 0.2s;">
                            +<?= $active_phone ?>
                            <?php if(!empty($active_assigned_to)): ?>
                                • 👤 <?= htmlspecialchars($active_assigned_to) ?>
                            <?php endif; ?>
                        </div>

                        <div id="typingIndicator" class="d-none" style="font-size: 0.75rem; color: #25d366; font-weight: 600; font-style: italic;">
                            mengetik...
                        </div>
                    </div>
                </div>
                
                <div class="d-flex align-items-center gap-1 flex-shrink-0">
                    <?php if($active_status == 'open' && empty($active_assigned_to)): ?>
                        <button class="btn btn-sm text-white fw-bold px-2 py-1 me-1" onclick="ambilChat()" style="background: var(--wa-teal-dark); font-size:0.75rem; white-space: nowrap;">✋ Ambil</button>
                    <?php endif; ?>
                    
                    <button class="header-icon-btn" data-bs-toggle="modal" data-bs-target="#modalCekKoneksi" title="Cek Koneksi / Biling" style="color: var(--btn-blue);">
                        <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>
                    </button>

                    <button class="header-icon-btn" data-bs-toggle="offcanvas" data-bs-target="#infoPelanggan" title="Info Kontak">
                        <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M12 7a2 2 0 1 0-.001-4.001A2 2 0 0 0 12 7zm0 2C9.243 9 5 10.364 5 13v3h14v-3c0-2.636-4.243-4-7-4z"></path></svg>
                    </button>

                    <?php if($active_status == 'open' && ($active_assigned_to == $_SESSION['name'] || $_SESSION['role'] == 'admin')): ?>
                        <button class="header-icon-btn" onclick="event.stopPropagation(); window.location.href='close_chat.php?phone=<?= $active_phone ?>'" title="Tutup Sesi" style="color: #ea0038;">
                            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path></svg>
                        </button>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="chat-history" id="chatHistory">
                <div class="text-center mb-3"><span style="background: #ffeecd; color: #54656f; font-size: 0.75rem; padding: 5px 12px; border-radius: 8px; box-shadow: 0 1px 1px rgba(0,0,0,0.05); display: inline-block;">🔒 Pesan dienkripsi secara end-to-end.</span></div>

                <?php 
                $last_date = '';
                foreach($messages as $msg): 
                    // MENGGUNAKAN FUNGSI FIX ZONA WAKTU
                    $waktu_msg = fixTime($msg['created_at']);
                    $current_date = date('Y-m-d', $waktu_msg);
                    
                    if ($current_date !== $last_date) {
                        echo '<div class="date-divider"><span>' . formatTanggalIndo($msg['created_at']) . '</span></div>';
                        $last_date = $current_date; 
                    }

                    $media_html = '';
                    $file_ext = !empty($msg['file_url']) ? strtolower(pathinfo($msg['file_url'], PATHINFO_EXTENSION)) : '';

                    if (in_array($file_ext, ['ogg', 'mp3', 'webm', 'wav'])) {
                        $media_html = '<audio src="'.htmlspecialchars($msg['file_url']).'" controls controlsList="nodownload" style="max-width: 100%; margin-bottom: 5px; height: 40px; border-radius: 20px; outline: none;"></audio><br>';
                    } elseif ($msg['message_type'] == 'image' && !empty($msg['file_url'])) {
                        $media_html = '<img src="'.htmlspecialchars($msg['file_url']).'" style="max-width: 100%; max-height: 280px; border-radius: 6px; margin-bottom: 5px; cursor: pointer;" onclick="tampilkanLightbox(this.src)"><br>';
                    } elseif ($msg['message_type'] == 'video' && !empty($msg['file_url'])) {
                        $media_html = '<video src="'.htmlspecialchars($msg['file_url']).'" controls style="max-width: 100%; max-height: 280px; border-radius: 6px; margin-bottom: 5px;"></video><br>';
                    } elseif ($msg['message_type'] == 'document' && !empty($msg['file_url'])) {
                        $media_html = '<a href="'.htmlspecialchars($msg['file_url']).'" target="_blank" style="display:inline-flex; align-items:center; padding:10px 14px; background:rgba(0,0,0,0.05); border-radius:6px; color:inherit; text-decoration:none; margin-bottom:5px; font-weight:500; font-size:0.85rem;"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" class="me-2"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg> Dokumen</a><br>';
                    }
                    
                    $raw_text = !empty($msg['message_text']) ? trim($msg['message_text']) : '';
                    $raw_text = str_replace(array('\r\n', '\n', '\r'), "\n", $raw_text); 
                    $text_html = $raw_text !== '' ? '<span style="white-space: pre-wrap; word-break: break-word;">' . htmlspecialchars($raw_text) . '</span>' : '';
                    
                    $raw_text_for_fw = !empty($msg['message_text']) ? htmlspecialchars($msg['message_text']) : '';
                    
                    $press_events = 'onmousedown="startPress(event, this.parentElement)" onmouseup="cancelPress()" onmouseleave="cancelPress()" ontouchstart="startPress(event, this.parentElement)" ontouchend="cancelPress()" onclick="bubbleClick(this.parentElement)" style="cursor: pointer;"';
                ?>
                    
                    <div class="message-row <?= $msg['type'] ?>" data-date="<?= $current_date ?>" data-id="<?= $msg['id'] ?>">
                        <div class="msg-checkbox-wrapper" style="display:none; align-items:center; padding: 0 15px 0 10px;" onclick="bubbleClick(this.parentElement)">
                            <input type="checkbox" class="msg-checkbox d-none" value="<?= $msg['id'] ?>">
                            <input type="hidden" class="msg-raw-text" value="<?= $raw_text_for_fw ?>">
                            <input type="hidden" class="msg-raw-url" value="<?= htmlspecialchars($msg['file_url'] ?? '') ?>">
                            <div class="custom-cb"></div>
                        </div>

                        <?php if($msg['type'] == 'in'): ?>
                            <div class="bubble in" <?= $press_events ?>>
                                <?= $media_html . $text_html ?>
                                <span class="msg-time"><?= date('H:i', $waktu_msg) ?></span>
                            </div>
                        <?php else: ?>
                            <div class="bubble out" <?= $press_events ?>>
                                <?= $media_html . $text_html ?>
                                <span class="msg-time"><?= date('H:i', $waktu_msg) ?></span>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <div class="chat-input-area">
                <?php if($active_status == 'open'): ?>
                    <?php if(empty($active_assigned_to)): ?>
                        <div class="text-center py-2 text-muted" style="font-size: 0.9rem;">
                            Tiket ini belum diambil. Klik <b>Ambil Tiket</b> di atas untuk membalas.
                        </div>
                    <?php elseif($active_assigned_to != $_SESSION['name'] && $_SESSION['role'] != 'admin'): ?>
                        <div class="text-center py-2 text-danger" style="font-size: 0.9rem;">
                            Sesi dikunci karena sedang dilayani oleh <?= htmlspecialchars($active_assigned_to) ?>.
                        </div>
                    <?php else: ?>
                        
                        <div class="quick-replies-bar">
                            <?php if(!empty($quick_replies)): ?>
                                <?php foreach($quick_replies as $qr): ?>
                                    <button type="button" class="qr-btn" onclick="setQuickReply('<?= htmlspecialchars(addslashes($qr['content'])) ?>')"><?= htmlspecialchars($qr['title']) ?></button>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>

                        <div id="emojiPicker" class="d-none bg-white border shadow p-2" style="position: absolute; bottom: 70px; left: 16px; z-index: 1000; width: 300px; border-radius: 8px; display: flex; flex-wrap: wrap; gap: 4px;"></div>

                        <form action="send_message.php" method="POST" enctype="multipart/form-data" class="w-100 m-0" onsubmit="return sedangMengirim()">
                            <input type="hidden" name="phone_number" value="<?= htmlspecialchars($active_phone) ?>">
                            <input type="hidden" name="sender_device" value="<?= htmlspecialchars($active_device) ?>">
                            <input type="hidden" name="current_tab" value="<?= $tab ?>">
                            
                            <div id="filePreview" class="d-none mb-2 p-2 rounded bg-white border d-flex justify-content-between align-items-center shadow-sm mx-1">
                                <div class="d-flex align-items-center overflow-hidden">
                                    <img id="imgThumbnail" src="" class="d-none rounded me-2" style="width: 40px; height: 40px; object-fit: cover; border: 1px solid var(--wa-border);">
                                    <span class="me-2 fs-5" id="iconAttachment">📎</span> 
                                    <small id="fileName" class="text-truncate fw-bold text-success d-flex align-items-center"><span id="fNameText"></span></small>
                                </div>
                                <button type="button" class="btn-close flex-shrink-0 ms-2" style="font-size: 0.7rem;" onclick="batalFile()"></button>
                            </div>

                            <div class="input-bar">
                                <button type="button" class="header-icon-btn" id="btnEmoji" title="Emoji">
                                    <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M9.153 11.603c.795 0 1.439-.879 1.439-1.962s-.644-1.962-1.439-1.962-1.439.879-1.439 1.962.644 1.962 1.439 1.962zm-3.204 1.362c-.026-.307-.131 5.218 6.063 5.551 6.066-.25 6.066-5.551 6.066-5.551-6.078 1.416-12.129 0-12.129 0zm11.3631.13c-.08-.035-.164-.067-.251-.098-.034-.012-.069-.022-.104-.033-.081-.025-.165-.047-.253-.067-.031-.007-.063-.012-.095-.018-.088-.016-.179-.029-.275-.038-.025-.002-.051-.004-.076-.006-.097-.006-.2-.008-.309-.008-.109 0-.211.002-.308.008-.026.002-.052.004-.077.006-.095.009-.186.022-.274.038-.032.006-.063.011-.095.018-.087.02-.172.042-.253.067-.035.011-.069-.021-.104.033-.087-.031-.171-.063-.251.098-.024-.01-.049-.022-.073-.033-.217.102-.411.233-.585.394-.061.056-.118.117-.171.182-.016.02-.03.04-.045.061-.044.06-.081-.124-.112-.193-.01-.022-.019-.045-.027-.067-.024-.066-.041-.135.05-.207-.003-.023-.005-.046-.005-.068 0-.023.002-.046-.005-.068.01-.072-.027-.141-.05-.207-.009-.022-.018-.044-.027-.067-.031-.069-.068-.133-.112-.193-.014-.02-.029-.04-.044-.06-.054-.066-.111-.127-.172-.183-.174-.161-.368-.293-.585-.395-.024-.011-.048-.022-.073-.033.08.035.164.067.251.098.034.012.069.022.104.033.081.025.165.047.253.067.031.007.063.012.095.018.088.016.179.029.275.038.025.002.051.004.076.006.097.006.2.008.309.008s.211-.002.308-.008c.026-.002.052-.004.077-.006.095-.009.186-.022.274-.038.032-.006.063-.011.095-.018.087-.02.172-.042.253-.067.035-.011.069-.021.104-.033.087-.031.171-.063.251-.098.024-.01.049-.022.073-.033.217-.102.411-.233.585-.394.061-.056.118-.117.171-.182.016-.02.03-.04.045-.061.044-.06.081-.124.112-.193.01-.022.019-.045.027-.067.024-.066.041-.135.05-.207-.003-.023-.005-.046-.005-.068 0-.023.002-.046-.005-.068-.01-.072-.027-.141-.05-.207-.009-.022-.018-.044-.027-.067-.031-.069-.068-.133-.112-.193-.014-.02-.029-.04-.044-.06-.054-.066-.111-.127-.172-.183-.174-.161-.368-.293-.585-.395-.024-.011-.048-.022-.073-.033zm-3.328-3.054c.795 0 1.439-.879 1.439-1.962s-.644-1.962-1.439-1.962-1.439.879-1.439 1.962.644 1.962 1.439 1.962z"></path></svg>
                                </button>
                                <button type="button" class="header-icon-btn" onclick="pilihFile()" title="Lampiran">
                                    <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M1.816 15.556v.002c0 1.502.584 2.912 1.646 3.972s2.472 1.647 3.974 1.647a5.58 5.58 0 0 0 3.972-1.645l9.547-9.548c.769-.768 1.147-1.767 1.058-2.817-.079-.968-.548-1.927-1.319-2.698-1.594-1.592-4.068-1.711-5.517-.262l-7.916 7.915c-.881.881-.792 2.25.214 3.261.959.958 2.423 1.053 3.263.215l5.511-5.512c.28-.28.267-.722.053-.936l-.244-.244c-.191-.191-.567-.349-.957.04l-5.506 5.506c-.18.18-.635.127-.976-.214-.098-.097-.576-.613-.213-.973l7.915-7.917c.818-.817 2.267-.699 3.23.262.5.501.802 1.1.849 1.685.051.573-.156 1.111-.589 1.543l-9.547 9.549a3.97 3.97 0 0 1-2.829 1.171 3.975 3.975 0 0 1-2.83-1.173 3.973 3.973 0 0 1-1.172-2.828c0-1.071.415-2.076 1.172-2.83l7.209-7.211c.157-.157.264-.579.028-.814L11.5 4.36a.57.57 0 0 0-.834.018l-7.205 7.207a5.577 5.577 0 0 0-1.645 3.971z"></path></svg>
                                </button>
                                <input type="file" id="fileAttachment" name="media_file" class="d-none" accept="image/*,video/*,audio/*,.pdf,.doc,.docx" onchange="previewFile()">
                                
                                <textarea name="message" id="inputPesan" placeholder="Ketik pesan..." required style="width: 100%; border: none; background: transparent; outline: none; resize: none; min-height: 24px; max-height: 120px; padding-top: 2px; line-height: 1.4; overflow-y: auto; font-family: 'Inter', sans-serif; color: var(--wa-text-main);" rows="1"><?= htmlspecialchars($pesan_teks) ?></textarea>
                                
                                <button type="submit" id="btnKirimAsli" class="d-none"></button>
                                
                                <button type="button" class="header-icon-btn ms-2 mb-1 align-self-end" id="btnKirimFake" onclick="document.getElementById('btnKirimAsli').click();">
                                    <svg id="iconSend" viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M1.101 21.757 23.8 12.028 1.101 2.3l.011 7.912 13.623 1.816-13.623 1.817-.011 7.912z"></path></svg>
                                    <div id="iconLoading" class="spinner-border spinner-border-sm text-secondary d-none"></div>
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="text-center py-2 text-muted" style="font-size: 0.9rem;">
                        Percakapan ini telah diselesaikan.
                    </div>
                <?php endif; ?>
            </div>

        <?php else: ?>
            <div class="d-flex align-items-center justify-content-center h-100 flex-column text-center p-4">
                <div style="margin-bottom: 30px;">
                    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/WhatsApp.svg/512px-WhatsApp.svg.png" width="90" style="opacity: 0.1; filter: grayscale(1);">
                </div>
                <h2 style="color: var(--wa-text-main); font-weight: 300; margin-bottom: 20px;">OmniDesk Web</h2>
                <p style="color: var(--wa-text-muted); font-size: 0.95rem; max-width: 450px; line-height: 1.5;">Kirim dan terima pesan tanpa perlu menghubungkan telepon Anda ke internet.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- ============================================================== -->
<!-- MODAL: NEW CHAT (KIRIM PESAN BARU)                             -->
<!-- ============================================================== -->
<div class="modal fade" id="modalNewChat" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px; background: var(--wa-bg-panel); color: var(--wa-text-main); font-family: 'Inter', sans-serif;">
            <form action="send_message.php" method="POST" enctype="multipart/form-data">
                <div class="modal-header p-4 border-bottom">
                    <h5 class="modal-title fw-bold" style="font-size: 1.15rem; color: var(--wa-text-main);">Mulai Percakapan Baru</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    
                    <div class="mb-3">
                        <label style="font-size: 0.85rem; color: var(--wa-teal-dark); margin-bottom: 8px; display: block; font-weight: 600;">Pilih Nomor Bot Pengirim</label>
                        <select name="sender_device" class="form-select bg-light border-0 shadow-none p-3 fw-medium" required style="border-radius: 8px;">
                            <?php if(!empty($available_devices)): ?>
                                <?php foreach($available_devices as $dev): ?>
                                    <option value="<?= htmlspecialchars($dev) ?>"><?= htmlspecialchars($dev) ?></option>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <option value="">(Database Bot Kosong - Gunakan Nomor Admin)</option>
                            <?php endif; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label style="font-size: 0.85rem; color: var(--wa-teal-dark); margin-bottom: 8px; display: block; font-weight: 600;">Nomor Pelanggan Tujuan</label>
                        <div class="input-group bg-light" style="border-radius: 8px; overflow: hidden; border: none;">
                            <span class="input-group-text border-0 bg-transparent text-muted fw-bold ps-3 pe-1">+62</span>
                            <input type="text" name="phone_number" class="form-control bg-transparent border-0 shadow-none py-3 px-2" placeholder="81234567890" required style="font-size: 1rem;">
                        </div>
                        <small style="color: var(--wa-text-muted); font-size: 0.75rem; margin-top: 6px; display: block;">Masukkan nomor tujuan tanpa awalan 0 atau +62.</small>
                    </div>

                    <div class="mb-3">
                        <label style="font-size: 0.85rem; color: var(--wa-teal-dark); margin-bottom: 8px; display: block; font-weight: 600;">Pesan Pertama</label>
                        <textarea name="message" class="form-control bg-light border-0 shadow-none p-3 fw-medium" rows="4" placeholder="Ketik pesan sapaan Anda di sini..." required style="border-radius: 12px; resize: none;"></textarea>
                    </div>

                    <div class="mb-2">
                        <label style="font-size: 0.85rem; color: var(--wa-text-main); margin-bottom: 8px; display: block; font-weight: 600;">Sertakan Lampiran File (Opsional)</label>
                        <input type="file" name="media_file" class="form-control bg-light border-0 shadow-none p-2 fw-medium" accept="image/*,video/*,.pdf,.doc,.docx" style="border-radius: 8px;">
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <input type="hidden" name="current_tab" value="open">
                    <button type="submit" class="btn w-100 text-white fw-bold py-3" style="background: var(--wa-teal-dark); border-radius: 12px; font-size: 1rem;" onclick="this.innerHTML='Mengirim...';">KIRIM PESAN SEKARANG</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if($active_phone): ?>
<div class="offcanvas offcanvas-end border-start-0" tabindex="-1" id="infoPelanggan" style="width: 360px; background: var(--wa-bg-app);">
    <div class="panel-header">
        <div class="d-flex align-items-center">
            <button type="button" class="header-icon-btn me-3" data-bs-dismiss="offcanvas">
                <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"></path></svg>
            </button>
            <span style="font-weight: 500; font-size: 1.1rem; color: var(--wa-text-main);">Info kontak</span>
        </div>
    </div>
    
    <div class="offcanvas-body p-0" style="overflow-y: auto;">
        
        <div style="background: var(--wa-bg-panel); padding: 30px 20px; text-align: center; margin-bottom: 10px; box-shadow: 0 1px 3px rgba(11,20,26,.05);">
            <div style="width: 200px; height: 200px; border-radius: 50%; background: #dfe5e7; color: white; display: flex; align-items: center; justify-content: center; font-size: 5rem; font-weight: 400; margin: 0 auto 20px auto; overflow: hidden;">
                <?= strtoupper(substr($active_name,0,1)) ?>
            </div>
            <div class="d-flex justify-content-center align-items-center mb-1">
                <input type="text" id="editNamaInput" value="<?= htmlspecialchars($active_name) ?>" style="font-size: 1.4rem; color: var(--wa-text-main); font-weight: 400; border: none; background: transparent; text-align: center; width: auto; max-width: 200px; outline: none; border-bottom: 1px dashed var(--wa-border); font-family: 'Inter', sans-serif;">
                <button class="header-icon-btn ms-2" onclick="simpanNama()" title="Simpan Nama" style="padding: 5px;">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="var(--wa-teal-dark)"><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"></path></svg>
                </button>
            </div>
            <div style="font-size: 1.05rem; color: var(--wa-text-muted);">+<?= htmlspecialchars($active_phone) ?></div>
            
            <div style="margin-top: 15px;">
                <span style="font-size: 0.8rem; background: var(--wa-bg-app); color: var(--wa-text-muted); padding: 6px 14px; border-radius: 16px; font-weight: 600; border: 1px solid var(--wa-border);">
                    🤖 Masuk via Bot: <?= !empty($active_device) ? htmlspecialchars($active_device) : 'Sistem Utama' ?>
                </span>
            </div>
        </div>
        
        <div style="background: var(--wa-bg-panel); padding: 20px; margin-bottom: 10px; box-shadow: 0 1px 3px rgba(11,20,26,.05);">
            <div style="font-size: 0.9rem; color: var(--wa-teal-dark); margin-bottom: 15px; font-weight: 500;">Kategori & Status Tiket</div>
            <div class="mb-3">
                <select class="form-select bg-light border-0 shadow-none fw-medium" id="labelSelect" onchange="simpanLabel()" style="border-radius: 8px; font-size: 0.95rem; color: var(--wa-text-main); padding: 10px 15px; font-family: 'Inter', sans-serif;">
                    <option value="" <?= empty($active_label) ? 'selected' : '' ?>>-- Tambahkan Label --</option>
                    <option value="Tanya Layanan" <?= $active_label == 'Tanya Layanan' ? 'selected' : '' ?>>🔵 Tanya Layanan</option>
                    <option value="Pasang Baru" <?= $active_label == 'Pasang Baru' ? 'selected' : '' ?>>🟢 Pasang Baru</option>
                    <option value="Gangguan" <?= $active_label == 'Gangguan' ? 'selected' : '' ?>>🔴 Gangguan</option>
                    <option value="Tagihan" <?= $active_label == 'Tagihan' ? 'selected' : '' ?>>🟡 Tagihan</option>
                    <option value="Selesai/Closing" <?= $active_label == 'Selesai/Closing' ? 'selected' : '' ?>>⚫ Selesai</option>
                </select>
            </div>
            <div class="d-flex justify-content-between align-items-center bg-light p-3 rounded-3 mt-3">
                <span style="color: var(--wa-text-main); font-size: 0.95rem;">Status Sesi Aktif</span>
                <span class="badge" style="background: <?= $active_status == 'open' ? '#25d366' : '#8696a0' ?>; font-weight: normal; padding: 6px 12px; font-size: 0.8rem; border-radius: 12px;">
                    <?= $active_status == 'open' ? 'TERBUKA' : 'SELESAI' ?>
                </span>
            </div>
        </div>

        <div style="background: var(--wa-bg-panel); padding: 20px; margin-bottom: 10px; box-shadow: 0 1px 3px rgba(11,20,26,.05);">
            <div style="font-size: 0.9rem; color: var(--wa-teal-dark); margin-bottom: 15px; font-weight: 500;">Catatan Pribadi (Admin/CS)</div>
            <textarea id="inputNotes" class="form-control bg-light border-0 shadow-none mb-3" rows="4" placeholder="Tambahkan deskripsi atau memo tentang pelanggan ini..." style="font-size: 0.95rem; border-radius: 8px; resize: none; color: var(--wa-text-main); padding: 10px 15px; font-family: 'Inter', sans-serif;"><?= htmlspecialchars($active_notes) ?></textarea>
            <button class="btn w-100" style="background: #f0f2f5; color: var(--wa-text-main); font-weight: 600; border-radius: 20px; font-family: 'Inter', sans-serif;" onclick="simpanCatatan()">Simpan Catatan</button>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="modal fade" id="modalGroup" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px; background: var(--wa-bg-panel); color: var(--wa-text-main); font-family: 'Inter', sans-serif;">
            <form action="send_group.php" method="POST" enctype="multipart/form-data">
                <div class="modal-header p-4 border-0">
                    <div class="avatar-circle me-3" style="background: var(--wa-teal-dark); width: 40px; height: 40px; font-size: 1.2rem;">📢</div>
                    <h5 class="modal-title fw-bold" style="color: var(--wa-text-main);">Broadcast Ekstra</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4 pt-0">
                    <div style="background: #fff3cd; color: #856404; padding: 10px 15px; border-radius: 8px; font-size: 0.85rem; margin-bottom: 20px;">
                        ⚠️ Pesan ini akan dikirim secara satu-arah menggunakan nomor Bot yang disetting di Admin Panel.
                    </div>
                    
                    <div class="mb-4 bg-light p-3 border" style="border-radius: 12px;">
                        <label style="font-size: 0.8rem; color: var(--wa-text-muted); margin-bottom: 5px; display: block; font-weight: 600;">ID GRUP TUJUAN</label>
                        <input type="text" name="group_id" class="form-control bg-transparent fw-bold border-0 shadow-none p-0" value="120363131874161004@g.us" readonly style="color: var(--wa-text-main); font-size: 1rem;">
                    </div>

                    <div class="mb-4">
                        <label style="font-size: 0.85rem; color: var(--wa-text-main); margin-bottom: 8px; display: block; font-weight: 600;">Teks Pengumuman</label>
                        <textarea name="message" class="form-control bg-light border-0 shadow-none p-3 fw-medium" rows="5" placeholder="Ketik pengumuman..." required style="border-radius: 12px; resize: none;"></textarea>
                    </div>
                    <div class="mb-2">
                        <label style="font-size: 0.85rem; color: var(--wa-text-main); margin-bottom: 8px; display: block; font-weight: 600;">Sertakan Lampiran File</label>
                        <input type="file" name="media_file" class="form-control bg-light border-0 shadow-none p-2 fw-medium" accept="image/*,video/*,.pdf,.doc,.docx" style="border-radius: 8px;">
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" class="btn w-100 text-white" style="background: var(--wa-teal-dark); border-radius: 12px; font-weight: 600; padding: 12px;" onclick="this.innerHTML='Mengirim...';">KIRIM BROADCAST</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalForward" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px; background: var(--wa-bg-panel); color: var(--wa-text-main); font-family: 'Inter', sans-serif;">
            <form action="forward_message.php" method="POST" onsubmit="document.getElementById('btnForwardSubmit').innerHTML='Meneruskan...'; document.getElementById('btnForwardSubmit').disabled=true;">
                <div class="modal-header p-4 border-bottom">
                    <h5 class="modal-title fw-bold" style="font-size: 1.15rem; color: var(--wa-text-main);">Teruskan pesan ke...</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    
                    <input type="hidden" name="fwd_text" id="fwd_text">
                    <input type="hidden" name="fwd_file" id="fwd_file">
                    <input type="hidden" name="fwd_type" id="fwd_type">
                    <input type="hidden" name="active_phone" value="<?= htmlspecialchars($active_phone) ?>">
                    
                    <div class="bg-light p-3 mb-3" style="border-radius: 12px; max-height: 150px; overflow-y: auto; border: 1px solid var(--wa-border);">
                        <span style="font-size: 0.75rem; color: var(--wa-text-muted); display: block; margin-bottom: 5px; font-weight: 600;">PESAN YANG DITERUSKAN:</span>
                        <div id="fwd_preview" class="fw-medium text-dark" style="font-size: 0.9rem; word-break: break-word;"></div>
                    </div>

                    <div class="mb-4">
                        <label style="font-size: 0.85rem; color: var(--wa-teal-dark); margin-bottom: 8px; display: block; font-weight: 600;">Tambahkan Catatan (Opsional)</label>
                        <textarea name="additional_msg" class="form-control bg-light border-0 shadow-none p-3 fw-medium" rows="2" placeholder="Cth: Tolong cek bukti TF dari klien <?= htmlspecialchars($active_name) ?>" style="border-radius: 8px; resize: none; font-size: 0.95rem;"></textarea>
                    </div>

                    <div class="mb-4">
                        <label style="font-size: 0.85rem; color: var(--wa-teal-dark); margin-bottom: 10px; display: block; font-weight: 600;">Kirim Cepat Ke Divisi Internal:</label>
                        <div class="d-flex flex-wrap gap-2 mb-3">
                            <?php if(!empty($fwd_contacts)): ?>
                                <?php foreach($fwd_contacts as $fc): ?>
                                    <button type="button" class="btn btn-sm px-3 py-2" style="background: #e0f2fe; color: #0284c7; border-radius: 8px; border: none; font-weight: 500;" onclick="document.getElementById('target_number').value='<?= htmlspecialchars($fc['phone_number']) ?>'"><?= htmlspecialchars($fc['name']) ?></button>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <span class="badge bg-light text-muted border p-2 fw-normal">Belum ada kontak internal di Admin Panel</span>
                            <?php endif; ?>
                        </div>

                        <label style="font-size: 0.85rem; color: var(--wa-teal-dark); margin-bottom: 8px; display: block; font-weight: 600;">Atau Ketik Nomor Tujuan Custom / ID Grup</label>
                        <input type="text" name="target_number" id="target_number" class="form-control bg-light border-0 shadow-none px-3 py-3" placeholder="62812xxx atau ID Grup" required style="border-radius: 8px; font-size: 1rem;">
                        <small style="color: var(--wa-text-muted); font-size: 0.75rem; margin-top: 6px; display: block;">Gunakan format awalan 62 untuk nomor pribadi.</small>
                    </div>

                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" id="btnForwardSubmit" class="btn w-100 text-white fw-bold py-3" style="background: var(--wa-teal-dark); border-radius: 12px; font-size: 1rem;">TERUSKAN SEKARANG</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCekKoneksi" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-xl modal-dialog-centered" style="max-width: 95%;">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px; background: var(--wa-bg-panel); height: 90vh; overflow: hidden;">
            <div class="modal-header px-4 py-3" style="background: var(--wa-bg-header); border-bottom: 1px solid var(--wa-border);">
                <div class="d-flex align-items-center gap-2">
                    <div style="width: 32px; height: 32px; background: var(--btn-blue); color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center;">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>
                    </div>
                    <div>
                        <h6 class="modal-title fw-bold" style="color: var(--wa-text-main); font-size: 1rem; margin:0;">Sistem Cek Jaringan / Biling</h6>
                        <div style="font-size: 0.75rem; color: var(--wa-text-muted);">
                            <?= $active_phone ? 'Mengecek data untuk: +' . htmlspecialchars($active_phone) : 'Akses Sistem Global' ?>
                        </div>
                    </div>
                </div>
                <button type="button" class="btn fw-bold d-flex align-items-center gap-2" data-bs-dismiss="modal" style="background: #fee2e2; color: #ef4444; border-radius: 8px; font-size: 0.85rem; padding: 8px 16px;">
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
                    Kembali
                </button>
            </div>
            <div class="modal-body p-0" style="background: #f3f4f6;">
                <iframe src="https://servmon.majapahitnet.id/index_cs.php" style="width: 100%; height: 100%; border: none;" title="Sistem Jaringan"></iframe>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="imageLightbox" tabindex="-1" style="background-color: rgba(17,24,39,0.95);">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content bg-transparent border-0 text-end">
            <button type="button" class="btn-close btn-close-white mb-3" data-bs-dismiss="modal"></button>
            <img id="lightboxImage" src="" class="img-fluid mx-auto" style="max-height: 85vh; object-fit: contain; border-radius: 8px; box-shadow: 0 20px 50px rgba(0,0,0,0.5);">
        </div>
    </div>
</div>

<audio id="notifSound" src="https://assets.mixkit.co/active_storage/sfx/2354/2354-preview.mp3" preload="auto"></audio>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
    var chatBox = document.getElementById("chatHistory");
    var notifSound = document.getElementById("notifSound");
    if(chatBox) chatBox.scrollTop = chatBox.scrollHeight;

    // ==============================================================
    // VARIABEL GLOBAL UNTUK SISTEM LONG PRESS MENGHAPUS MASSAL
    // ==============================================================
    window.isSelectingMode = false;
    window.selectedMsgIds = new Set();
    window.pressTimer = null;
    
    window.isContactSelectingMode = false;
    window.selectedContacts = new Set();
    window.contactPressTimer = null;

    // ==============================================================
    // 1. LOGIKA LONG PRESS DALAM CHAT (UNTUK FORWARD/HAPUS)
    // ==============================================================
    function startPress(e, rowElement) {
        if (window.isSelectingMode) return; 
        window.pressTimer = setTimeout(() => {
            enableSelectionMode(rowElement);
            if(navigator.vibrate) navigator.vibrate(50); // Getar di HP
        }, 500); 
    }
    
    function cancelPress() { clearTimeout(window.pressTimer); }

    function bubbleClick(rowElement) {
        if (window.isSelectingMode) {
            let cb = rowElement.querySelector('.msg-checkbox');
            let id = cb.value;
            
            if (window.selectedMsgIds.has(id)) {
                window.selectedMsgIds.delete(id);
                cb.checked = false;
                rowElement.classList.remove('selected-row');
            } else {
                window.selectedMsgIds.add(id);
                cb.checked = true;
                rowElement.classList.add('selected-row');
            }
            updateActionBar();
        }
    }

    function enableSelectionMode(rowElement) {
        window.isSelectingMode = true;
        document.querySelectorAll('.msg-checkbox-wrapper').forEach(w => w.style.display = 'flex');
        bubbleClick(rowElement);
    }

    function updateActionBar() {
        let bar = document.getElementById('deleteActionBar');
        if (window.selectedMsgIds.size > 0) {
            bar.style.display = 'flex';
            document.getElementById('deleteCount').innerText = window.selectedMsgIds.size;
        } else {
            cancelSelection();
        }
    }

    function cancelSelection() {
        window.isSelectingMode = false;
        window.selectedMsgIds.clear();
        document.querySelectorAll('.msg-checkbox-wrapper').forEach(w => w.style.display = 'none');
        document.querySelectorAll('.message-row').forEach(row => {
            row.classList.remove('selected-row');
            let cb = row.querySelector('.msg-checkbox');
            if(cb) cb.checked = false;
        });
        document.getElementById('deleteActionBar').style.display = 'none';
    }

    function executeMultiForward() {
        if (window.selectedMsgIds.size === 0) return;
        
        let combinedText = [];
        let fileUrl = ''; 
        
        // Looping pesan yang dipilih
        document.querySelectorAll('.message-row.selected-row').forEach(row => {
            let textVal = row.querySelector('.msg-raw-text').value;
            let urlVal = row.querySelector('.msg-raw-url').value;
            
            if (textVal.trim() !== '') { combinedText.push(textVal); }
            if (urlVal.trim() !== '' && fileUrl === '') { fileUrl = urlVal; }
        });

        let finalMergedText = combinedText.join('\n\n---\n\n'); 
        
        let fwDataArray = {
            text: finalMergedText,
            file_url: fileUrl,
            type: fileUrl !== '' ? 'document' : 'text' 
        };
        
        let fakeBtn = document.createElement('button');
        fakeBtn.setAttribute('data-fw-text', btoa(unescape(encodeURIComponent(JSON.stringify(fwDataArray)))));
        
        cancelSelection(); 
        openForwardModal(fakeBtn); 
    }

    function executeDelete() {
        if (window.selectedMsgIds.size === 0) return;
        if (!confirm('Hapus ' + window.selectedMsgIds.size + ' pesan ini bagi saya?')) return;
        
        let formData = new URLSearchParams();
        formData.append('action', 'delete_messages');
        formData.append('msg_ids', JSON.stringify(Array.from(window.selectedMsgIds)));
        
        fetch('delete_bulk.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: formData.toString()
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                cancelSelection();
                location.reload(); 
            } else { alert(data.message); }
        }).catch(err => alert('Error koneksi.'));
    }

    // ==============================================================
    // 2. LOGIKA MENGHAPUS KONTAK/PERCAKAPAN DARI TAB SELESAI
    // ==============================================================
    function startContactPress(e, contactElement, phone) {
        if (window.isContactSelectingMode) return; 
        window.contactPressTimer = setTimeout(() => {
            enableContactSelectionMode(contactElement, phone);
            if(navigator.vibrate) navigator.vibrate(50); 
        }, 600); 
    }

    function cancelContactPress() { clearTimeout(window.contactPressTimer); }

    function contactClick(e, contactElement, phone) {
        if (window.isContactSelectingMode) {
            e.preventDefault(); 
            let cb = contactElement.querySelector('.contact-checkbox');
            
            if (window.selectedContacts.has(phone)) {
                window.selectedContacts.delete(phone);
                cb.checked = false;
                contactElement.classList.remove('selected-contact');
            } else {
                window.selectedContacts.add(phone);
                cb.checked = true;
                contactElement.classList.add('selected-contact');
            }
            updateContactActionBar();
        }
    }

    function enableContactSelectionMode(contactElement, phone) {
        window.isContactSelectingMode = true;
        document.querySelectorAll('.contact-checkbox-wrapper').forEach(w => w.style.display = 'flex');
        contactElement.classList.add('selected-contact');
        window.selectedContacts.add(phone);
        let cb = contactElement.querySelector('.contact-checkbox');
        if(cb) cb.checked = true;
        updateContactActionBar();
    }

    function updateContactActionBar() {
        let bar = document.getElementById('deleteContactActionBar');
        if (window.selectedContacts.size > 0) {
            bar.style.display = 'flex';
            document.getElementById('deleteContactCount').innerText = window.selectedContacts.size + ' riwayat dipilih';
        } else {
            cancelContactSelection();
        }
    }

    function cancelContactSelection() {
        window.isContactSelectingMode = false;
        window.selectedContacts.clear();
        document.querySelectorAll('.contact-checkbox-wrapper').forEach(w => w.style.display = 'none');
        document.querySelectorAll('.contact-item').forEach(row => {
            row.classList.remove('selected-contact');
            let cb = row.querySelector('.contact-checkbox');
            if(cb) cb.checked = false;
        });
        document.getElementById('deleteContactActionBar').style.display = 'none';
    }

    function executeContactDelete() {
        if (window.selectedContacts.size === 0) return;
        if (!confirm('HAPUS PERMANEN seluruh riwayat chat untuk ' + window.selectedContacts.size + ' kontak terpilih? Aksi ini tidak dapat dikembalikan!')) return;
        
        let formData = new URLSearchParams();
        formData.append('action', 'delete_conversations');
        formData.append('phone_numbers', JSON.stringify(Array.from(window.selectedContacts)));
        
        fetch('delete_bulk.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: formData.toString()
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                cancelContactSelection();
                location.reload(); 
            } else { alert(data.message); }
        }).catch(err => alert('Error koneksi.'));
    }

    // ==============================================================
    // FUNGSI UMUM LAINNYA
    // ==============================================================
    function mintaIzinNotifikasi() {
        if (!("Notification" in window)) { console.log("Browser tidak mendukung notifikasi"); } 
        else if (Notification.permission !== "granted") { Notification.requestPermission(); }
    }

    function tampilkanNotifikasiDesktop(nama, pesan) {
        if (Notification.permission === "granted") {
            var options = { body: pesan, icon: 'https://cdn-icons-png.flaticon.com/512/124/124034.png' };
            var notification = new Notification("Pesan Baru: " + nama, options);
            notification.onclick = function() { window.focus(); this.close(); };
        }
    }

    function toggleQRPresence() {
        var input = document.getElementById('inputPesan').value;
        var qrRow = document.getElementById('qrRow');
        if(qrRow) {
            if(input.length > 0) { qrRow.style.display = 'none'; } 
            else { qrRow.style.display = 'flex'; }
        }
    }

    function openForwardModal(btn) {
        let base64Data = btn.getAttribute('data-fw-text');
        let dataStr = atob(base64Data);
        let data = JSON.parse(dataStr);

        document.getElementById('fwd_text').value = data.text || '';
        document.getElementById('fwd_file').value = data.file_url || '';
        document.getElementById('fwd_type').value = data.type || 'text';
        
        let previewHtml = '';
        if (data.file_url) { previewHtml += '<span class="badge bg-success mb-2">['+data.type.toUpperCase()+'] TERLAMPIR</span><br>'; }
        if (data.text) { previewHtml += data.text; }
        if (!data.text && !data.file_url) { previewHtml = '<i class="text-muted">Pesan kosong / Tidak didukung</i>'; }
        
        document.getElementById('fwd_preview').innerHTML = previewHtml;
        var fwModal = new bootstrap.Modal(document.getElementById('modalForward'));
        fwModal.show();
    }

    const emojis = ['😀','😂','🤣','😍','🥰','😘','😊','😎','😢','😭','😡','😠','🙏','👍','👎','👏','🤝','🔥','❤️','💔','💯','✨','🎉','✅','❌','🛑','🟢','🟡','🔴','🔵','📦','💻','📡','🔌','🔧'];
    const emojiPicker = document.getElementById('emojiPicker');
    const inputPesan = document.getElementById('inputPesan');
    const btnEmoji = document.getElementById('btnEmoji');

    if(emojiPicker && inputPesan && btnEmoji) {
        emojis.forEach(emp => {
            let span = document.createElement('span');
            span.innerText = emp;
            span.style.cursor = 'pointer'; span.style.fontSize = '1.4rem'; span.style.padding = '6px';
            span.className = 'emoji-item';
            span.onclick = function() { 
                inputPesan.value += emp; 
                inputPesan.focus(); 
                toggleQRPresence(); 
                inputPesan.style.height = '24px';
                inputPesan.style.height = (inputPesan.scrollHeight) + 'px';
            };
            emojiPicker.appendChild(span);
        });

        let style = document.createElement('style');
        style.innerHTML = '.emoji-item:hover { background: #f3f4f6; border-radius: 8px; } body.dark-mode .emoji-item:hover { background: #2a3942; }';
        document.head.appendChild(style);

        btnEmoji.onclick = function(e) { e.stopPropagation(); emojiPicker.classList.toggle('d-none'); };
        document.addEventListener('click', function(e) { if (!emojiPicker.contains(e.target) && e.target.id !== 'btnEmoji') { emojiPicker.classList.add('d-none'); } });
    }

    function pilihFile() { document.getElementById('fileAttachment').click(); }
    function previewFile() {
        var file = document.getElementById('fileAttachment').files[0];
        if(file) {
            document.getElementById('fNameText').innerText = file.name;
            document.getElementById('filePreview').classList.remove('d-none');
            document.getElementById('inputPesan').removeAttribute('required'); 
            if(document.getElementById('qrRow')) document.getElementById('qrRow').style.display = 'none'; 
            
            var imgThumb = document.getElementById('imgThumbnail');
            var iconAttach = document.getElementById('iconAttachment');
            
            if (file.type.startsWith('image/')) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    imgThumb.src = e.target.result;
                    imgThumb.classList.remove('d-none');
                    iconAttach.classList.add('d-none');
                }
                reader.readAsDataURL(file);
            } else {
                imgThumb.classList.add('d-none');
                iconAttach.classList.remove('d-none');
            }
        }
    }
    
    function batalFile() {
        document.getElementById('fileAttachment').value = '';
        document.getElementById('filePreview').classList.add('d-none');
        document.getElementById('inputPesan').setAttribute('required', 'required');
        
        document.getElementById('imgThumbnail').src = '';
        document.getElementById('imgThumbnail').classList.add('d-none');
        document.getElementById('iconAttachment').classList.remove('d-none');
        
        toggleQRPresence();
    }

    function sedangMengirim() {
        document.getElementById('iconSend').classList.add('d-none');
        document.getElementById('iconLoading').classList.remove('d-none');
        document.getElementById('btnKirimAsli').disabled = true;
        document.getElementById('btnKirimFake').disabled = true;
        return true;
    }

    function setQuickReply(text) {
        var input = document.getElementById('inputPesan');
        var namaPelanggan = "<?= addslashes(htmlspecialchars($active_name)) ?>";
        if (namaPelanggan === "Pelanggan" || namaPelanggan.trim() === "") { namaPelanggan = "Kak/Bapak/Ibu"; }
        var namaCS = "<?= addslashes(htmlspecialchars($_SESSION['name'])) ?>";
        var jam = new Date().getHours();
        var sapaanWaktu = "pagi";
        if (jam >= 0 && jam < 11) { sapaanWaktu = "pagi"; } else if (jam >= 11 && jam < 15) { sapaanWaktu = "siang"; } else if (jam >= 15 && jam < 18) { sapaanWaktu = "sore"; } else { sapaanWaktu = "malam"; }
        var processedText = text.replace(/\[NAMA\]/gi, namaPelanggan).replace(/\[WAKTU\]/gi, sapaanWaktu).replace(/\[CS\]/gi, namaCS);
        input.value = processedText;
        input.focus();
        toggleQRPresence();
        input.style.height = '24px';
        input.style.height = (input.scrollHeight) + 'px';
    }

    function tampilkanLightbox(imageSrc) {
        document.getElementById('lightboxImage').src = imageSrc;
        var lightboxModal = new bootstrap.Modal(document.getElementById('imageLightbox'));
        lightboxModal.show();
    }

    function toggleDarkMode() {
        var body = document.body;
        body.classList.toggle('dark-mode');
        if (body.classList.contains('dark-mode')) { localStorage.setItem('darkMode', 'enabled'); } 
        else { localStorage.setItem('darkMode', 'disabled'); }
    }
    if (localStorage.getItem('darkMode') === 'enabled') { document.body.classList.add('dark-mode'); }

    var searchInput = document.getElementById('searchContact');
    if(searchInput) {
        searchInput.addEventListener('keyup', function() {
            var keyword = this.value.toLowerCase();
            document.querySelectorAll('.contact-item').forEach(function(item) {
                var text = item.innerText.toLowerCase();
                item.style.display = text.includes(keyword) ? 'flex' : 'none';
            });
        });
    }

    function ambilChat() { fetch('assign_chat.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'phone=<?= $active_phone ?>' }).then(r => r.text()).then(res => { if(res.trim() == "success") { location.reload(); } else alert("Gagal!"); }); }
    function simpanNama() { var n = document.getElementById('editNamaInput').value; if(n.trim() == "") return alert("Nama tidak boleh kosong"); fetch('update_contact.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'phone=<?= $active_phone ?>&name=' + encodeURIComponent(n) }).then(r => r.text()).then(res => { if(res.trim() == "success") { location.reload(); } else alert("Gagal!"); }); }
    function simpanCatatan() { var notes = document.getElementById('inputNotes').value; fetch('update_note.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'phone=<?= $active_phone ?>&notes=' + encodeURIComponent(notes) }).then(r => r.text()).then(res => { if(res.trim() == "success") alert("Catatan disimpan!"); else alert("Gagal!"); }); }
    function simpanLabel() { var l = document.getElementById('labelSelect').value; fetch('update_label.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'phone=<?= $active_phone ?>&label=' + encodeURIComponent(l) }).then(r => r.text()).then(res => { if(res.trim() !== "success") alert("Gagal!"); }); }

    function setTypingStatus(isTyping) {
        var statusNormal = document.getElementById('statusPelanggan');
        var statusTyping = document.getElementById('typingIndicator');
        
        if(statusNormal && statusTyping) {
            if(isTyping) {
                statusNormal.classList.add('d-none');
                statusTyping.classList.remove('d-none');
            } else {
                statusTyping.classList.add('d-none');
                statusNormal.classList.remove('d-none');
            }
        }
    }

    // ==============================================================
    // AUTO REFRESH CHAT
    // ==============================================================
    setInterval(function(){
        if("<?= $active_phone ?>" !== "" && !window.isSelectingMode){
            fetch('get_chat.php?phone=<?= $active_phone ?>').then(r => r.text()).then(data => {
                var tempDiv = document.createElement('div');
                tempDiv.innerHTML = data;
                var currentCount = chatBox.querySelectorAll('.message-row').length;
                var newNodes = tempDiv.querySelectorAll('.message-row, .date-divider'); 
                var newsCount = tempDiv.querySelectorAll('.message-row').length;
                
                if(newsCount > currentCount) {
                    setTypingStatus(true);
                    setTimeout(function() {
                        var isAtBottom = (chatBox.scrollHeight - chatBox.scrollTop <= chatBox.clientHeight + 50);
                        var currentMsgIndex = 0;
                        for(var i = 0; i < newNodes.length; i++) {
                            if(newNodes[i].classList.contains('message-row')) { currentMsgIndex++; }
                            if(currentMsgIndex > currentCount || (newNodes[i].classList.contains('date-divider') && currentMsgIndex == currentCount)) {
                                chatBox.appendChild(newNodes[i].cloneNode(true));
                            }
                        }
                        if(isAtBottom) chatBox.scrollTop = chatBox.scrollHeight;
                        notifSound.play().catch(e => {});
                        setTypingStatus(false);
                    }, 1500);
                }
            });
        }
    }, 3000);

    // ==============================================================
    // AUTO REFRESH CONTACT LIST
    // ==============================================================
    setInterval(function(){
        if(!window.isContactSelectingMode) {
            fetch('dashboard.php?tab=<?= $tab ?>&phone=<?= $active_phone ?>').then(response => response.text()).then(html => {
                var parser = new DOMParser();
                var doc = parser.parseFromString(html, 'text/html');
                var oldList = document.getElementById('contactListArea');
                var newList = doc.getElementById('contactListArea');

                if(oldList.innerHTML.replace(/\s+/g,'') !== newList.innerHTML.replace(/\s+/g,'')){
                    oldList.innerHTML = newList.innerHTML;
                    var keyword = document.getElementById('searchContact').value.toLowerCase();
                    if(keyword !== "") {
                        document.querySelectorAll('.contact-item').forEach(function(item) {
                            var text = item.innerText.toLowerCase();
                            item.style.display = text.includes(keyword) ? 'flex' : 'none';
                        });
                    }
                }
            });
        }
    }, 5000);

    window.addEventListener('DOMContentLoaded', (event) => {
        let inputChat = document.getElementById('inputPesan');
        if(inputChat) {
            if(inputChat.value.trim() !== '') {
                inputChat.focus(); 
                inputChat.style.height = '24px';
                inputChat.style.height = (inputChat.scrollHeight) + 'px';
            }
            
            inputChat.addEventListener('input', function() {
                this.style.height = '24px';
                this.style.height = (this.scrollHeight) + 'px';
                toggleQRPresence();
            });
            
            inputChat.addEventListener('keydown', function(e) {
                if (window.innerWidth > 768) {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        if (this.value.trim() !== '') {
                            document.getElementById('btnKirimAsli').click();
                        }
                    }
                } 
            });
        }
    });

</script>
</body>
</html>