<?php
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';

// Function to generate a consistent color for categories
function getCategoryColor($categoryId) {
    // Array of nice colors that work well on dark backgrounds
    $colors = [
        '#3b82f6', // blue-500
        '#10b981', // emerald-500
        '#f59e0b', // amber-500
        '#8b5cf6', // violet-500
        '#ec4899', // pink-500
        '#14b8a6', // teal-500
        '#f97316', // orange-500
        '#6366f1', // indigo-500
    ];
    
    // Use modulo to cycle through colors if we have more categories than colors
    return $colors[$categoryId % count($colors)];
}

// Initialize filters with default values
$filters = [
    'status' => isset($_GET['status']) ? trim($_GET['status']) : 'all',
    'date_from' => isset($_GET['date_from']) ? trim($_GET['date_from']) : date('Y-m-d', strtotime('-7 days')),
    'date_to' => isset($_GET['date_to']) ? trim($_GET['date_to']) : date('Y-m-d'),
    'user_id' => isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0,
    'task_id' => isset($_GET['task_id']) ? (int)$_GET['task_id'] : 0,
    'category_id' => isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0,
    'gender' => isset($_GET['gender']) ? trim($_GET['gender']) : '',
    'ethnicity' => isset($_GET['ethnicity']) ? trim($_GET['ethnicity']) : '',
    'quality_status' => isset($_GET['quality_status']) ? trim($_GET['quality_status']) : ''
];

// Initialize variables to prevent undefined variable errors
$users = [];
$tasks = [];
$genders = [];
$ethnicities = [];
$recordings = [];
$totalRecordings = 0;
$totalPages = 1;
$page = 1;

// Build the main query with pagination
$query = "SELECT r.*, 
                 u.full_name, u.phone, u.gender, u.ethnicity, 
                 t.title as task_title,
                 t.instruction_text as task_instruction,
                 tc.name as category_name,
                 tc.id as category_id
          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";

// Add filters to query with named parameters
$params = [];

if ($filters['status'] !== 'all') {
    $query .= " AND r.status = :status";
    $params[':status'] = $filters['status'];
}

if ($filters['date_from']) {
    $query .= " AND DATE(r.created_at) >= :date_from";
    $params[':date_from'] = $filters['date_from'];
}

if ($filters['date_to']) {
    $query .= " AND DATE(r.created_at) <= :date_to";
    $params[':date_to'] = $filters['date_to'];
}

if ($filters['user_id']) {
    $query .= " AND r.user_id = :user_id";
    $params[':user_id'] = $filters['user_id'];
}

if ($filters['task_id']) {
    $query .= " AND r.task_id = :task_id";
    $params[':task_id'] = $filters['task_id'];
}

if ($filters['category_id']) {
    $query .= " AND tc.id = :category_id";
    $params[':category_id'] = $filters['category_id'];
}

if ($filters['gender']) {
    $query .= " AND u.gender = :gender";
    $params[':gender'] = $filters['gender'];
}

if ($filters['ethnicity']) {
    $query .= " AND u.ethnicity = :ethnicity";
    $params[':ethnicity'] = $filters['ethnicity'];
}

if ($filters['quality_status']) {
    $query .= " AND r.quality_status = :quality_status";
    $params[':quality_status'] = $filters['quality_status'];
}

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

// Build count query by replacing SELECT clause
$countQuery = "SELECT COUNT(*) as total FROM (" . str_replace(
    "SELECT r.*, u.full_name, u.phone, u.gender, u.ethnicity, t.title as task_title, tc.name as category_name, tc.id as category_id",
    "SELECT r.id",
    $query
) . ") as count_table";

// Prepare and execute count query
$countStmt = $pdo->prepare($countQuery);
foreach ($params as $key => $value) {
    $countStmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$countStmt->execute();
$totalRecordings = $countStmt->fetchColumn();
$totalPages = ceil($totalRecordings / $perPage);

// Add pagination to main query
$query .= " ORDER BY r.created_at DESC LIMIT :per_page OFFSET :offset";

// Prepare and execute main query
$stmt = $pdo->prepare($query);

// Bind all parameters including pagination
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
}

// Bind pagination parameters
$stmt->bindValue(':per_page', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

$stmt->execute();
$recordings = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get filter options with error handling
try {
    // Get active users
    $users = $pdo->query("SELECT id, full_name, phone FROM users ORDER BY full_name")->fetchAll();
    
    // Get task categories for filter dropdown
    $categoriesQuery = "SELECT id, name FROM task_categories ORDER BY name";
    $categories = $pdo->query($categoriesQuery)->fetchAll(PDO::FETCH_ASSOC);

    // Get tasks for reference
    $tasksQuery = "SELECT id, title, category_id FROM tasks ORDER BY title";
    $tasks = $pdo->query($tasksQuery)->fetchAll(PDO::FETCH_ASSOC);
    $tasksByCategory = [];
    foreach ($tasks as $task) {
        $tasksByCategory[$task['category_id']][] = $task;
    }
    
    // Get unique genders
    $genders = $pdo->query("SELECT DISTINCT gender FROM users WHERE gender IS NOT NULL AND gender != ''")->fetchAll(PDO::FETCH_COLUMN);
    
    // Get unique ethnicities
    $ethnicities = $pdo->query("SELECT DISTINCT ethnicity FROM users WHERE ethnicity IS NOT NULL AND ethnicity != ''")->fetchAll(PDO::FETCH_COLUMN);
    
    // Set empty arrays if no results
    $users = $users ?: [];
    $tasks = $tasks ?: [];
    $categories = $categories ?: [];
    $genders = $genders ?: [];
    $ethnicities = $ethnicities ?: [];
    
} catch (PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    $error = "Error loading filter options: " . $e->getMessage();
}

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!empty($_POST['selected_recordings'])) {
        $ids = array_map('intval', $_POST['selected_recordings']);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        
        switch ($_POST['action']) {
            case 'approve':
                $stmt = $pdo->prepare("UPDATE recordings SET status = 'approved' WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                break;
                
            case 'reject':
                $stmt = $pdo->prepare("UPDATE recordings SET status = 'rejected' WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                break;
                
            case 'delete':
                // In a real app, you might want to actually delete the files too
                $stmt = $pdo->prepare("DELETE FROM recordings WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                break;
                
            case 'download':
        $ids = $_POST['ids'] ?? $_REQUEST['ids'] ?? [];
        if (!$ids || !is_array($ids)) {
            http_response_code(400);
            echo "No recordings selected.";
            exit;
        }

        // Sanitize ids
        $ids = array_map('intval', $ids);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));

        // Get recordings info
        $stmt = $pdo->prepare("SELECT id, filename, filepath, title, created_at FROM recordings WHERE id IN ($placeholders)");
        $stmt->execute($ids);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!$rows) {
            http_response_code(404);
            echo "No valid recordings found.";
            exit;
        }

        // Create a temporary zip
        $tmpZip = tempnam(sys_get_temp_dir(), 'reczip_');
        $zip = new ZipArchive();
        if ($zip->open($tmpZip, ZipArchive::OVERWRITE) !== true) {
            http_response_code(500);
            echo "Failed to create ZIP file.";
            exit;
        }

        // Create CSV in memory
        $csvHandle = fopen('php://temp', 'r+');
        fputcsv($csvHandle, ['id', 'title', 'filename', 'filepath', 'created_at']);

        foreach ($rows as $row) {
            fputcsv($csvHandle, [
                $row['id'],
                $row['title'] ?? '',
                $row['filename'] ?? '',
                $row['filepath'] ?? '',
                $row['created_at'] ?? '',
            ]);

            $filePath = $row['filepath'] ?? (__DIR__ . '/uploads/' . ($row['filename'] ?? ''));
            if (file_exists($filePath) && is_readable($filePath)) {
                $zip->addFile($filePath, 'recordings/' . basename($filePath));
            } else {
                $zip->addFromString("missing_{$row['id']}.txt", "File not found: $filePath");
            }
        }

        rewind($csvHandle);
        $csvData = stream_get_contents($csvHandle);
        fclose($csvHandle);
        $zip->addFromString('recordings_list.csv', $csvData);

        $zip->close();

        // Send the zip
        while (ob_get_level()) ob_end_clean();

        $zipFilename = 'recordings_' . date('Y-m-d_H-i-s') . '.zip';
        header('Content-Type: application/zip');
        header('Content-Length: ' . filesize($tmpZip));
        header('Content-Disposition: attachment; filename=\"' . $zipFilename . '\"');
        readfile($tmpZip);
        unlink($tmpZip);
        exit;
        }
        
        // Redirect to avoid form resubmission
        header("Location: ".$_SERVER['PHP_SELF'].'?'.http_build_query($filters));
        exit;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Manage Recordings - Admin</title>
  <link rel="stylesheet" href="assets/theme.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
  <style>
    :root {
      --bg: #0b0b0b;
      --surface: #121214;
      --muted: #9aa7c7;
      --accent-orange: #ff9a3c;
      --accent-blue: #1ea7ff;
      --text: #ffffff;
      --card-shadow: 0 8px 30px rgba(0,0,0,0.6);
      --radius: 10px;
    }
    
    body {
      background: var(--bg);
      color: var(--text);
    }
    
    .main {
      margin-left: 250px;
      padding: 2rem;
      min-height: 100vh;
    }
    
    .topbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1rem 0;
      margin-bottom: 2rem;
      border-bottom: 1px solid rgba(255,255,255,0.1);
    }
    
    .topbar-left {
      font-size: 1.5rem;
      font-weight: 600;
      color: var(--accent-orange);
    }
    
    .card {
      background: var(--surface);
      border: none;
      border-radius: var(--radius);
      box-shadow: var(--card-shadow);
      margin-bottom: 2rem;
    }
    
    .card-header {
      background: rgba(0,0,0,0.2);
      border-bottom: 1px solid rgba(255,255,255,0.05);
      padding: 1.25rem 1.5rem;
    }
    
    .card-body {
      padding: 1.5rem;
    }
    
    .table {
      --bs-table-bg: transparent;
      --bs-table-color: var(--text);
      --bs-table-striped-bg: rgba(0,0,0,0.1);
      --bs-table-hover-bg: rgba(255,255,255,0.03);
      margin-bottom: 0;
    }
    
    .form-control, .form-select {
      background: rgba(255,255,255,0.03);
      border: 1px solid rgba(255,255,255,0.1);
      color: var(--text);
    }
    
    .form-control:focus, .form-select:focus {
      background: rgba(255,255,255,0.05);
      border-color: var(--accent-orange);
      box-shadow: 0 0 0 0.25rem rgba(255, 154, 60, 0.25);
      color: var(--text);
    }
    
    .btn-primary {
      background: var(--accent-orange);
      border: none;
    }
    
    .btn-primary:hover {
      background: #e68a00;
    }
    
    .btn-outline-secondary {
      border-color: rgba(255,255,255,0.1);
      color: var(--text);
    }
    
    .btn-outline-secondary:hover {
      background: rgba(255,255,255,0.1);
      border-color: rgba(255,255,255,0.2);
      color: var(--text);
    }
    
    .pagination .page-link {
      background: var(--surface);
      border-color: rgba(255,255,255,0.1);
      color: var(--text);
    }
    
    .pagination .page-item.active .page-link {
      background: var(--accent-orange);
      border-color: var(--accent-orange);
    }
    
    .dropdown-menu {
      background: var(--surface);
      border: 1px solid rgba(255,255,255,0.1);
    }
    
    .dropdown-item {
      color: var(--text);
    }
    
    .dropdown-item:hover {
      background: rgba(255,255,255,0.05);
      color: var(--accent-orange);
    }
    
    .badge {
      font-weight: 500;
      padding: 0.35em 0.65em;
    }
  </style>
  <style>
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: var(--accent-orange);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      margin-right: 12px;
      flex-shrink: 0;
    }
    
    .table th {
      white-space: nowrap;
      padding: 1rem 0.75rem;
    }
    
    .table td {
      vertical-align: middle;
      padding: 1rem 0.75rem;
    }
    
    .badge {
      font-weight: 500;
      padding: 0.35em 0.65em;
      font-size: 0.75em;
    }
    
    .filter-section {
      background: rgba(255,255,255,0.02);
      border-radius: var(--radius);
      padding: 1.5rem;
      margin-bottom: 2rem;
      border: 1px solid rgba(255,255,255,0.03);
    }
    .filter-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 1rem;
      margin-bottom: 1rem;
    }
    .card {
      border: none;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
      margin-bottom: 1.5rem;
    }
    .card-header {
      background: var(--surface);
      border-bottom: 1px solid rgba(0,0,0,0.05);
      padding: 1rem 1.5rem;
    }
    .card-body {
      padding: 1.5rem;
    }
    .table {
      margin-bottom: 0;
    }
    .table th {
      border-top: none;
      font-weight: 600;
      text-transform: uppercase;
      font-size: 0.75rem;
      letter-spacing: 0.5px;
      color: var(--muted);
    }
    .badge {
      font-weight: 500;
      padding: 0.35em 0.65em;
      background-color: var(--accent-orange);
      color: #fff;
    }
    
    .btn-primary {
      background-color: var(--accent-orange);
      border-color: var(--accent-orange);
    }
    
    .btn-primary:hover {
      background-color: #e68a00;
      border-color: #e68a00;
    }
    
    .btn-warning {
      background-color: #ffc107;
      border-color: #ffc107;
      color: #000;
    }
    
    .table {
      color: var(--text);
    }
    
    .table th {
      background-color: var(--surface);
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .table td {
      border-color: rgba(255, 255, 255, 0.05);
      vertical-align: middle;
    }
    
    .form-control, .form-select {
      background-color: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.1);
      color: var(--text);
    }
    
    .form-control:focus, .form-select:focus {
      background-color: rgba(255, 255, 255, 0.1);
      border-color: var(--accent-orange);
      color: var(--text);
      box-shadow: 0 0 0 0.25rem rgba(255, 154, 60, 0.25);
    }
    
    .modal-content {
      background-color: var(--surface);
      color: var(--text);
    }
    
    .modal-header {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .modal-footer {
      border-top: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .close {
      color: var(--text);
      opacity: 0.8;
    }
    .pagination {
      margin-top: 1.5rem;
    }
  </style>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
  <style>
    .filter-section {
      background: rgba(255,255,255,0.02);
      padding: 1.5rem;
      border-radius: var(--radius);
      margin-bottom: 2rem;
      border: 1px solid rgba(255,255,255,0.03);
    }
    .filter-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 1rem;
      margin-bottom: 1rem;
    }
    .filter-actions {
      display: flex;
      gap: 1rem;
      margin-top: 1rem;
    }
    .recordings-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 1.5rem;
      margin-top: 1.5rem;
    }
    .recording-card {
      background: var(--surface);
      border-radius: var(--radius);
      overflow: hidden;
      box-shadow: var(--card-shadow);
      transition: transform 0.2s;
    }
    .recording-card:hover {
      transform: translateY(-2px);
    }
    .recording-audio {
      width: 100%;
      background: rgba(0,0,0,0.05);
      padding: 1rem;
    }
    .recording-details {
      padding: 1rem;
    }
    .recording-meta {
      font-size: 0.85rem;
      color: var(--muted);
      margin-top: 0.5rem;
    }
    .recording-actions {
      display: flex;
      gap: 0.5rem;
      margin-top: 1rem;
      padding-top: 1rem;
      border-top: 1px solid rgba(255,255,255,0.05);
    }
    .badge {
      display: inline-block;
      padding: 0.25rem 0.5rem;
      border-radius: 4px;
      font-size: 0.75rem;
      font-weight: 600;
    }
    .badge-pending { background: #ffc107; color: #000; }
    .badge-approved { background: #28a745; color: #fff; }
    .badge-rejected { background: #dc3545; color: #fff; }
    .pagination {
      display: flex;
      justify-content: center;
      gap: 0.5rem;
      margin-top: 2rem;
    }
    .pagination a, .pagination span {
      display: inline-block;
      padding: 0.5rem 1rem;
      background: var(--surface);
      border-radius: 4px;
      text-decoration: none;
    }
    .pagination .active {
      background: var(--accent-orange);
      color: #fff;
    }
  </style>
</head>
<body class="dashboard-page">
  <?php include 'includes/sidebar.php'; ?>

  <main class="main">
    <header class="topbar">
      <div class="topbar-left">Manage Recordings</div>
      <div class="topbar-right">
        <button class="btn btn-primary" id="bulkActionsBtn">
          <i class="bi bi-download me-1"></i> Bulk Actions
        </button>
      </div>
    </header>

    <section class="content">
      <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
      <?php endif; ?>
      
      <div class="filter-section">
        <h5 class="mb-3"><i class="bi bi-funnel me-2"></i>Filter Recordings</h5>
        <form method="get" class="filter-form">
          <div class="filter-grid">
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Status</label>
              <select name="status" class="form-select form-select-sm">
                <option value="all" <?= $filters['status'] === 'all' ? 'selected' : '' ?>>All Statuses</option>
                <option value="pending" <?= $filters['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
                <option value="approved" <?= $filters['status'] === 'approved' ? 'selected' : '' ?>>Approved</option>
                <option value="rejected" <?= $filters['status'] === 'rejected' ? 'selected' : '' ?>>Rejected</option>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Date From</label>
              <input type="date" name="date_from" class="form-control form-control-sm" value="<?= htmlspecialchars($filters['date_from']) ?>">
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Date To</label>
              <input type="date" name="date_to" class="form-control form-control-sm" value="<?= htmlspecialchars($filters['date_to']) ?>">
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">User</label>
              <select name="user_id" class="form-select form-select-sm">
                <option value="0">All Users</option>
                <?php foreach ($users as $user): ?>
                  <option value="<?= (int)$user['id'] ?>" <?= $filters['user_id'] == $user['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($user['full_name'] . ' (' . ($user['phone'] ?? 'N/A') . ')') ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Task</label>
              <select name="task_id" class="form-select form-select-sm">
                <option value="0">All Tasks</option>
                <?php 
                $currentCategory = '';
                foreach ($tasks as $task): 
                  if ($task['category_id'] !== $currentCategory) {
                    if ($currentCategory !== '') echo '</optgroup>';
                    echo '<optgroup label="' . htmlspecialchars($categories[$task['category_id']]['name']) . '">';
                    $currentCategory = $task['category_id'];
                  }
                ?>
                  <option value="<?= (int)$task['id'] ?>" <?= $filters['task_id'] == $task['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($task['title']) ?>
                  </option>
                <?php endforeach; ?>
                <?php if ($currentCategory !== '') echo '</optgroup>'; ?>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Task Category</label>
              <select name="category_id" class="form-select form-select-sm">
                <option value="">All Categories</option>
                <?php foreach ($categories as $category): ?>
                  <option value="<?= $category['id'] ?>" <?= ($filters['category_id'] ?? '') == $category['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($category['name']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Gender</label>
              <select name="gender" class="form-select form-select-sm">
                <option value="">All Genders</option>
                <?php foreach ($genders as $gender): ?>
                  <option value="<?= htmlspecialchars($gender) ?>" <?= $filters['gender'] === $gender ? 'selected' : '' ?>>
                    <?= ucfirst(htmlspecialchars($gender)) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Ethnicity</label>
              <select name="ethnicity" class="form-select form-select-sm">
                <option value="">All Ethnicities</option>
                <?php foreach ($ethnicities as $ethnicity): ?>
                  <option value="<?= htmlspecialchars($ethnicity) ?>" <?= $filters['ethnicity'] === $ethnicity ? 'selected' : '' ?>>
                    <?= ucfirst(htmlspecialchars($ethnicity)) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label small fw-bold text-muted">Quality Status</label>
              <select name="quality_status" class="form-select form-select-sm">
                <option value="">All Qualities</option>
                <option value="good" <?= $filters['quality_status'] === 'good' ? 'selected' : '' ?>>Good</option>
                <option value="needs_review" <?= $filters['quality_status'] === 'needs_review' ? 'selected' : '' ?>>Needs Review</option>
                <option value="poor" <?= $filters['quality_status'] === 'poor' ? 'selected' : '' ?>>Poor</option>
              </select>
            </div>
          </div>
          
          <div class="d-flex gap-2 mt-3">
            <button type="submit" class="btn btn-sm btn-primary">
              <i class="bi bi-funnel me-1"></i> Apply Filters
            </button>
            <a href="?" class="btn btn-sm btn-outline-secondary">
              <i class="bi bi-arrow-counterclockwise me-1"></i> Reset
            </a>
          </div>
        </form>
      </div>

      <div class="card">
        <div class="card-header">
          <h3>Recordings (<?= number_format($totalRecordings) ?>)</h3>
          <div class="card-actions">
            <div class="dropdown">
              <button class="btn btn-secondary dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-download"></i> Export
              </button>
              <ul class="dropdown-menu" aria-labelledby="exportDropdown">
                <li><a class="dropdown-item" href="#" data-export-format="csv">Export as CSV</a></li>
                <li><a class="dropdown-item" href="#" data-export-format="excel">Export as Excel</a></li>
                <li><a class="dropdown-item" href="#" data-export-format="json">Export as JSON</a></li>
              </ul>
            </div>
          </div>
        </div>
        
        <div class="card-body">
          <?php if (empty($recordings)): ?>
            <div class="alert alert-info">No recordings found matching your criteria.</div>
          <?php else: ?>
            <form method="post" id="recordingsForm">
              <div class="table-responsive">
                <table class="table">
                  <thead>
                    <tr>
                      <th width="40">
                        <input type="checkbox" id="selectAll">
                      </th>
                      <th>User</th>
                      <th>Task & Category</th>
                      <th>Recording</th>
                      <th>Details</th>
                      <th>Status</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach ($recordings as $recording): ?>
                      <tr>
                        <td>
                          <input type="checkbox" name="selected_recordings[]" value="<?= $recording['id'] ?>">
                        </td>
                        <td>
                          <div class="d-flex align-items-center">
                            <div class="avatar">
                              <?= strtoupper(substr($recording['full_name'] ?? 'U', 0, 1)) ?>
                            </div>
                            <div class="ms-3">
                              <div class="fw-bold"><?= htmlspecialchars($recording['full_name'] ?? 'Unknown User') ?></div>
                              <div class="text-muted small"><?= htmlspecialchars($recording['phone'] ?? 'N/A') ?></div>
                              <div class="text-muted small">
                                <?= $recording['created_at'] ? date('M j, Y g:i A', strtotime($recording['created_at'])) : 'N/A' ?>
                              </div>
                            </div>
                          </div>
                        </td>
                        <td>
                          <?php if (!empty($recording['task_title'])): ?>
    <div class="fw-bold"><?= htmlspecialchars($recording['task_title']) ?></div>
<?php endif; ?>
                          <?php if (!empty($recording['task_instruction'])): ?>
                            <div class="mt-2" style="font-size: 1.1rem; line-height: 1.6; color: #e9ecef;">
                                <?= nl2br(htmlspecialchars($recording['task_instruction'])) ?>
                            </div>
                          <?php endif; ?>
                          <?php if (!empty($recording['category_name'])): ?>
                            <div class="mt-1">
                                <span class="badge" style="background-color: <?= getCategoryColor($recording['category_id'] ?? 0) ?>">
                                    <?= htmlspecialchars($recording['category_name']) ?>
                                </span>
                            </div>
                          <?php endif; ?>
                        </td>
                        <td>
                          <?php 
                          // Try different path combinations to find the audio file
                          $audioPath = '';
                          $possiblePaths = [];
                          
                          // Add possible path combinations to check
                          if (!empty($recording['filename'])) {
                              // Try with just filename (relative to uploads)
                              $possiblePaths[] = '../' . ltrim($recording['filename'], '/');
                              // Try with full file_path if available
                              if (!empty($recording['file_path'])) {
                                  $possiblePaths[] = '../' . ltrim($recording['file_path'], '/');
                              }
                              // Try with just the basename in case of path issues
                              $possiblePaths[] = '../uploads/recordings/' . $recording['user_id'] . '/' . basename($recording['filename']);
                          }
                          
                          // Find the first valid path
                          foreach ($possiblePaths as $path) {
                              if (file_exists($path)) {
                                  $audioPath = $path;
                                  break;
                              }
                          }
                          
                          if (!empty($audioPath)): 
                          ?>
                            <audio controls class="w-100" style="max-width: 250px;">
                              <source src="<?= htmlspecialchars($audioPath) ?>" type="audio/wav">
                              Your browser does not support the audio element.
                            </audio>
                            <div class="small text-muted mt-1">
                              <?= htmlspecialchars($audioPath) ?>
                            </div>
                            <div class="small text-muted mt-1">
                              <?php 
                              $size = $recording['size_bytes'] ?? 0;
                              $duration = $recording['duration'] ?? 0;
                              $formattedSize = $size > 0 ? number_format($size / 1024, 1) . ' KB' : 'N/A';
                              $formattedDuration = $duration > 0 ? number_format($duration, 1) . 's' : 'N/A';
                              echo "{$formattedDuration} • {$formattedSize}";
                              ?>
                            </div>
                          <?php else: ?>
                            <div class="text-danger small">
                              Audio file not found. Tried paths:
                              <ul class="mt-1 mb-0">
                                <?php foreach ($possiblePaths as $path): ?>
                                  <li><?= htmlspecialchars($path) ?></li>
                                <?php endforeach; ?>
                              </ul>
                              <div class="mt-1">
                                <strong>Debug Info:</strong><br>
                                User ID: <?= $recording['user_id'] ?><br>
                                Filename: <?= htmlspecialchars($recording['filename'] ?? 'Not set') ?><br>
                                File Path: <?= htmlspecialchars($recording['file_path'] ?? 'Not set') ?>
                              </div>
                            </div>
                          <?php endif; ?>
                        </td>
                        <td>
                          <div class="small">
                            <div>Sample Rate: <?= $recording['sample_rate'] ?? 'N/A' ?> Hz</div>
                            <div>Channels: <?= $recording['channels'] ?? 'N/A' ?></div>
                            <?php if (!empty($recording['reviewed_at'])): ?>
                              <div class="mt-2">
                                <div>Reviewed: <?= date('M j, Y g:i A', strtotime($recording['reviewed_at'])) ?></div>
                                <?php if (!empty($recording['reviewer_id'])): ?>
                                  <div>By: Admin #<?= $recording['reviewer_id'] ?></div>
                                <?php endif; ?>
                              </div>
                            <?php endif; ?>
                          </div>
                        </td>
                        <td>
                          <?php 
                          $statusClass = [
                            'pending' => 'bg-warning',
                            'approved' => 'bg-success',
                            'rejected' => 'bg-danger'
                          ][$recording['status'] ?? 'pending'] ?? 'bg-secondary';
                          ?>
                          <span class="badge <?= $statusClass ?> mb-2">
                            <?= ucfirst($recording['status'] ?? 'unknown') ?>
                          </span>
                        </td>
                        <td>
                          <div class="btn-group">
                            <a href="#" class="btn btn-sm btn-outline-primary" title="Download">
                              <i class="fas fa-download"></i>
                            </a>
                            <a href="#" class="btn btn-sm btn-outline-success" title="Approve">
                              <i class="fas fa-check"></i>
                            </a>
                            <a href="#" class="btn btn-sm btn-outline-danger" title="Reject">
                              <i class="fas fa-times"></i>
                            </a>
                            <a href="#" class="btn btn-sm btn-outline-info" title="View Details">
                              <i class="fas fa-eye"></i>
                            </a>
                          </div>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
              
              <div class="d-flex justify-content-between align-items-center mt-3">
                <div class="bulk-actions d-none">
                  <select name="action" class="form-control form-control-sm d-inline-block w-auto me-2">
                    <option value="">With Selected:</option>
                    <option value="approve">Approve</option>
                    <option value="reject">Reject</option>
                    <option value="download">Download</option>
                    <option value="delete">Delete</option>
                  </select>
                  <button type="submit" class="btn btn-sm btn-primary">Apply</button>
                </div>
                
                <?php if ($totalPages > 1): ?>
                  <nav>
                    <ul class="pagination mb-0">
                      <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                          <a class="page-link" href="?<?= http_build_query(array_merge($filters, ['page' => $i])) ?>">
                            <?= $i ?>
                          </a>
                        </li>
                      <?php endfor; ?>
                    </ul>
                  </nav>
                <?php endif; ?>
              </div>
            </form>
          <?php endif; ?>
        </div>
      </div>
    </section>
  </main>

  <!-- Bulk Actions Modal -->
  <div class="modal fade" id="bulkActionsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Bulk Actions</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <p>Select an action to perform on the selected recordings:</p>
          <div class="d-grid gap-2">
            <button type="button" class="btn btn-success" data-action="approve">
              <i class="fas fa-check me-2"></i> Approve Selected
            </button>
            <button type="button" class="btn btn-warning" data-action="reject">
              <i class="fas fa-times me-2"></i> Reject Selected
            </button>
            <button type="button" class="btn btn-primary" data-action="download">
              <i class="fas fa-download me-2"></i> Download Selected
            </button>
            <button type="button" class="btn btn-danger" data-action="delete">
              <i class="fas fa-trash me-2"></i> Delete Selected
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- JavaScript Libraries -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script>
    // Initialize date pickers
    document.addEventListener('DOMContentLoaded', function() {
      flatpickr('input[type="date"]', {
        dateFormat: 'Y-m-d',
        allowInput: true
      });
      
      // Initialize tooltips
      var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
      var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
      });
      
      // Handle form submission with loading state
      const filterForm = document.querySelector('.filter-form');
      if (filterForm) {
        filterForm.addEventListener('submit', function() {
          const submitBtn = this.querySelector('button[type="submit"]');
          if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span> Applying...';
          }
        });
      }

    // Toggle checkboxes
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
      selectAllCheckbox.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('input[name="selected_recordings[]"]');
        checkboxes.forEach(checkbox => {
          checkbox.checked = this.checked;
        });
        toggleBulkActions();
      });
    }

    // Toggle bulk actions when checkboxes change
    const checkboxes = document.querySelectorAll('input[name="selected_recordings[]"]');
    checkboxes.forEach(checkbox => {
      checkbox.addEventListener('change', toggleBulkActions);
    });

    function toggleBulkActions() {
      const checkboxes = document.querySelectorAll('input[name="selected_recordings[]"]:checked');
      const bulkActionsBtn = document.getElementById('bulkActionsBtn');
      if (bulkActionsBtn) {
        if (checkboxes.length > 0) {
          bulkActionsBtn.classList.remove('btn-primary');
          bulkActionsBtn.classList.add('btn-warning');
          bulkActionsBtn.innerHTML = `<i class="bi bi-check-circle me-2"></i> ${checkboxes.length} Selected`;
        } else {
          bulkActionsBtn.classList.remove('btn-warning');
          bulkActionsBtn.classList.add('btn-primary');
          bulkActionsBtn.innerHTML = '<i class="bi bi-download me-2"></i> Bulk Actions';
        }
      }
    }

    // Initialize bulk actions modal
    const bulkActionsModal = new bootstrap.Modal(document.getElementById('bulkActionsModal'));
    const bulkActionsBtn = document.getElementById('bulkActionsBtn');
    if (bulkActionsBtn) {
      bulkActionsBtn.addEventListener('click', function(e) {
        e.preventDefault();
        bulkActionsModal.show();
      });
    }

    // Handle bulk action form submission
    const bulkActionForm = document.getElementById('bulkActionForm');
    if (bulkActionForm) {
      bulkActionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const action = document.querySelector('input[name="bulk_action"]:checked');
    // Handle bulk action buttons in modal
    document.querySelectorAll('[data-action]').forEach(button => {
      button.addEventListener('click', function() {
        const action = this.getAttribute('data-action');
        const form = document.getElementById('recordingsForm');
        if (form) {
          const actionInput = form.querySelector('[name="action"]');
          if (actionInput) {
            actionInput.value = action;
            
            // If no checkboxes are checked, check them all
            if (document.querySelectorAll('input[name="selected_recordings[]"]:checked').length === 0) {
              const checkboxes = document.querySelectorAll('input[name="selected_recordings[]"]');
              checkboxes.forEach(checkbox => {
                checkbox.checked = true;
              });
            }
            
            form.submit();
          }
        }
      });
    });
  });
</script>
</body>
</html>
