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

$pageTitle = "Bulk Task Upload";
$successMessage = '';
$errorMessage = '';

// Create uploads directory if it doesn't exist
$uploadDir = __DIR__ . '/../uploads/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    try {
        // Check for upload errors
        if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload failed with error code: ' . $_FILES['csv_file']['error']);
        }

        // Check file type
        $fileType = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));
        if ($fileType !== 'csv') {
            throw new Exception('Only CSV files are allowed.');
        }

        // Process audio files
        $audioFiles = [];
        if (!empty($_FILES['audio_files'])) {
            foreach ($_FILES['audio_files']['name'] as $key => $name) {
                if ($_FILES['audio_files']['error'][$key] === UPLOAD_ERR_OK) {
                    $audioFiles[$name] = [
                        'name' => $name,
                        'tmp_name' => $_FILES['audio_files']['tmp_name'][$key]
                    ];
                }
            }
        }
        
        // Ensure uploads directory exists
        if (!file_exists($uploadDir)) {
            if (!mkdir($uploadDir, 0755, true)) {
                throw new Exception('Failed to create uploads directory');
            }
        }

        // Open the uploaded file
        $file = fopen($_FILES['csv_file']['tmp_name'], 'r');
        if ($file === false) {
            throw new Exception('Failed to open uploaded file.');
        }

        // Read and process the CSV file
        $header = fgetcsv($file); // Read header row
        $requiredColumns = ['category_id', 'instruction', 'instruction_text'];
        $optionalColumns = ['tips_text', 'status', 'sort_order', 'is_mini_task', 'sample_audio_url'];
        
        // Convert header to lowercase for case-insensitive comparison
        $header = array_map('strtolower', $header);
        
        // Validate CSV header
        foreach ($requiredColumns as $column) {
            if (!in_array($column, $header)) {
                throw new Exception("Missing required column: $column");
            }
        }

        $pdo->beginTransaction();
        $importedCount = 0;
        $rowNumber = 1; // Start from 1 to account for header row

        // Prepare the insert statement
        $sql = "INSERT INTO tasks (
            category_id,
            instruction,
            instruction_text,
            tips_text,
            is_mini_task,
            status,
            sort_order,
            sample_audio_url,
            created_at
        ) VALUES (
            :category_id,
            :instruction_text,
            :instruction_text,
            :tips_text,
            :is_mini_task,
            :status,
            :sort_order,
            :sample_audio_url,
            NOW()
        )";

        $stmt = $pdo->prepare($sql);

        // Process each row
        while (($data = fgetcsv($file)) !== false) {
            $rowNumber++;
            
            // Skip empty rows
            if (count(array_filter($data)) === 0) {
                continue;
            }

            // Combine header with row data (case-insensitive)
            $row = array_combine(array_map('strtolower', $header), $data);
            
            // Validate required fields
            foreach ($requiredColumns as $column) {
                $columnLower = strtolower($column);
                if (empty($row[$columnLower])) {
                    throw new Exception("Missing value for required column '$column' on row $rowNumber");
                }
            }

            // Set default values for optional fields
            $taskData = [
                ':category_id' => $row['category_id'],
                ':instruction' => $row['instruction'],
                ':instruction_text' => $row['instruction_text'],
                ':tips_text' => $row['tips_text'] ?? '',
                ':is_mini_task' => isset($row['is_mini_task']) ? (int)$row['is_mini_task'] : 1,
                ':status' => $row['status'] ?? 'active',
                ':sort_order' => $row['sort_order'] ?? 0,
                ':sample_audio_url' => ''
            ];
            
            // Handle audio file if provided
            if (!empty($row['sample_audio_url'])) {
                $audioFileName = basename($row['sample_audio_url']);
                
                // Check if the file was uploaded
                if (isset($audioFiles[$audioFileName])) {
                    $audioFile = $audioFiles[$audioFileName];
                    $targetFile = $uploadDir . $audioFileName;
                    
                    if (move_uploaded_file($audioFile['tmp_name'], $targetFile)) {
                        $taskData[':sample_audio_url'] = 'uploads/' . $audioFileName;
                    } else {
                        throw new Exception("Failed to move uploaded audio file: " . $audioFileName);
                    }
                } else {
                    // If file wasn't uploaded but has a value, use it as-is (in case it's a URL)
                    $taskData[':sample_audio_url'] = $row['sample_audio_url'];
                }
            }

            // Insert into database
            $stmt->execute($taskData);

            $importedCount++;
        }

        $pdo->commit();
        fclose($file);
        
        $successMessage = "Successfully imported $importedCount tasks.";
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $errorMessage = 'Error: ' . $e->getMessage();
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title><?= htmlspecialchars($pageTitle) ?> - Admin</title>
  <link rel="stylesheet" href="assets/theme.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    body {
      background-color: #1a1a1a;
      color: #e9ecef;
    }
    /* Dark mode styles */
    body.dark-mode .upload-area {
      border-color: #4a4a4a;
      background-color: #2d2d2d;
    }
    
    body.dark-mode .upload-area:hover, 
    body.dark-mode .upload-area.dragover {
      border-color: #3a7bd5;
      background-color: rgba(58, 123, 213, 0.1);
    }
    
    body.dark-mode .upload-area h4,
    body.dark-mode .upload-area .text-muted,
    body.dark-mode .upload-area .file-info,
    body.dark-mode .upload-area .form-control,
    body.dark-mode .upload-area .form-label {
      color: #e0e0e0 !important;
    }
    
    /* Base styles */
    .upload-area {
      border: 2px dashed #6c757d;
      border-radius: 8px;
      padding: 2rem;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
      margin-bottom: 1rem;
      color: #212529;
    }
    
    .upload-area:hover, .upload-area.dragover {
      border-color: #0d6efd;
      background-color: rgba(13, 110, 253, 0.05);
    }
    
    .upload-area.dragover {
      transform: scale(1.01);
    }
    
    .btn-upload {
      display: inline-block;
      padding: 0.5rem 1.5rem;
      background-color: #0d6efd;
      color: white;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    
    .btn-upload:hover {
      background-color: #0b5ed7;
      color: white;
      text-decoration: none;
    }
    
    .file-info {
      margin-top: 1rem;
      padding: 0.5rem;
      border-radius: 4px;
      background-color: #f8f9fa;
    }
    
    /* Dark mode file input */
    body.dark-mode .form-control {
      background-color: #2d2d2d;
      border-color: #4a4a4a;
      color: #e0e0e0;
    }
    
    body.dark-mode .form-control:focus {
      background-color: #2d2d2d;
      color: #e0e0e0;
      border-color: #3a7bd5;
      box-shadow: 0 0 0 0.25rem rgba(58, 123, 213, 0.25);
    }
  </style>
</head>
<body class="dashboard-page">
  <?php include 'includes/sidebar.php'; ?>

  <main class="main">
    <header class="topbar">
      <div class="topbar-left"><?= htmlspecialchars($pageTitle) ?></div>
      <div class="topbar-right">
        <a href="task_management.php" class="btn btn-outline-light btn-sm">
          <i class="bi bi-arrow-left"></i> Back to Tasks
        </a>
      </div>
    </header>

    <section class="content">
      <div class="container-fluid">
        <?php if ($successMessage): ?>
          <div class="alert alert-success"><?= htmlspecialchars($successMessage) ?></div>
        <?php endif; ?>
        
        <?php if ($errorMessage): ?>
          <div class="alert alert-danger"><?= htmlspecialchars($errorMessage) ?></div>
        <?php endif; ?>

        <div class="card">
          <div class="card-header">
            <h3>Upload Tasks via CSV</h3>
            <p class="text-muted mb-0">Upload a CSV file containing tasks to import them into the system.</p>
          </div>
          <div class="card-body">
            <form id="uploadForm" method="post" enctype="multipart/form-data">
              <div class="upload-area" id="dropArea">
                <i class="bi bi-cloud-arrow-up" style="font-size: 3rem; color: #6c757d;"></i>
                <h4 class="mb-2">Drag & Drop your CSV file here</h4>
                <p class="text-muted mb-3">or</p>
                <label for="csvFile" class="btn-upload">
                  <i class="bi bi-upload"></i> Select CSV File
                </label>
                <input type="file" id="csvFile" name="csv_file" accept=".csv" style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0;" required>
                <div id="fileInfo" class="file-info mb-4"></div>
                
                <div class="mt-4 pt-3 border-top">
                  <h5 class="mb-2">Audio Files (Optional)</h5>
                  <p class="small text-muted mb-3">Upload audio files referenced in the CSV</p>
                  <input type="file" id="audioFiles" name="audio_files[]" multiple accept="audio/*" class="form-control bg-dark text-light">
                  <div id="audioFilesInfo" class="small mt-2">No files selected</div>
                </div>
              </div>
              
              <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                <a href="task_management.php" class="btn btn-outline-secondary me-md-2">Cancel</a>
                <button type="submit" class="btn btn-primary">
                  <i class="bi bi-upload"></i> Upload and Import
                </button>
              </div>
            </form>
          </div>
        </div>

        <div class="template-download mt-4">
          <h5><i class="bi bi-download"></i> Download CSV Template</h5>
          <p>Use this template to ensure your CSV file has the correct format.</p>
          <a href="data:text/csv;charset=utf-8,category_id,instruction,instruction_text,tips_text,is_mini_task,status,sort_order,sample_audio_url%0A1,%22Read this positive statement%22,%22Read this positive statement%22,%22Speak clearly and naturally%22,1,active,1,positive1.mp3%0A2,%22This is a negative English statement%22,%22This is a negative English statement%22,%22Maintain a neutral tone%22,1,active,2,negative_en1.mp3%0A3,%22Me wo din de ɛyɛ dɛn?%22,%22Me wo din de ɛyɛ dɛn?%22,%22Use proper Twi intonation%22,1,active,3,twi1.mp3" 
             class="btn btn-outline-info" download="task_import_template.csv">
            <i class="bi bi-file-earmark-spreadsheet"></i> Download Template
          </a>
          
          <div class="mt-3">
            <h6>CSV Format:</h6>
            <ul>
              <li><strong>category_id</strong>: The ID of the category (1-8 based on your categories)</li>
              <li><strong>instruction</strong>: The task instruction (required, will be used for both instruction and instruction_text fields)</li>
              <li><strong>instruction_text</strong>: The task instruction text (required, should match instruction field)</li>
              <li><strong>tips_text</strong>: Helpful tips for the task (optional)</li>
              <li><strong>is_mini_task</strong>: 1 for mini task, 0 for regular (default: 1)</li>
              <li><strong>status</strong>: Task status - 'active' or 'inactive' (default: 'active')</li>
              <li><strong>sort_order</strong>: Number for ordering (default: 0)</li>
              <li><strong>sample_audio_url</strong>: Name of the audio file (must be included in the audio files upload)</li>
            </ul>
            
            <h6 class="mt-3">Category Reference:</h6>
            <ul>
              <li><strong>1</strong>: cat1_positive</li>
              <li><strong>2</strong>: cat2_neg_en</li>
              <li><strong>3</strong>: cat3_neg_twi</li>
              <li><strong>4</strong>: cat4_neg_pid</li>
              <li><strong>5</strong>: cat5_hdneg_en</li>
              <li><strong>6</strong>: cat6_hdneg_twi</li>
              <li><strong>7</strong>: cat7_hdneg_pid</li>
              <li><strong>8</strong>: cat8_iot_mix</li>
            </ul>
            
            <h6 class="mt-3">Audio Files:</h6>
            <ul>
              <li>Upload audio files that are referenced in the CSV</li>
              <li>Supported formats: MP3, WAV, OGG</li>
              <li>Files will be stored in the <code>uploads/</code> directory</li>
              <li>Reference files in CSV using just the filename (e.g., <code>positive1.mp3</code>)</li>
            </ul>
          </div>
        </div>
      </div>
    </section>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      const dropArea = document.getElementById('dropArea');
      const fileInput = document.getElementById('csvFile');
      const audioFilesInput = document.getElementById('audioFiles');
      const fileInfo = document.getElementById('fileInfo');
      const audioFilesInfo = document.getElementById('audioFilesInfo');
      const form = document.getElementById('uploadForm');

      // Prevent default drag behaviors
      ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
      });

      // Highlight drop area when item is dragged over it
      ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, highlight, false);
      });

      ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, unhighlight, false);
      });

      // Handle dropped files
      dropArea.addEventListener('drop', handleDrop, false);

      // Handle file selection via button
      fileInput.addEventListener('change', handleFiles, false);

      // Handle audio files selection
      audioFilesInput.addEventListener('change', function(e) {
        const files = e.target.files;
        if (files.length > 0) {
          const fileList = Array.from(files).map(file => 
            `${file.name} (${formatFileSize(file.size)})`
          ).join('<br>');
          audioFilesInfo.innerHTML = `${files.length} file(s) selected:<br>${fileList}`;
        } else {
          audioFilesInfo.textContent = 'No files selected';
        }
      });

      function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
      }

      function highlight() {
        dropArea.classList.add('dragover');
      }

      function unhighlight() {
        dropArea.classList.remove('dragover');
      }

      function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles({ target: { files } });
      }

      function handleFiles(e) {
        const files = e.target.files;
        const fileInput = document.getElementById('csvFile');
        
        if (files.length > 0) {
          fileInfo.innerHTML = `
            <div class="d-flex align-items-center justify-content-center">
              <i class="bi bi-file-earmark-text me-2"></i>
              <span>${files[0].name} (${formatFileSize(files[0].size)})</span>
            </div>
          `;
          // Ensure the file input is valid for form submission
          fileInput.setCustomValidity('');
        } else {
          fileInput.setCustomValidity('Please select a file to upload.');
        }
      }

      function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
      }
    });
  </script>
</body>
</html>
