<?php
declare(strict_types=1);
session_start();
$role = (string)($_SESSION['role'] ?? 'Buyer');
if ($role !== 'Admin') { header('Location: login.html'); exit; }

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
  $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  ]);
} catch (Throwable $e) {
  http_response_code(500);
  echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='admin-dashboard.php';</script></body></html>";
  exit;
}

try {
  $pdo->exec('CREATE TABLE IF NOT EXISTS users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}
try {
  $pdo->exec('CREATE TABLE IF NOT EXISTS chat_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT UNSIGNED NOT NULL,
    sender ENUM("user","admin") NOT NULL,
    content TEXT NOT NULL,
    is_read TINYINT(1) NOT NULL DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

if (isset($_GET['action'])) {
  header('Content-Type: application/json');
  $action = (string)$_GET['action'];
  if ($action === 'unread_count') {
    try { $c = (int)$pdo->query("SELECT COUNT(*) c FROM chat_messages WHERE sender='user' AND is_read=0")->fetchColumn(); } catch (Throwable $e) { $c = 0; }
    echo json_encode(['count' => $c]);
    exit;
  }
  if ($action === 'list_users') {
    try {
      $rows = $pdo->query('SELECT u.id, u.username, u.email, COALESCE(SUM(CASE WHEN m.sender="user" AND m.is_read=0 THEN 1 ELSE 0 END),0) AS unread, MAX(m.created_at) AS last_at FROM users u LEFT JOIN chat_messages m ON m.user_id=u.id GROUP BY u.id, u.username, u.email ORDER BY last_at DESC')->fetchAll();
    } catch (Throwable $e) { $rows = []; }
    echo json_encode(['items' => $rows]);
    exit;
  }
  if ($action === 'list' && isset($_GET['user_id'])) {
    $uid = (int)$_GET['user_id'];
    try {
      $st = $pdo->prepare('SELECT id,sender,content,is_read,created_at FROM chat_messages WHERE user_id=:u ORDER BY created_at ASC LIMIT 500');
      $st->execute([':u'=>$uid]);
      $items = $st->fetchAll();
      $pdo->prepare("UPDATE chat_messages SET is_read=1 WHERE user_id=:u AND sender='user' AND is_read=0")->execute([':u'=>$uid]);
    } catch (Throwable $e) { $items = []; }
    echo json_encode(['items'=>$items]);
    exit;
  }
  if ($action === 'send' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $uid = (int)($_POST['user_id'] ?? 0);
    $content = trim((string)($_POST['content'] ?? ''));
    if ($uid <= 0 || $content === '') { echo json_encode(['ok'=>false]); exit; }
    try {
      $st = $pdo->prepare("INSERT INTO chat_messages(user_id,sender,content) VALUES(:u,'admin',:c)");
      $st->execute([':u'=>$uid, ':c'=>$content]);
      echo json_encode(['ok'=>true]);
    } catch (Throwable $e) { echo json_encode(['ok'=>false]); }
    exit;
  }
  echo json_encode(['ok'=>false]);
  exit;
}
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Admin Chat - ListBnb</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
  <link rel="stylesheet" href="assets/css/bootstrap.css">
  <link rel="stylesheet" href="assets/css/animate.css">
  <link rel="stylesheet" href="assets/css/swiper-bundle.css">
  <link rel="stylesheet" href="assets/css/slick.css">
  <link rel="stylesheet" href="assets/css/magnific-popup.css">
  <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
  <link rel="stylesheet" href="assets/css/spacing.css">
  <link rel="stylesheet" href="assets/css/custom-animation.css">
  <link rel="stylesheet" href="assets/css/main.css">
  <style>
    :root {
      --primary: #4f46e5;
      --primary-light: #eef2ff;
      --primary-dark: #4338ca;
      --success: #10b981;
      --danger: #ef4444;
      --warning: #f59e0b;
      --dark: #1f2937;
      --light: #f9fafb;
      --border: #e5e7eb;
      --text: #374151;
      --text-light: #6b7280;
      --radius: 12px;
      --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
      --transition: all 0.2s ease-in-out;
    }

    body {
      background-color: #f3f4f6;
      color: var(--text);
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      line-height: 1.5;
    }

    /* Chat Layout */
    .chat-admin {
      display: grid;
      grid-template-columns: 320px 1fr;
      gap: 24px;
      height: calc(100vh - 200px);
      max-height: 800px;
      background: #fff;
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      overflow: hidden;
    }

    @media (max-width: 991px) {
      .chat-admin {
        grid-template-columns: 1fr;
        height: auto;
      }
    }

    /* Users List */
    .chat-users {
      background: #fff;
      border-right: 1px solid var(--border);
      overflow-y: auto;
      display: flex;
      flex-direction: column;
    }

    .chat-users-header {
      padding: 16px 20px;
      font-size: 18px;
      font-weight: 600;
      color: var(--dark);
      border-bottom: 1px solid var(--border);
      background: #fff;
      position: sticky;
      top: 0;
      z-index: 10;
    }

    .chat-user {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 14px 16px;
      cursor: pointer;
      transition: var(--transition);
      border-bottom: 1px solid var(--border);
      position: relative;
    }

    .chat-user:last-child {
      border-bottom: none;
    }

    .chat-user:hover {
      background: var(--primary-light);
    }

    .chat-user.active {
      background: var(--primary-light);
      border-left: 3px solid var(--primary);
    }

    .user-avatar {
      width: 44px;
      height: 44px;
      border-radius: 10px;
      background: var(--primary);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      font-size: 18px;
      text-transform: uppercase;
      flex-shrink: 0;
    }

    .user-info {
      flex: 1;
      min-width: 0;
    }

    .user-name {
      font-weight: 600;
      color: var(--dark);
      margin-bottom: 2px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .user-email {
      font-size: 12px;
      color: var(--text-light);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .badge {
      margin-left: auto;
      min-width: 22px;
      height: 22px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: var(--danger);
      color: #fff;
      border-radius: 999px;
      font-size: 12px;
      font-weight: 500;
      padding: 0 6px;
      flex-shrink: 0;
    }

    /* Chat Room */
    .chat-room {
      display: flex;
      flex-direction: column;
      height: 100%;
      background: #f8f9fa;
    }

    .chat-head {
      padding: 16px 24px;
      background: #fff;
      border-bottom: 1px solid var(--border);
      font-weight: 600;
      font-size: 16px;
      color: var(--dark);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .chat-head .back-btn {
      display: none;
      background: none;
      border: none;
      font-size: 18px;
      color: var(--text-light);
      cursor: pointer;
      margin-right: 12px;
    }

    .chat-body {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .msg {
      max-width: 75%;
      padding: 12px 16px;
      border-radius: 16px;
      position: relative;
      line-height: 1.5;
      word-wrap: break-word;
      animation: fadeIn 0.3s ease;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .msg.me {
      margin-left: auto;
      background: var(--primary);
      color: white;
      border-top-right-radius: 4px;
    }

    .msg.other {
      background: #fff;
      border: 1px solid var(--border);
      border-top-left-radius: 4px;
    }

    .msg-time {
      font-size: 11px;
      color: var(--text-light);
      margin-top: 4px;
      text-align: right;
    }

    .msg.me .msg-time {
      color: rgba(255, 255, 255, 0.8);
    }

    /* Chat Input */
    .chat-input {
      display: block;
      padding: 16px 24px;
      background: #fff;
      border-top: 1px solid var(--border);
    }

    .chat-input input {
      width: 100%;
      height: 48px;
      border: 1px solid var(--border);
      border-radius: 24px;
      padding: 0 80px 0 20px; /* extra right padding for button overlap */
      font-size: 15px;
      transition: var(--transition);
      outline: none;
    }

    .chat-input input:focus {
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }

    .chat-input button {
      height: 48px;
      border-radius: 24px;
      border: none;
      background: var(--primary);
      color: white;
      padding: 0 24px;
      font-weight: 500;
      cursor: pointer;
      transition: var(--transition);
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .chat-input button:hover {
      background: var(--primary-dark);
    }

    .chat-input button i {
      font-size: 16px;
    }
    #chat-send{position: absolute; right: 32px; top: 50%; transform: translateY(-50%); margin: 0; z-index: 2}
    .chat-room{position: relative}
    .chat-input{position: sticky; bottom: 0}
    .chat-input button:disabled{opacity:.6; cursor:not-allowed}

    /* Empty State */
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: var(--text-light);
      text-align: center;
      padding: 24px;
    }

    .empty-state i {
      font-size: 48px;
      margin-bottom: 16px;
      color: var(--border);
    }

    /* Responsive */
    @media (max-width: 767px) {
      .chat-admin {
        height: calc(100vh - 160px);
      }
      
      .chat-head .back-btn {
        display: block;
      }
      
      .chat-user {
        padding: 12px;
      }
      
      .chat-input {
        padding: 12px 16px;
      }
      
      .chat-input button {
        padding: 0 16px;
      }
    }
    @media (max-width: 480px) {
      .chat-input input { padding-right: 56px; }
      #chat-send { right: 20px; }
      #chat-send span { display: none; }
      #chat-send { padding: 0 12px; }
    }
    .header-left{display:flex;align-items:center;gap:12px}
    .admin-headline{font-weight:800;font-size:24px;color:var(--dark)}
    .tp-header-area.tp-header-inner-style{margin-bottom:0}
    .tp-profile-area{padding-top:8px !important;padding-bottom:48px !important}
  </style>
</head>
<body>
  <header class="tp-header-height">
    <div id="header-sticky" class="tp-header-area tp-header-inner-style">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-xl-3 col-lg-6 col-md-6 col-6">
            <div class="header-left">
              <div class="admin-headline">Admin Dashboard</div>
            </div>
          </div>
          <div class="col-xl-6 col-lg-4 d-none d-xl-block">
            <div class="tp-header-menu">
              <nav class="tp-main-menu-content">
                <ul></ul>
              </nav>
            </div>
          </div>
          <div class="col-xl-3 col-lg-6 col-md-6 col-6">
            <div class="tp-header-right d-flex align-items-center justify-content-end">
              <div class="tp-header-sign-box d-none d-sm-block">
                <a href="logout.php"><i class="fa-solid fa-right-from-bracket"></i>Logout</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>

  <main>
    <section class="tp-profile-area z-index pb-120 pt-60">
      <div class="container">
        <div class="chat-admin">
          <div class="chat-users">
            <div class="chat-users-header">Messages</div>
            <div id="chat-users"></div>
          </div>
          <div class="chat-room">
            <div class="chat-head" id="room-head">
              <button class="back-btn" id="back-to-users"><i class="fa-solid fa-arrow-left"></i></button>
              <span>Select a user to start chatting</span>
            </div>
            <div class="chat-body" id="chat-body">
              <div class="empty-state">
                <i class="fa-regular fa-comments"></i>
                <h4>No conversation selected</h4>
                <p>Select a user from the list to start chatting or view your messages.</p>
              </div>
            </div>
            <div class="chat-input">
              <input type="text" id="chat-text" placeholder="Type your message...">
              <button id="chat-send" type="button">
                <i class="fa-regular fa-paper-plane"></i>
                <span>Send</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>

  <script src="assets/js/vendor/jquery.js"></script>
  <script src="assets/js/bootstrap-bundle.js"></script>
  <script src="assets/js/slick.js"></script>
  <script src="assets/js/main.js"></script>
  <script>
    (function(){
      // DOM Elements
      const usersEl = document.getElementById('chat-users');
      const bodyEl = document.getElementById('chat-body');
      const headEl = document.getElementById('room-head').querySelector('span');
      const backBtn = document.getElementById('back-to-users');
      const chatAdmin = document.querySelector('.chat-admin');
      let currentUserId = 0;
      let usersData = [];

      // Format time
      function formatTime(dateString) {
        try {
          const date = new Date(dateString);
          const now = new Date();
          const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24));
          
          if (diffDays === 0) {
            // Today - show time
            return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
          } else if (diffDays === 1) {
            // Yesterday
            return 'Yesterday';
          } else if (diffDays < 7) {
            // Within a week - show day name
            return date.toLocaleDateString([], { weekday: 'short' });
          } else {
            // Older - show date
            return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
          }
        } catch (e) {
          return '';
        }
      }

      // Escape HTML to prevent XSS
      function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
      }

      // Load users list
      function loadUsers() {
        fetch('admin-chat.php?action=list_users')
          .then(r => r.json())
          .then(data => {
            usersData = data.items || [];
            renderUsersList(usersData);
            if (currentUserId) {
              // If we have an active chat, make sure it's marked as active
              const activeUser = usersData.find(u => u.id == currentUserId);
              if (activeUser) {
                updateChatHeader(activeUser);
              }
            }
          });
      }

      // Render users list
      function renderUsersList(users) {
        if (!users || users.length === 0) {
          usersEl.innerHTML = `
            <div class="empty-state" style="padding: 40px 20px;">
              <i class="fa-regular fa-user-group" style="font-size: 32px;"></i>
              <p>No users found</p>
            </div>
          `;
          return;
        }

        usersEl.innerHTML = users.map(user => {
          const unreadBadge = user.unread > 0 ? 
            `<span class="badge">${user.unread}</span>` : '';
          const lastMessageTime = user.last_at ? formatTime(user.last_at) : '';
          
          return `
            <div class="chat-user ${currentUserId == user.id ? 'active' : ''}" data-id="${user.id}">
              <div class="user-avatar">${(user.username || 'U').charAt(0).toUpperCase()}</div>
              <div class="user-info">
                <div class="user-name">${escapeHtml(user.username || 'User')}</div>
                <div class="user-email">${escapeHtml(user.email || '')}</div>
              </div>
              ${unreadBadge}
            </div>
          `;
        }).join('');

        // Add event listeners
        document.querySelectorAll('.chat-user').forEach(el => {
          el.addEventListener('click', () => {
            const userId = parseInt(el.getAttribute('data-id')) || 0;
            const user = usersData.find(u => u.id == userId);
            if (user) {
              selectUser(user);
            }
          });
        });
      }

      // Select user and load chat
      function selectUser(user) {
        currentUserId = user.id;
        updateChatHeader(user);
        loadThread();
        
        // Update active state in users list
        document.querySelectorAll('.chat-user').forEach(el => {
          if (parseInt(el.getAttribute('data-id')) === user.id) {
            el.classList.add('active');
          } else {
            el.classList.remove('active');
          }
        });
        
        // On mobile, show chat area and hide users list
        if (window.innerWidth < 992) {
          chatAdmin.classList.add('show-chat');
        }
        updateSendState();
      }

      // Update chat header with user info
      function updateChatHeader(user) {
        if (!user) {
          headEl.textContent = 'Select a user to start chatting';
          return;
        }
        headEl.textContent = user.username || 'User';
      }

      // Render messages
      function renderMessages(messages) {
        if (!messages || messages.length === 0) {
          bodyEl.innerHTML = `
            <div class="empty-state">
              <i class="fa-regular fa-comment-dots"></i>
              <p>No messages yet</p>
              <p class="text-muted">Send a message to start the conversation</p>
            </div>
          `;
          return;
        }

        bodyEl.innerHTML = messages.map(msg => {
          const isMe = msg.sender === 'admin';
          const time = formatTime(msg.created_at);
          
          return `
            <div class="msg ${isMe ? 'me' : 'other'}">
              <div>${escapeHtml(msg.content)}</div>
              <div class="msg-time">${time}</div>
            </div>
          `;
        }).join('');
        
        // Scroll to bottom
        bodyEl.scrollTop = bodyEl.scrollHeight;
      }

      // Load chat thread
      function loadThread() {
        if (!currentUserId) return;
        
        fetch(`admin-chat.php?action=list&user_id=${encodeURIComponent(currentUserId)}`)
          .then(r => r.json())
          .then(data => {
            renderMessages(data.items || []);
            // Refresh users list to update unread counts
            loadUsers();
          });
      }

      // Send message
      function sendMessage() {
        const input = document.getElementById('chat-text');
        const btn = document.getElementById('chat-send');
        const message = (input.value || '').trim();
        if (!message || !currentUserId) return;
        input.disabled = true;
        btn.disabled = true;
        fetch('admin-chat.php?action=send', {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: `user_id=${encodeURIComponent(currentUserId)}&content=${encodeURIComponent(message)}`
        })
        .then(r => r.json())
        .then(data => {
          if (data && data.ok) {
            loadThread();
          } else {
            console.error('Failed to send message');
          }
        })
        .catch(error => {
          console.error('Error sending message:', error);
        })
        .finally(() => {
          input.disabled = false;
          btn.disabled = false;
          input.value = '';
          updateSendState();
          input.focus();
        });
      }

      // Event Listeners
      document.getElementById('chat-send').addEventListener('click', sendMessage);
      
      // Send message on Enter key
      document.getElementById('chat-text').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          sendMessage();
        }
      });
      // Enable/disable send button depending on state
      function updateSendState(){
        const btn = document.getElementById('chat-send');
        const val = (document.getElementById('chat-text').value||'').trim();
        btn.disabled = !(currentUserId && val.length>0);
      }
      document.getElementById('chat-text').addEventListener('input', updateSendState);
      
      // Back button (for mobile)
      backBtn.addEventListener('click', () => {
        chatAdmin.classList.remove('show-chat');
      });

      // Initial load
      loadUsers();
      updateSendState();
      
      // Poll for new messages
      setInterval(() => {
        if (currentUserId) {
          loadThread();
        } else {
          loadUsers();
        }
      }, 5000);
      
      // Handle window resize for responsive behavior
      function handleResize() {
        if (window.innerWidth >= 992) {
          chatAdmin.classList.remove('show-chat');
        }
      }
      
      window.addEventListener('resize', handleResize);
    })();
  </script>
</body>
</html>
