<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once __DIR__ . '/includes/auth_check.php';
require_once __DIR__ . '/includes/db_connect.php';

// Pagination settings
$perPage = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;

// Search and filter parameters
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? date('Y-m-d');

// Get total task completion stats
$taskStatsQuery = "SELECT 
    COUNT(DISTINCT ut.id) as total_tasks,
    SUM(CASE WHEN ut.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,
    COUNT(DISTINCT ut.user_id) as active_users
FROM user_tasks ut
WHERE DATE(ut.assigned_date) = CURDATE()";
$taskStats = $pdo->query($taskStatsQuery)->fetch(PDO::FETCH_ASSOC);

// Get user list for filter
$usersQuery = "SELECT id, full_name, email FROM users ORDER BY full_name";
$users = $pdo->query($usersQuery)->fetchAll(PDO::FETCH_ASSOC);

// Build the base query
$query = "SELECT 
            r.*, 
            u.full_name, 
            u.email, 
            u.phone,
            t.instruction_text as task_name,
            t.id as task_id,
            tc.name as category_name,
            tc.id as category_id,
            CONCAT('/vonaida/uploads/recordings/', r.filename) as file_path,
            (SELECT COUNT(*) FROM user_tasks ut2 
             WHERE ut2.user_id = u.id 
             AND DATE(ut2.assigned_date) = DATE(r.created_at)
             AND ut2.status = 'completed') as completed_tasks,
            (SELECT COUNT(*) FROM user_tasks ut3 
             WHERE ut3.user_id = u.id 
             AND DATE(ut3.assigned_date) = DATE(r.created_at)) as total_tasks
          FROM recordings r 
          LEFT JOIN users u ON r.user_id = u.id 
          LEFT JOIN tasks t ON r.task_id = t.id 
          LEFT JOIN task_categories tc ON t.category_id = tc.id 
          WHERE 1=1";
$params = [];

// Add search conditions
if (!empty($search)) {
    $query .= " AND (u.full_name LIKE ? OR u.email LIKE ? OR t.instruction_text LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm]);
}

// Add status filter
if (!empty($status) && in_array($status, ['pending', 'approved', 'rejected'])) {
    $query .= " AND r.status = ?";
    $params[] = $status;
}

// Add date range filter
if (!empty($dateFrom)) {
    $query .= " AND DATE(r.created_at) >= ?";
    $params[] = $dateFrom;
}
if (!empty($dateTo)) {
    $query .= " AND DATE(r.created_at) <= ?";
    $params[] = $dateTo;
}

// Get total count for pagination
$countQuery = str_replace(
    'r.*, u.full_name, u.email, t.instruction_text as task_name, tc.name as category_name, CONCAT(\'/vonaida/uploads/recordings/\', r.filename) as file_path', 
    'COUNT(*) as total', 
    $query
);
$countQuery = preg_replace('/ORDER BY.*$/', '', $countQuery); // Remove ORDER BY for count
$countStmt = $pdo->prepare($countQuery);
$countStmt->execute($params);
$result = $countStmt->fetch(PDO::FETCH_ASSOC);
$totalItems = isset($result['total']) ? (int)$result['total'] : 0;
$totalPages = $totalItems > 0 ? ceil($totalItems / $perPage) : 1;

// Add sorting and pagination - use direct variable interpolation for LIMIT and OFFSET
$query .= sprintf(" ORDER BY r.created_at DESC LIMIT %d OFFSET %d", 
    (int)$perPage, 
    (int)$offset
);

// Execute the main query
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$recordings = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Daily Task Tracking - Admin Panel</title>
  <link rel="stylesheet" href="assets/theme.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    .filters {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      padding: 1.5rem;
      margin-bottom: 1.5rem;
    }
    .filter-row {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem;
      margin-bottom: 1rem;
    }
    .filter-group {
      flex: 1;
      min-width: 200px;
    }
    .filter-group label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 500;
      color: #4a5568;
    }
    .filter-group input[type="text"],
    .filter-group select,
    .filter-group input[type="date"] {
      width: 100%;
      padding: 0.5rem;
      border: 1px solid #e2e8f0;
      border-radius: 4px;
      font-size: 0.9rem;
    }
    .actions {
      display: flex;
      gap: 0.5rem;
    }
    .btn {
      padding: 0.5rem 1rem;
      border-radius: 0.375rem;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      display: inline-flex;
      align-items: center;
      justify-content: center;
    }
    .btn i {
      margin-right: 0.5rem;
    }
    .btn-primary {
      background-color: #3b82f6;
      color: white;
      border: 1px solid #2563eb;
    }
    .btn-primary:hover {
      background-color: #2563eb;
    }
    .btn-outline {
      background-color: transparent;
      border: 1px solid #4b5563;
      color: #e5e7eb;
    }
    .btn-outline:hover {
      background-color: #374151;
    }
    .status-badge {
      display: inline-flex;
      align-items: center;
      padding: 0.25rem 0.75rem;
      border-radius: 9999px;
      font-size: 0.75rem;
      font-weight: 500;
      text-transform: capitalize;
    }
    .status-pending {
      background-color: rgba(251, 191, 36, 0.1);
      color: #fbbf24;
    }
    .status-approved {
      background-color: rgba(34, 197, 94, 0.1);
      color: #22c55e;
    }
    .status-rejected {
      background-color: rgba(239, 68, 68, 0.1);
      color: #ef4444;
    }
    .table {
      width: 100%;
      border-collapse: collapse;
    }
    .table th {
      text-align: left;
      padding: 0.75rem 1rem;
      font-weight: 500;
      color: #9ca3af;
      border-bottom: 1px solid #374151;
    }
    .table td {
      padding: 1rem;
      border-bottom: 1px solid #374151;
      color: #e5e7eb;
    }
    .table tr:last-child td {
      border-bottom: none;
    }
    .table tr:hover td {
      background-color: rgba(255, 255, 255, 0.03);
    }
    .pagination {
      display: flex;
      justify-content: flex-end;
      gap: 0.5rem;
      margin-top: 1.5rem;
    }
    .pagination a, .pagination span {
      padding: 0.5rem 1rem;
      border: 1px solid #374151;
      border-radius: 0.375rem;
      color: #e5e7eb;
      text-decoration: none;
      transition: all 0.2s;
    }
    .pagination a:hover {
      background-color: #374151;
    }
    .pagination .active {
      background-color: #3b82f6;
      border-color: #3b82f6;
      color: white;
    }
    .form-input {
      background-color: #1f2937;
      border: 1px solid #374151;
      border-radius: 0.375rem;
      padding: 0.5rem 0.75rem;
      color: #e5e7eb;
      width: 100%;
    }
    .form-input:focus {
      outline: none;
      border-color: #3b82f6;
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
    }
    .form-label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 500;
      color: #d1d5db;
    }
    .form-group {
      margin-bottom: 1rem;
    }
  </style>
</head>
<body class="dashboard-page">
  <aside class="sidebar">
    <div class="sidebar-brand">Wake Word</div>
    <nav class="nav">
      <a href="dashboard.php" class="nav-item">Dashboard</a>
      <a href="review_queue.php" class="nav-item">Review Queue</a>
      <a href="users.php" class="nav-item">Users</a>
      <a href="export.php" class="nav-item">Dataset Export</a>
      <a href="task_management.php" class="nav-item">Task Management</a>
      <a href="daily_task_tracking.php" class="nav-item active">Daily Task Tracking</a>
      <a href="audit_logs.php" class="nav-item">Audit Logs</a>
      <a href="logout.php" class="nav-item">Logout</a>
    </nav>
  </aside>

  <main class="main">
    <header class="topbar">
      <div class="topbar-left">Daily Task Tracking</div>
      <div class="topbar-right">Welcome, Admin</div>
    </header>

    <section class="content">
      <!-- Stats Overview -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="bg-gray-800 p-4 rounded-lg">
          <h3 class="text-lg font-medium text-gray-300 mb-2">Daily Tasks</h3>
          <div class="flex items-center justify-between">
            <div>
              <span class="text-2xl font-bold text-white"><?= $taskStats['completed_tasks'] ?? 0 ?></span>
              <span class="text-gray-400">/ <?= $taskStats['total_tasks'] ?? 0 ?> completed</span>
            </div>
            <div class="w-16 h-16">
              <div class="relative w-full h-full">
                <svg class="w-full h-full" viewBox="0 0 36 36">
                  <path
                    d="M18 2.0845
                      a 15.9155 15.9155 0 0 1 0 31.831
                      a 15.9155 15.9155 0 0 1 0 -31.831"
                    fill="none"
                    stroke="#2d3748"
                    stroke-width="4"
                  />
                  <path
                    d="M18 2.0845
                      a 15.9155 15.9155 0 0 1 0 31.831
                      a 15.9155 15.9155 0 0 1 0 -31.831"
                    fill="none"
                    stroke="#10b981"
                    stroke-width="4"
                    stroke-dasharray="<?= (($taskStats['completed_tasks'] ?? 0) / max(1, $taskStats['total_tasks'] ?? 1)) * 100 ?>, 100"
                    stroke-linecap="round"
                  />
                  <text x="18" y="20.5" text-anchor="middle" font-size="8" fill="#ffffff" font-weight="bold">
                    <?= $taskStats['total_tasks'] > 0 ? round(($taskStats['completed_tasks'] / $taskStats['total_tasks']) * 100) : 0 ?>%
                  </text>
                </svg>
              </div>
            </div>
          </div>
        </div>
        <div class="bg-gray-800 p-4 rounded-lg">
          <h3 class="text-lg font-medium text-gray-300 mb-2">Active Users</h3>
          <div class="flex items-center justify-between">
            <span class="text-3xl font-bold text-white"><?= $taskStats['active_users'] ?? 0 ?></span>
            <div class="text-green-400">
              <i class="fas fa-users text-4xl opacity-50"></i>
            </div>
          </div>
        </div>
        <div class="bg-gray-800 p-4 rounded-lg">
          <h3 class="text-lg font-medium text-gray-300 mb-2">Recordings Today</h3>
          <div class="flex items-center justify-between">
            <span class="text-3xl font-bold text-white"><?= count($recordings) ?></span>
            <div class="text-blue-400">
              <i class="fas fa-microphone text-4xl opacity-50"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- Filters -->
      <div class="card mb-6">
        <h3>Filters</h3>
        <form method="get" class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="filter-group">
            <label for="user_id" class="block text-sm font-medium text-gray-300 mb-1">User</label>
            <select name="user_id" id="user_id" class="w-full p-2 rounded bg-gray-700 border border-gray-600 text-white">
              <option value="">All Users</option>
              <?php foreach ($users as $user): ?>
                <option value="<?= $user['id'] ?>" <?= isset($_GET['user_id']) && $_GET['user_id'] == $user['id'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($user['full_name']) ?> (<?= htmlspecialchars($user['email']) ?>)
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Search</label>
            <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search..." class="form-input">
          </div>
          <div class="form-group">
            <label class="form-label">Status</label>
            <select name="status" class="form-input">
              <option value="">All Status</option>
              <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
              <option value="approved" <?= $status === 'approved' ? 'selected' : '' ?>>Approved</option>
              <option value="rejected" <?= $status === 'rejected' ? 'selected' : '' ?>>Rejected</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">From Date</label>
            <input type="date" name="date_from" value="<?= htmlspecialchars($dateFrom) ?>" class="form-input">
          </div>
          <div class="form-group">
            <label class="form-label">To Date</label>
            <input type="date" name="date_to" value="<?= htmlspecialchars($dateTo) ?>" class="form-input">
          </div>
          <div class="md:col-span-4 flex justify-end space-x-2">
            <button type="submit" class="btn btn-primary">
              <i class="fas fa-filter"></i> Apply Filters
            </button>
            <a href="daily_task_tracking.php" class="btn btn-outline">
              <i class="fas fa-sync-alt"></i> Reset
            </a>
          </div>
        </form>
      </div>

      <!-- Recordings Table -->
      <div class="card">
        <h3>Recordings</h3>
        <?php if (empty($recordings)): ?>
          <p>No recordings found.</p>
        <?php else: ?>
          <div class="overflow-x-auto">
            <table class="table">
              <thead>
                <tr>
                  <th>User</th>
                  <th>Task</th>
                  <th>Category</th>
                  <th>Duration</th>
                  <th>Recorded At</th>
                  <th>Task Progress</th>
                  <th>Status</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($recordings as $recording): ?>
                  <tr>
                    <td>
                      <div class="font-medium"><?= htmlspecialchars($recording['full_name']) ?></div>
                      <div class="text-sm text-gray-400"><?= htmlspecialchars($recording['email']) ?></div>
                    </td>
                    <td><?= htmlspecialchars($recording['task_name'] ?? 'N/A') ?></td>
                    <td><?= htmlspecialchars($recording['category_name'] ?? 'N/A') ?></td>
                    <td><?= gmdate('H:i:s', (int)$recording['duration']) ?></td>
                    <td><?= date('M d, Y H:i', strtotime($recording['created_at'])) ?></td>
                    <td>
                      <?php if ($recording['total_tasks'] > 0): ?>
                        <div class="w-full bg-gray-700 rounded-full h-2.5">
                          <div class="bg-green-500 h-2.5 rounded-full" 
                               style="width: <?= ($recording['completed_tasks'] / $recording['total_tasks']) * 100 ?>%">
                          </div>
                        </div>
                        <div class="text-xs text-gray-400 mt-1">
                          <?= $recording['completed_tasks'] ?>/<?= $recording['total_tasks'] ?> tasks
                        </div>
                      <?php else: ?>
                        <span class="text-gray-400 text-sm">No tasks</span>
                      <?php endif; ?>
                    </td>
                    <td>
                      <?php 
                      $statusClass = [
                        'pending' => 'bg-yellow-500/20 text-yellow-400',
                        'approved' => 'bg-green-500/20 text-green-400',
                        'rejected' => 'bg-red-500/20 text-red-400'
                      ][$recording['status']] ?? 'bg-gray-500/20 text-gray-400';
                      ?>
                      <span class="px-2 py-1 text-xs font-medium rounded-full <?= $statusClass ?>">
                        <?= ucfirst($recording['status']) ?>
                      </span>
                    </td>
                    <td class="whitespace-nowrap">
                      <div class="flex items-center space-x-1">
                        <button onclick="viewRecording(<?= htmlspecialchars(json_encode($recording), ENT_QUOTES, 'UTF-8') ?>)" 
                                class="btn btn-outline btn-sm" 
                                title="View Details">
                          <i class="fas fa-eye"></i>
                        </button>
                        <?php if (!empty($recording['file_path'])): ?>
                          <a href="<?= htmlspecialchars($recording['file_path']) ?>" 
                             download 
                             class="btn btn-outline btn-sm text-blue-400 hover:bg-blue-900/50 hover:border-blue-400 hover:text-blue-300"
                             title="Download Audio">
                            <i class="fas fa-download"></i>
                          </a>
                        <?php else: ?>
                          <button class="btn btn-outline btn-sm text-gray-500 cursor-not-allowed" 
                                  title="No audio file available" disabled>
                            <i class="fas fa-download"></i>
                          </button>
                        <?php endif; ?>
                        <?php if ($recording['status'] === 'pending'): ?>
                          <button onclick="updateStatus(<?= $recording['id'] ?>, 'approved')" 
                                  class="btn btn-outline btn-sm text-green-400 hover:bg-green-900/50 hover:border-green-400 hover:text-green-300" 
                                  title="Approve">
                            <i class="fas fa-check"></i>
                          </button>
                          <button onclick="updateStatus(<?= $recording['id'] ?>, 'rejected')" 
                                  class="btn btn-outline btn-sm text-red-400 hover:bg-red-900/50 hover:border-red-400 hover:text-red-300" 
                                  title="Reject">
                            <i class="fas fa-times"></i>
                          </button>
                        <?php endif; ?>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>

          <!-- Pagination -->
          <?php if ($totalPages > 1): ?>
            <div class="pagination">
              <?php if ($page > 1): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => 1])) ?>">
                  <i class="fas fa-angle-double-left"></i>
                </a>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">
                  <i class="fas fa-angle-left"></i>
                </a>
              <?php endif; ?>
              
              <?php for ($i = max(1, $page - 2); $i <= min($page + 2, $totalPages); $i++): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" class="<?= $i == $page ? 'active' : '' ?>">
                  <?= $i ?>
                </a>
              <?php endfor; ?>
              
              <?php if ($page < $totalPages): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">
                  <i class="fas fa-angle-right"></i>
                </a>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $totalPages])) ?>">
                  <i class="fas fa-angle-double-right"></i>
                </a>
              <?php endif; ?>
            </div>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </section>
  </main>

  <!-- View Recording Modal -->
  <div id="recordingModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center hidden z-50 p-4" onclick="closeModal()">
    <div class="bg-gray-800 border border-gray-700 rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto relative" onclick="event.stopPropagation()">
      <!-- Close button (X) at top right -->
      <button onclick="closeModal()" class="absolute top-4 right-4 text-gray-400 hover:text-white p-1 rounded-full hover:bg-gray-700 transition-colors">
        <i class="fas fa-times text-xl"></i>
      </button>
      
      <!-- Modal content -->
      <div class="pr-6">
        <h3 class="text-xl font-semibold text-white mb-6 pb-4 border-b border-gray-700">Recording Details</h3>
        <div id="recordingDetails" class="space-y-4">
          <!-- Filled by JavaScript -->
        </div>
        <div class="mt-6 pt-4 border-t border-gray-700 flex justify-end">
          <button onclick="closeModal()" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-md transition-colors flex items-center">
            <i class="fas fa-times mr-2"></i> Close
          </button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // Ensure modal is hidden on page load
    document.addEventListener('DOMContentLoaded', function() {
      const modal = document.getElementById('recordingModal');
      if (modal) {
        modal.style.display = 'none';
      }
    });

    // Function to update recording status
    function updateStatus(recordingId, status) {
      const statusText = {approved: 'approve', rejected: 'reject'}[status] || status;
      const note = prompt(`Enter a note for ${statusText} (optional):`) || '';
      
      if (confirm(`Are you sure you want to ${statusText} this recording?`)) {
        const formData = new FormData();
        formData.append('recording_id', recordingId);
        formData.append('status', status);
        formData.append('note', note);
        
        // Show loading state
        const button = event.target.closest('button');
        const originalHTML = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        button.disabled = true;
        
        fetch('update_recording_status.php', {
          method: 'POST',
          body: formData
        })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            // Show success message
            const toast = document.createElement('div');
            toast.className = 'fixed bottom-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg flex items-center';
            toast.innerHTML = `
              <i class="fas fa-check-circle mr-2"></i>
              <span>Recording ${statusText}ed successfully</span>
            `;
            document.body.appendChild(toast);
            
            // Reload after a short delay
            setTimeout(() => {
              window.location.reload();
            }, 1000);
          } else {
            throw new Error(data.message || 'Failed to update status');
          }
        })
        .catch(error => {
          console.error('Error:', error);
          alert('Error: ' + (error.message || 'Failed to update status'));
          button.innerHTML = originalHTML;
          button.disabled = false;
        });
      }
      return false;
    }

    // Function to view recording details in a modal
    function viewRecording(recording) {
      const modal = document.getElementById('recordingModal');
      const detailsDiv = document.getElementById('recordingDetails');
      
      // Format the recording details
      const detailsHtml = `
        <div class="space-y-4">
          <div class="bg-gray-750 p-4 rounded-lg">
            <h4 class="font-semibold text-gray-300 mb-1">User Information</h4>
            <p class="text-white">${recording.full_name} <span class="text-gray-400">(${recording.email})</span></p>
          </div>
          <div class="bg-gray-750 p-4 rounded-lg">
            <h4 class="font-semibold text-gray-300 mb-1">Task</h4>
            <p class="text-white">${recording.task_name}</p>
            <p class="text-sm text-gray-400">${recording.category_name}</p>
          </div>
          <div class="bg-gray-750 p-4 rounded-lg">
            <h4 class="font-semibold text-gray-300 mb-2">Recording</h4>
            <audio controls class="w-full mt-2 rounded-lg" style="background-color: #1f2937;">
              <source src="${recording.file_path}" type="audio/wav">
              <source src="${recording.file_path.replace(/\.wav$/, '.mp3')}" type="audio/mp3">
              Your browser does not support the audio element. <a href="${recording.file_path}" download>Download audio</a>
            </audio>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="bg-gray-750 p-4 rounded-lg">
              <h4 class="font-semibold text-gray-300 mb-1">Duration</h4>
              <p class="text-white">${new Date(recording.duration * 1000).toISOString().substr(11, 8)}</p>
            </div>
            <div class="bg-gray-750 p-4 rounded-lg">
              <h4 class="font-semibold text-gray-300 mb-1">Recorded At</h4>
              <p class="text-white">${new Date(recording.created_at).toLocaleString()}</p>
            </div>
          </div>
          <div class="bg-gray-750 p-4 rounded-lg">
            <h4 class="font-semibold text-gray-300 mb-1">Status</h4>
            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${getStatusBadgeClass(recording.status)}">
              ${recording.status.charAt(0).toUpperCase() + recording.status.slice(1)}
            </span>
          </div>
          ${recording.notes ? `
          <div class="bg-gray-750 p-4 rounded-lg">
            <h4 class="font-semibold text-gray-300 mb-1">Admin Notes</h4>
            <p class="text-gray-200">${recording.notes}</p>
          </div>` : ''}
        </div>
      `;
      
      detailsDiv.innerHTML = detailsHtml;
      modal.style.display = 'flex';
      
      // Prevent body scroll when modal is open
      document.body.style.overflow = 'hidden';
    }
    
    // Helper function to get status badge class
    function getStatusBadgeClass(status) {
      const statusClasses = {
        'pending': 'bg-yellow-100 text-yellow-800',
        'approved': 'bg-green-100 text-green-800',
        'rejected': 'bg-red-100 text-red-800'
      };
      return statusClasses[status] || 'bg-gray-100 text-gray-800';
    }
    
    // Close modal function
    function closeModal() {
      const modal = document.getElementById('recordingModal');
      modal.style.display = 'none';
      document.body.style.overflow = 'auto';
    }
    
    // Close modal when pressing Escape key
    document.addEventListener('keydown', function(event) {
      if (event.key === 'Escape') {
        closeModal();
      }
    });
  </script>
</body>
</html>
