<?php
// Enable error display for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

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

$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        try {
            if ($_POST['action'] === 'add' && !empty($_POST['category_id']) && !empty($_POST['instruction_text'])) {
                // Add new mini task
                $stmt = $pdo->prepare("INSERT INTO tasks (category_id, is_mini_task, instruction_text, tips_text, sample_audio_url, status, sort_order) 
                                     VALUES (?, 1, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $_POST['category_id'],
                    $_POST['instruction_text'],
                    $_POST['tips_text'] ?? '',
                    $_FILES['audio_file']['name'] ? 'uploads/' . basename($_FILES['audio_file']['name']) : null,
                    $_POST['status'] ?? 'active',
                    (int)($_POST['sort_order'] ?? 0)
                ]);
                
                // Handle file upload
                if (isset($_FILES['audio_file']) && $_FILES['audio_file']['error'] === UPLOAD_ERR_OK) {
                    $uploadDir = __DIR__ . '/../uploads/';
                    if (!file_exists($uploadDir)) {
                        mkdir($uploadDir, 0777, true);
                    }
                    $uploadFile = $uploadDir . basename($_FILES['audio_file']['name']);
                    move_uploaded_file($_FILES['audio_file']['tmp_name'], $uploadFile);
                }
                
                $message = 'Mini task added successfully!';
            } 
            elseif ($_POST['action'] === 'update' && !empty($_POST['id'])) {
                // Debug logging
                error_log('Starting update for task ID: ' . $_POST['id']);
                
                // Get current task data
                $stmt = $pdo->prepare("SELECT * FROM tasks WHERE id = ?");
                $stmt->execute([$_POST['id']]);
                $currentTask = $stmt->fetch();
                
                if (!$currentTask) {
                    throw new Exception('Task not found');
                }
                
                // Initialize SQL and params
                $sql = "UPDATE tasks SET 
                        category_id = ?, 
                        instruction_text = ?, 
                        tips_text = ?, 
                        status = ?,
                        sort_order = ?";
                
                $params = [
                    $_POST['category_id'],
                    $_POST['instruction_text'],
                    $_POST['tips_text'] ?? '',
                    $_POST['status'] ?? 'active',
                    (int)($_POST['sort_order'] ?? 0)
                ];
                
                // Handle file upload if a new file is provided
                if (isset($_FILES['audio_file']) && $_FILES['audio_file']['error'] === UPLOAD_ERR_OK) {
                    $uploadDir = __DIR__ . '/../uploads/';
                    
                    // Ensure uploads directory exists and is writable
                    if (!file_exists($uploadDir)) {
                        if (!mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
                            throw new Exception('Failed to create uploads directory');
                        }
                    }
                    
                    // Sanitize filename
                    $fileName = preg_replace('/[^a-zA-Z0-9\._-]/', '', basename($_FILES['audio_file']['name']));
                    if (empty($fileName)) {
                        $fileName = 'audio_' . time() . '.wav';
                    }
                    
                    // Generate unique filename
                    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                    $newFileName = 'task_' . $_POST['id'] . '_' . time() . '.' . $fileExt;
                    $uploadFile = $uploadDir . $newFileName;
                    $audioUrl = '/uploads/' . $newFileName;
                    
                    // Debug logging
                    error_log('Attempting to upload file: ' . $uploadFile);
                    error_log('Temporary file: ' . $_FILES['audio_file']['tmp_name']);
                    
                    // Ensure the file doesn't already exist
                    $counter = 1;
                    while (file_exists($uploadFile)) {
                        $info = pathinfo($newFileName);
                        $newFileName = $info['filename'] . '_' . $counter . '.' . $info['extension'];
                        $uploadFile = $uploadDir . $newFileName;
                        $audioUrl = '/uploads/' . $newFileName;
                        $counter++;
                    }
                    
                    // Move the uploaded file
                    if (move_uploaded_file($_FILES['audio_file']['tmp_name'], $uploadFile)) {
                        // Set proper permissions
                        chmod($uploadFile, 0644);
                        
                        // Update SQL and parameters
                        $sql .= ", sample_audio_url = ?";
                        $params[] = $audioUrl;
                        
                        error_log('File uploaded successfully: ' . $uploadFile);
                    } else {
                        $errorMsg = 'Failed to move uploaded file. ';
                        $errorMsg .= 'Tmp file exists: ' . (file_exists($_FILES['audio_file']['tmp_name']) ? 'yes' : 'no') . '. ';
                        $errorMsg .= 'Upload dir writable: ' . (is_writable($uploadDir) ? 'yes' : 'no') . '. ';
                        error_log($errorMsg);
                        throw new Exception($errorMsg);
                    }
                }
                
                // Add ID as the last parameter for WHERE clause
                $params[] = $_POST['id'];
                
                $sql .= " WHERE id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                
                error_log('Task updated successfully');
                $message = 'Mini task updated successfully!';
            }
            elseif ($_POST['action'] === 'delete' && !empty($_POST['id'])) {
                // Check if task is in use
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM recordings WHERE task_id = ?");
                $stmt->execute([$_POST['id']]);
                $count = $stmt->fetchColumn();
                
                if ($count > 0) {
                    $error = 'Cannot delete task: It is being used by ' . $count . ' recording(s).';
                } else {
                    $stmt = $pdo->prepare("DELETE FROM tasks WHERE id = ? AND is_mini_task = 1");
                    $stmt->execute([$_POST['id']]);
                    $message = 'Mini task deleted successfully!';
                }
            }
        } catch (PDOException $e) {
            error_log('Database error in mini_task_manager: ' . $e->getMessage());
            $error = 'Database error: ' . $e->getMessage();
        } catch (Exception $e) {
            error_log('Exception in mini_task_manager: ' . $e->getMessage());
            $error = 'Error: ' . $e->getMessage();
        }
    }
}

// Fetch all mini tasks with category names
$stmt = $pdo->query("
    SELECT t.*, tc.name as category_name 
    FROM tasks t
    LEFT JOIN task_categories tc ON t.category_id = tc.id
    WHERE t.is_mini_task = 1
    ORDER BY t.sort_order, t.created_at DESC
");
$miniTasks = $stmt->fetchAll();

// Fetch all active categories for the dropdown
$categories = $pdo->query("SELECT * FROM task_categories WHERE status = 'active' ORDER BY name")->fetchAll();
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Mini Task Manager - Admin Panel</title>
  <link rel="stylesheet" href="assets/theme.css">
  <style>
    .task-form {
      background: var(--surface);
      padding: 1.5rem;
      border-radius: var(--radius);
      box-shadow: var(--card-shadow);
      margin-bottom: 1.5rem;
      border: 1px solid rgba(255,255,255,0.03);
    }
    .form-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 1.5rem;
      margin-bottom: 1rem;
    }
    .form-group {
      margin-bottom: 1rem;
    }
    .form-group.full-width {
      grid-column: 1 / -1;
    }
    .form-group label {
      display: block;
      margin-bottom: 0.5rem;
      color: var(--muted);
      font-size: 0.9em;
    }
    .form-control {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid rgba(255,255,255,0.08);
      border-radius: 8px;
      background: rgba(255,255,255,0.02);
      color: var(--text);
      transition: border-color 0.2s;
    }
    .form-control:focus {
      outline: none;
      border-color: var(--accent-orange);
    }
    textarea.form-control {
      min-height: 100px;
      resize: vertical;
    }
    .form-actions {
      display: flex;
      gap: 10px;
      margin-top: 1rem;
    }
    .btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 10px 18px;
      border-radius: 8px;
      border: none;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s;
      text-decoration: none;
    }
    .btn-primary {
      background: var(--accent-orange);
      color: #000;
    }
    .btn-primary:hover {
      background: #ff8c1a;
      transform: translateY(-1px);
    }
    .btn-cancel {
      background: rgba(255,255,255,0.05);
      color: var(--muted);
    }
    .btn-cancel:hover {
      background: rgba(255,255,255,0.1);
      color: var(--text);
    }
    .btn-danger {
      background: rgba(239, 68, 68, 0.15);
      color: #f87171;
    }
    .btn-danger:hover {
      background: rgba(239, 68, 68, 0.25);
      color: #f87171;
    }
    .table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 1rem;
      color: var(--text);
    }
    .table th, .table td {
      padding: 12px 16px;
      text-align: left;
      border-bottom: 1px solid rgba(255,255,255,0.05);
    }
    .table th {
      background: rgba(255,255,255,0.02);
      color: var(--muted);
      font-weight: 600;
      font-size: 0.85em;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    .table tr:hover {
      background: rgba(255,255,255,0.02);
    }
    .status-active {
      color: #4ade80;
      font-weight: 500;
    }
    .status-inactive {
      color: #f87171;
      font-weight: 500;
    }
    .alert {
      padding: 12px 16px;
      border-radius: 8px;
      margin-bottom: 1.5rem;
      font-size: 0.95em;
    }
    .alert-success {
      background: rgba(16, 185, 129, 0.15);
      color: #6ee7b7;
      border: 1px solid rgba(16, 185, 129, 0.1);
    }
    .alert-error {
      background: rgba(239, 68, 68, 0.15);
      color: #fca5a5;
      border: 1px solid rgba(239, 68, 68, 0.1);
    }
    .action-buttons {
      display: flex;
      gap: 8px;
    }
    .audio-preview {
      background: rgba(255,255,255,0.03);
      border-radius: 6px;
      padding: 8px;
      margin-top: 8px;
    }
    .audio-preview audio {
      width: 100%;
      height: 36px;
    }
    .preview-label {
      font-size: 0.8em;
      color: var(--muted);
      margin-bottom: 4px;
    }
  </style>
</head>
<body class="dashboard-page">
  <aside class="sidebar">
    <div class="sidebar-brand">Wake Word</div>
    <nav class="nav">
      <a href="dashboard.php" class="nav-item">Dashboard</a>
      <a href="review_queue.php" class="nav-item">Review Queue</a>
      <a href="users.php" class="nav-item">Users</a>
      <a href="export.php" class="nav-item">Dataset Export</a>
      <a href="task_management.php" class="nav-item active">Task Management</a>
      <a href="audit_logs.php" class="nav-item">Audit Logs</a>
      <a href="logout.php" class="nav-item">Logout</a>
    </nav>
  </aside>

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

    <section class="content">
      <?php if ($message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
      <?php endif; ?>
      
      <?php if ($error): ?>
        <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
      <?php endif; ?>

      <div class="task-form">
        <h3 id="form-title">Add New Mini Task</h3>
        <form id="taskForm" method="post" enctype="multipart/form-data">
          <input type="hidden" name="action" id="formAction" value="add">
          <input type="hidden" name="id" id="taskId">
          
          <div class="form-grid">
            <div class="form-group">
              <label for="category_id">Category</label>
              <select id="category_id" name="category_id" class="form-control" required>
                <option value="">Select a category</option>
                <?php foreach ($categories as $category): ?>
                  <option value="<?= $category['id'] ?>"><?= htmlspecialchars($category['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <div class="form-group">
              <label for="status">Status</label>
              <select id="status" name="status" class="form-control">
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
            </div>
            
            <div class="form-group">
              <label for="sort_order">Sort Order</label>
              <input type="number" id="sort_order" name="sort_order" class="form-control" value="0" min="0">
            </div>
            
            <div class="form-group">
              <label for="audio_file">Audio File</label>
              <input type="file" id="audio_file" name="audio_file" class="form-control" accept="audio/*">
              <div id="audioPreview" class="audio-preview" style="display: none;">
                <div class="preview-label">Current Audio:</div>
                <audio controls id="currentAudio"></audio>
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <label for="instruction_text">Instruction Text (will appear in the instruction bubble)</label>
            <textarea id="instruction_text" name="instruction_text" class="form-control" rows="3" required></textarea>
            <small class="muted">Example: "Today's Task: Say the wake word 'Hey Nova' as if you're in a hurry."</small>
          </div>
          
          <div class="form-group">
            <label for="tips_text">Tips (will appear below the audio bubble)</label>
            <textarea id="tips_text" name="tips_text" class="form-control" rows="3"></textarea>
            <small class="muted">Provide helpful tips or context for this task.</small>
          </div>
          
          <div class="form-actions">
            <button type="submit" class="btn btn-primary" id="submitBtn">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
                <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                <polyline points="17 21 17 13 7 13 7 21"></polyline>
                <polyline points="7 3 7 8 15 8"></polyline>
              </svg>
              Add Mini Task
            </button>
            <button type="button" class="btn btn-cancel" id="cancelBtn" style="display: none;" onclick="resetForm()">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
              Cancel
            </button>
          </div>
        </form>
      </div>

      <div class="card">
        <h3>Mini Tasks</h3>
        <?php if (empty($miniTasks)): ?>
          <p>No mini tasks found. Add your first mini task above.</p>
        <?php else: ?>
          <table class="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Instruction Preview</th>
                <th>Status</th>
                <th>Order</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($miniTasks as $task): ?>
                <tr>
                  <td><?= htmlspecialchars($task['id']) ?></td>
                  <td><?= htmlspecialchars($task['category_name'] ?? 'N/A') ?></td>
                  <td>
                    <div style="max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" 
                         title="<?= htmlspecialchars($task['instruction_text']) ?>">
                      <?= htmlspecialchars($task['instruction_text']) ?>
                    </div>
                  </td>
                  <td>
                    <span class="status-<?= htmlspecialchars($task['status']) ?>">
                      <?= ucfirst(htmlspecialchars($task['status'])) ?>
                    </span>
                  </td>
                  <td><?= (int)$task['sort_order'] ?></td>
                  <td class="action-buttons">
                    <button onclick="editTask(<?= htmlspecialchars(json_encode($task)) ?>)" class="btn" style="background: rgba(255, 154, 60, 0.1); color: var(--accent-orange); padding: 6px 12px; font-size: 0.85em;">
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 4px;">
                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                      </svg>
                      Edit
                    </button>
                    <button onclick="deleteTask(<?= $task['id'] ?>, '<?= addslashes(htmlspecialchars($task['instruction_text'])) ?>')" class="btn btn-danger">
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 4px;">
                        <polyline points="3 6 5 6 21 6"></polyline>
                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                        <line x1="10" y1="11" x2="10" y2="17"></line>
                        <line x1="14" y1="11" x2="14" y2="17"></line>
                      </svg>
                      Delete
                    </button>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php endif; ?>
      </div>
    </section>
  </main>

  <form id="deleteForm" method="post" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="id" id="deleteId">
    <?php if (isset($_SESSION['csrf_token'])): ?>
      <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
    <?php endif; ?>
  </form>

  <script>
    function editTask(task) {
      document.getElementById('form-title').textContent = 'Edit Mini Task';
      document.getElementById('formAction').value = 'update';
      document.getElementById('taskId').value = task.id;
      document.getElementById('category_id').value = task.category_id || '';
      document.getElementById('instruction_text').value = task.instruction_text || '';
      document.getElementById('tips_text').value = task.tips_text || '';
      document.getElementById('status').value = task.status || 'active';
      document.getElementById('sort_order').value = task.sort_order || 0;
      
      // Handle audio preview
      const audioPreview = document.getElementById('audioPreview');
      const currentAudio = document.getElementById('currentAudio');
      
      if (task.sample_audio_url) {
        currentAudio.src = '../' + task.sample_audio_url;
        audioPreview.style.display = 'block';
      } else {
        audioPreview.style.display = 'none';
      }
      
      document.getElementById('submitBtn').innerHTML = `
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
        </svg>
        Update Task
      `;
      document.getElementById('cancelBtn').style.display = 'inline-flex';
      
      // Scroll to form
      document.querySelector('.task-form').scrollIntoView({ behavior: 'smooth' });
      document.getElementById('instruction_text').focus();
    }
    
    function resetForm() {
      document.getElementById('taskForm').reset();
      document.getElementById('form-title').textContent = 'Add New Mini Task';
      document.getElementById('formAction').value = 'add';
      document.getElementById('taskId').value = '';
      document.getElementById('audioPreview').style.display = 'none';
      document.getElementById('submitBtn').innerHTML = `
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
          <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
          <polyline points="17 21 17 13 7 13 7 21"></polyline>
          <polyline points="7 3 7 8 15 8"></polyline>
        </svg>
        Add Mini Task
      `;
      document.getElementById('cancelBtn').style.display = 'none';
    }
    
    function deleteTask(id, name) {
      if (confirm(`Are you sure you want to delete the mini task "${name}"?`)) {
        document.getElementById('deleteId').value = id;
        document.getElementById('deleteForm').submit();
      }
    }
    
    // Handle file input change to show filename
    document.getElementById('audio_file').addEventListener('change', function(e) {
      const fileName = e.target.files.length ? e.target.files[0].name : 'No file chosen';
      // You could add more sophisticated file handling here if needed
    });
  </script>
</body>
</html>
