<?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 = 200; // Increased from 20 to 200 for bulk operations
$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 metadata export
if (isset($_GET['export']) && $_GET['export'] === 'metadata') {
    // Set headers for CSV download
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=recordings_metadata_' . date('Y-m-d_His') . '.csv');
    
    // Create output stream
    $output = fopen('php://output', 'w');
    
    // Add CSV headers
    $headers = [
        'file_name',
        'file_path',
        'category_name',
        'task_title',
        'task_instruction',
        'user_full_name',
        'user_phone',
        'user_gender',
        'user_ethnicity',
        'age_range',
        'duration_seconds',
        'sample_rate_hz',
        'channels',
        'file_size_bytes',
        'status',
        'quality_status',
        'created_at',
        'reviewed_at'
    ];
    fputcsv($output, $headers);
    
    // Get all recordings with the same filters applied
    $exportQuery = str_replace(
        "ORDER BY r.created_at DESC LIMIT :per_page OFFSET :offset",
        "ORDER BY r.created_at DESC",
        $query
    );
    
    $exportStmt = $pdo->prepare($exportQuery);
    
    // Bind all parameters except pagination
    foreach ($params as $key => $value) {
        if ($key !== ':per_page' && $key !== ':offset') {
            $exportStmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
        }
    }
    
    $exportStmt->execute();
    $recordings = $exportStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Add data rows
    foreach ($recordings as $recording) {
        $row = [
            $recording['filename'] ?? '',
            $recording['file_path'] ?? '',
            $recording['category_name'] ?? '',
            $recording['task_title'] ?? '',
            str_replace(["\r\n", "\r", "\n"], ' ', $recording['task_instruction'] ?? ''),
            $recording['full_name'] ?? '',
            $recording['phone'] ?? '',
            $recording['gender'] ?? '',
            $recording['ethnicity'] ?? '',
            $recording['age_range'] ?? '',
            $recording['duration'] ?? '',
            $recording['sample_rate'] ?? '',
            $recording['channels'] ?? '',
            $recording['size_bytes'] ?? '',
            $recording['status'] ?? '',
            $recording['quality_status'] ?? '',
            $recording['created_at'] ?? '',
            $recording['reviewed_at'] ?? ''
        ];
        fputcsv($output, $row);
    }
    
    fclose($output);
    exit;
}

// 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':
                // Log the download attempt
                error_log('Bulk download started for IDs: ' . implode(',', $ids));
                
                // Ensure we have the ZipArchive class
                if (!class_exists('ZipArchive')) {
                    error_log('ZipArchive class not found');
                    header('HTTP/1.1 500 Internal Server Error');
                    echo 'Server error: ZipArchive extension not available';
                    exit;
                }
                
                // Create a temporary directory in the project's temp folder
                $tempBaseDir = dirname(__DIR__) . '/temp';
                
                // Create the temp directory if it doesn't exist
                if (!file_exists($tempBaseDir)) {
                    if (!@mkdir($tempBaseDir, 0777, true)) {
                        $error = error_get_last();
                        error_log('Failed to create temp base directory: ' . ($error['message'] ?? 'Unknown error'));
                        header('HTTP/1.1 500 Internal Server Error');
                        echo 'Failed to create temporary directory. Please ensure the web server has write permissions to the /vonaida/temp directory.';
                        exit;
                    }
                    // Ensure the directory is writable
                    chmod($tempBaseDir, 0777);
                }
                
                // Create a unique subdirectory for this export
                $tempDir = $tempBaseDir . '/export_' . uniqid();
                if (!@mkdir($tempDir, 0777, true)) {
                    $error = error_get_last();
                    error_log('Failed to create temp directory: ' . ($error['message'] ?? 'Unknown error'));
                    header('HTTP/1.1 500 Internal Server Error');
                    echo 'Failed to create export directory. Please check server logs for details.';
                    exit;
                }
                
                $zip = new ZipArchive();
                $zipname = 'recordings_' . date('Y-m-d_His') . '.zip';
                $zipfile = $tempDir . '/' . $zipname;
                
                // Create the zip file
                if ($zip->open($zipfile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                    // Create audio directory in the zip
                    $zip->addEmptyDir('audio');
                    
                    // Get all recordings data for metadata
                    $placeholders = implode(',', array_fill(0, count($ids), '?'));
                    $stmt = $pdo->prepare("
                        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
                        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 r.id IN ($placeholders)
                    ");
                    $stmt->execute($ids);
                    $recordings = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    // Add audio files to zip and prepare metadata
                    $metadata = [];
                    $metadata[] = [
                        'file_name', 'file_path', 'category_name', 'task_title', 'task_instruction',
                        'user_full_name', 'user_phone', 'user_gender', 'user_ethnicity', 'age_range',
                        'duration_seconds', 'sample_rate_hz', 'channels', 'file_size_bytes',
                        'status', 'quality_status', 'created_at', 'reviewed_at'
                    ];
                    
                    foreach ($recordings as $recording) {
                        $audioPath = '';
                        $possiblePaths = [];
                        
                        // Try different path combinations to find the audio file (matching the single download logic)
                        if (!empty($recording['filename'])) {
                            // Try with just filename (relative to uploads)
                            $possiblePaths[] = __DIR__ . '/../' . ltrim($recording['filename'], '/');
                            // Try with full file_path if available
                            if (!empty($recording['file_path'])) {
                                $possiblePaths[] = __DIR__ . '/../' . ltrim($recording['file_path'], '/');
                            }
                            // Try with user-specific path
                            if (!empty($recording['user_id'])) {
                                $possiblePaths[] = __DIR__ . '/../uploads/recordings/' . $recording['user_id'] . '/' . basename($recording['filename']);
                            }
                        }
                        
                        // Find the first valid path
                        foreach ($possiblePaths as $path) {
                            if (file_exists($path) && is_readable($path)) {
                                $audioPath = $path;
                                break;
                            }
                        }
                        
                        if (!empty($audioPath)) {
                            $filename = 'recording-' . $recording['id'] . '.wav';
                            $localPath = 'audio/' . $filename;
                            
                            if ($zip->addFile($audioPath, $localPath)) {
                                // Get file size if not already set
                                $fileSize = $recording['size_bytes'] ?? @filesize($audioPath);
                                
                                // Add to metadata
                                $metadata[] = [
                                    $filename,
                                    $audioPath,
                                    $recording['category_name'] ?? '',
                                    $recording['task_title'] ?? '',
                                    str_replace(["\r\n", "\r", "\n"], ' ', $recording['task_instruction'] ?? ''),
                                    $recording['full_name'] ?? '',
                                    $recording['phone'] ?? '',
                                    $recording['gender'] ?? '',
                                    $recording['ethnicity'] ?? '',
                                    $recording['age_range'] ?? '',
                                    $recording['duration'] ?? '',
                                    $recording['sample_rate'] ?? '',
                                    $recording['channels'] ?? '',
                                    $fileSize,
                                    $recording['status'] ?? '',
                                    $recording['quality_status'] ?? '',
                                    $recording['created_at'] ?? '',
                                    $recording['reviewed_at'] ?? ''
                                ];
                            } else {
                                error_log("Failed to add file to zip: $audioPath");
                                // Add a placeholder for failed files
                                $missingContent = "Failed to add file to zip: " . basename($audioPath);
                                $zip->addFromString('audio/error_' . $recording['id'] . '.txt', $missingContent);
                            }
                        } else {
                            // Add a placeholder for missing files
                            $missingContent = "File not found for recording ID: " . $recording['id'] . "\n";
                            $missingContent .= "Tried paths:\n" . implode("\n", array_map('htmlspecialchars', $possiblePaths));
                            $zip->addFromString('audio/missing_' . $recording['id'] . '.txt', $missingContent);
                        }
                    }
                    
                    // Create and add metadata.csv to zip
                    $metadataFile = $tempDir . '/metadata.csv';
                    $fp = fopen($metadataFile, 'w');
                    if ($fp === false) {
                        error_log("Failed to create metadata file: $metadataFile");
                    } else {
                        foreach ($metadata as $fields) {
                            fputcsv($fp, $fields);
                        }
                        fclose($fp);
                        
                        if (!file_exists($metadataFile)) {
                            error_log("Metadata file was not created: $metadataFile");
                        } elseif (!$zip->addFile($metadataFile, 'metadata.csv')) {
                            error_log("Failed to add metadata.csv to zip");
                        }
                    }
                    
                    // Add a README file
                    $readme = "Recordings Dataset\n\n";
                    $readme .= "This archive contains:\n";
                    $readme .= "- audio/: Directory containing all audio recordings\n";
                    $readme .= "- metadata.csv: CSV file with metadata for all recordings\n\n";
                    $readme .= "Generated on: " . date('Y-m-d H:i:s');
                    $zip->addFromString('README.txt', $readme);
                    
                    // Close the zip file
                    if (!$zip->close()) {
                        error_log("Failed to close zip file: " . $zip->getStatusString());
                        header('HTTP/1.1 500 Internal Server Error');
                        echo 'Failed to finalize zip file. Check server logs for details.';
                        exit;
                    }
                    
                    // Verify the zip file was created and has content
                    if (!file_exists($zipfile)) {
                        error_log("Zip file was not created: $zipfile");
                        header('HTTP/1.1 500 Internal Server Error');
                        echo 'Failed to create zip file. Check server logs for details.';
                        exit;
                    }
                    
                    $filesize = filesize($zipfile);
                    if ($filesize === 0) {
                        error_log("Created empty zip file: $zipfile");
                        header('HTTP/1.1 500 Internal Server Error');
                        echo 'Created an empty zip file. No files were added.';
                        unlink($zipfile);
                        exit;
                    }
                    
                    // Set headers for file download
                    header('Content-Type: application/zip');
                    header('Content-Disposition: attachment; filename="' . $zipname . '"');
                    header('Content-Length: ' . $filesize);
                    header('Content-Transfer-Encoding: binary');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    
                    // Clean all output buffers
                    while (ob_get_level()) {
                        ob_end_clean();
                    }
                    
                    // Stream the file to the browser
                    readfile($zipfile);
                    
                    // Clean up
                    unlink($zipfile);
                    rmdir($tempDir);
                    exit;
                }
                break;
        }
    }
    
    // Redirect to avoid form resubmission if we get here
    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>
    /* Style for disabled download button */
    .btn[disabled] {
      opacity: 0.6;
      cursor: not-allowed;
      pointer-events: none;
    }
    
    .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-x-circle me-1"></i> Reset
            </a>
            <button type="button" id="exportMetadataBtn" class="btn btn-sm btn-success ms-auto">
              <i class="bi bi-download me-1"></i> Export Metadata (CSV)
            </button>
          </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="bi bi-download me-1"></i> Export
              </button>
              <ul class="dropdown-menu" aria-labelledby="exportDropdown">
                <li><a class="dropdown-item" href="#" data-action="download"><i class="bi bi-file-earmark-arrow-down me-2"></i>Download Selected (ZIP + CSV)</a></li>
                <li><a class="dropdown-item" href="?export=metadata" id="exportMetadataLink"><i class="bi bi-file-earmark-spreadsheet me-2"></i>Export All Metadata (CSV)</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="pagination-info">
                              <?php if ($totalRecordings > 0): ?>
                                Showing <?= $offset + 1 ?> to <?= min($offset + 200, $totalRecordings) ?> of <?= number_format($totalRecordings) ?> entries
                                <div class="small text-muted mt-1">Showing up to 200 records per page for bulk operations</div>
                              <?php else: ?>
                                No records found
                              <?php endif; ?>
                            </div>
                            <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>
                        </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="d-flex flex-column gap-2">
                            <!-- Download Button -->
                            <a href="<?= !empty($audioPath) ? htmlspecialchars($audioPath) : '#' ?>" 
                               class="btn btn-sm btn-outline-primary d-flex align-items-center justify-content-start px-3 py-1" 
                               title="Download Recording"
                               download="recording-<?= $recording['id'] ?>.wav"
                               <?= empty($audioPath) ? 'disabled' : '' ?>>
                              <i class="fas fa-download me-2"></i>
                              <span>Download</span>
                            </a>
                            
                            <!-- Approve Button -->
                            <button type="button" 
                                    class="btn btn-sm btn-outline-success d-flex align-items-center justify-content-start px-3 py-1" 
                                    title="Approve Recording"
                                    onclick="updateStatus(<?= $recording['id'] ?>, 'approved')">
                              <i class="fas fa-check me-2"></i>
                              <span>Approve</span>
                            </button>
                            
                            <!-- Reject Button -->
                            <button type="button" 
                                    class="btn btn-sm btn-outline-danger d-flex align-items-center justify-content-start px-3 py-1" 
                                    title="Reject Recording"
                                    onclick="updateStatus(<?= $recording['id'] ?>, 'rejected')">
                              <i class="fas fa-times me-2"></i>
                              <span>Reject</span>
                            </button>
                            
                            <!-- View Details Button -->
                            <button type="button" 
                                    class="btn btn-sm btn-outline-info d-flex align-items-center justify-content-start px-3 py-1" 
                                    title="View Details"
                                    onclick="showDetails(<?= htmlspecialchars(json_encode($recording)) ?>)">
                              <i class="fas fa-eye me-2"></i>
                              <span>Details</span>
                            </button>
                          </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() {
      // Handle metadata export link click
    document.addEventListener('click', function(e) {
      const exportLink = e.target.closest('#exportMetadataLink');
      if (!exportLink) return;
      
      e.preventDefault();
      console.log('Export button clicked');
      
      // Show loading state
      const originalText = exportLink.innerHTML;
      exportLink.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Preparing export...';
      
      // Get the export URL
      const exportUrl = exportLink.getAttribute('href');
      console.log('Export URL:', exportUrl);
      
      // Create a hidden iframe for the download
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
      
      // Set a timeout to handle any potential issues
      const timeout = setTimeout(() => {
        console.log('Export timed out');
        exportLink.innerHTML = originalText;
        document.body.removeChild(iframe);
        Swal.fire({
          icon: 'error',
          title: 'Export Timed Out',
          text: 'The export is taking longer than expected. Please try again.',
          confirmButtonText: 'OK'
        });
      }, 30000); // 30 second timeout
      
      // Handle when the iframe loads
      iframe.onload = function() {
        clearTimeout(timeout);
        console.log('Export iframe loaded');
        
        // Check for errors in the response
        try {
          const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
          const responseText = iframeDoc.body.innerText;
          
          if (responseText.includes('error') || responseText.includes('Exception')) {
            console.error('Export error:', responseText);
            Swal.fire({
              icon: 'error',
              title: 'Export Failed',
              text: 'An error occurred while generating the export. Please check the console for details.',
              confirmButtonText: 'OK'
            });
          }
        } catch (e) {
          console.log('Export completed, response not accessible due to CORS');
        }
        
        // Clean up
        setTimeout(() => {
          document.body.removeChild(iframe);
          exportLink.innerHTML = originalText;
        }, 1000);
      };
      
      // Start the download
      console.log('Starting download...');
      iframe.src = exportUrl;
    });
      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 to toggle bulk actions visibility
    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';
        }
      }
    }

    // Update recording status
    async function updateStatus(recordingId, status) {
      try {
        const response = await fetch('update_recording_status.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            recording_id: recordingId,
            status: status
          })
        });

        const result = await response.json();

        if (result.success) {
          // Show success message
          Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: `Recording ${status} successfully`,
            timer: 2000,
            showConfirmButton: false
          });
          
          // Reload the page after a short delay
          setTimeout(() => {
            window.location.reload();
          }, 1000);
        } else {
          throw new Error(result.message || 'Failed to update status');
        }
      } catch (error) {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: error.message || 'An error occurred while updating the recording status',
          confirmButtonText: 'OK'
        });
      }
    }

    // Show recording details in a modal
    function showDetails(recording) {
      // Format the details into a readable format
      const details = `
        <div class="mb-3">
          <h6 class="fw-bold mb-2">Recording Details</h6>
          <div class="d-flex flex-column gap-2">
            <div><strong>ID:</strong> ${recording.id}</div>
            <div><strong>User:</strong> ${recording.full_name || 'Unknown'} (ID: ${recording.user_id})</div>
            <div><strong>Task:</strong> ${recording.task_title || 'N/A'}</div>
            <div><strong>Status:</strong> <span class="badge bg-${getStatusBadgeClass(recording.status)}">${recording.status || 'unknown'}</span></div>
            <div><strong>Created:</strong> ${formatDate(recording.created_at)}</div>
            ${recording.reviewed_at ? `<div><strong>Reviewed:</strong> ${formatDate(recording.reviewed_at)}</div>` : ''}
            <div><strong>Duration:</strong> ${recording.duration ? recording.duration + 's' : 'N/A'}</div>
            <div><strong>File Size:</strong> ${formatFileSize(recording.size_bytes)}</div>
            <div><strong>Sample Rate:</strong> ${recording.sample_rate || 'N/A'} Hz</div>
            <div><strong>Channels:</strong> ${recording.channels || 'N/A'}</div>
          </div>
        </div>
      `;

      Swal.fire({
        title: 'Recording Information',
        html: details,
        confirmButtonText: 'Close',
        width: '600px'
      });
    }

    // Helper function to get badge class based on status
    function getStatusBadgeClass(status) {
      const statusClasses = {
        'approved': 'success',
        'rejected': 'danger',
        'pending': 'warning'
      };
      return statusClasses[status] || 'secondary';
    }

    // Helper function to format dates
    function formatDate(dateString) {
      if (!dateString) return 'N/A';
      const date = new Date(dateString);
      return date.toLocaleString();
    }

    // Helper function to format file size
    function formatFileSize(bytes) {
      if (!bytes) return 'N/A';
      if (bytes < 1024) return bytes + ' B';
      if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
      return (bytes / 1048576).toFixed(1) + ' MB';
    }

    // Handle bulk actions
    document.addEventListener('click', async function(e) {
      const actionElement = e.target.closest('[data-action]');
      if (!actionElement) return;
      
      const action = actionElement.getAttribute('data-action');
      const selectedIds = Array.from(document.querySelectorAll('input[name="selected_recordings[]"]:checked'))
        .map(checkbox => checkbox.value);
      
      if (selectedIds.length === 0) {
        Swal.fire({
          icon: 'warning',
          title: 'No Recordings Selected',
          text: 'Please select at least one recording to perform this action.',
          confirmButtonText: 'OK'
        });
        return;
      }

      if (action === 'delete') {
        // Handle delete confirmation
        Swal.fire({
          title: 'Confirm Deletion',
          text: `Are you sure you want to delete ${selectedIds.length} selected recording(s)? This action cannot be undone.`,
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Yes, delete them!',
          cancelButtonText: 'Cancel',
          confirmButtonColor: '#dc3545',
          reverseButtons: true
        }).then((result) => {
          if (result.isConfirmed) {
            submitBulkAction(action, selectedIds);
          }
        });
      } else if (action === 'download') {
        // Show loading state
        const originalButtonHTML = actionElement.innerHTML;
        actionElement.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Preparing download...';
        actionElement.disabled = true;
        
        try {
          // First, check if the server can process the request
          const response = await fetch('recordings.php', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=download&selected_recordings[]=${selectedIds.join('&selected_recordings[]=')}`
          });
          
          if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`Server returned ${response.status}: ${errorText}`);
          }
          
          // If we get here, the server should have sent a file download
          const blob = await response.blob();
          
          if (blob.size === 0) {
            throw new Error('Received empty response from server');
          }
          
          // Create download link and trigger it
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = `recordings_${new Date().toISOString().slice(0, 10)}.zip`;
          document.body.appendChild(a);
          a.click();
          
          // Clean up
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
          
        } catch (error) {
          console.error('Download error:', error);
          Swal.fire({
            icon: 'error',
            title: 'Download Failed',
            html: `Could not download the files. Please try again.<br><br>
                  <small>Error: ${error.message}</small>`,
            confirmButtonText: 'OK',
            allowOutsideClick: false
          });
        } finally {
          // Restore button state
          actionElement.innerHTML = originalButtonHTML;
          actionElement.disabled = false;
        }
      } else {
        submitBulkAction(action, selectedIds);
      }
    });

    // Submit bulk action to server
    async function submitBulkAction(action, ids) {
      try {
        const response = await fetch('bulk_actions.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            action: action,
            ids: ids
          })
        });

        const result = await response.json();

        if (result.success) {
          Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: result.message || 'Action completed successfully',
            timer: 2000,
            showConfirmButton: false
          });
          
          // Reload the page after a short delay
          setTimeout(() => {
            window.location.reload();
          }, 1000);
        } else {
          throw new Error(result.message || 'Failed to complete the action');
        }
      } catch (error) {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: error.message || 'An error occurred while processing your request',
          confirmButtonText: 'OK'
        });
      }
    }

    // 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');
        if (action) {
          const form = document.getElementById('recordingsForm');
          if (form) {
            const actionInput = form.querySelector('[name="action"]');
            if (actionInput) {
              actionInput.value = action.value;
              form.submit();
            }
          }
        }
      });
    }
    
    // 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>
