<?php
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['name'])) {
                // Add new category
                $stmt = $pdo->prepare("INSERT INTO task_categories (name, status) VALUES (?, ?)");
                $stmt->execute([$_POST['name'], 'active']);
                $message = 'Category added successfully!';
            } 
            elseif ($_POST['action'] === 'update' && !empty($_POST['id']) && !empty($_POST['name'])) {
                // Update existing category
                $stmt = $pdo->prepare("UPDATE task_categories SET name = ?, status = ? WHERE id = ?");
                $stmt->execute([$_POST['name'], $_POST['status'], $_POST['id']]);
                $message = 'Category updated successfully!';
            }
            elseif ($_POST['action'] === 'delete' && !empty($_POST['id'])) {
                // Check if category is in use
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE category_id = ?");
                $stmt->execute([$_POST['id']]);
                $count = $stmt->fetchColumn();
                
                if ($count > 0) {
                    $error = 'Cannot delete category: It is being used by ' . $count . ' task(s).';
                } else {
                    $stmt = $pdo->prepare("DELETE FROM task_categories WHERE id = ?");
                    $stmt->execute([$_POST['id']]);
                    $message = 'Category deleted successfully!';
                }
            }
        } catch (PDOException $e) {
            $error = 'Database error: ' . $e->getMessage();
        }
    }
}

// Fetch all categories
$categories = $pdo->query("SELECT * FROM task_categories ORDER BY name")->fetchAll();
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Task Category Manager - Admin Panel</title>
  <link rel="stylesheet" href="assets/theme.css">
  <style>
    .category-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-group {
      margin-bottom: 1rem;
    }
    .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);
    }
    .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;
    }
    .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);
      margin-left: 10px;
    }
    .btn-cancel:hover {
      background: rgba(255,255,255,0.1);
      color: var(--text);
    }
    .btn-danger {
      background: rgba(229, 62, 62, 0.15);
      color: #ff6b6b;
      padding: 6px 12px;
      font-size: 0.85em;
    }
    .btn-danger:hover {
      background: rgba(229, 62, 62, 0.25);
      color: #ff5252;
    }
    .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;
    }
  </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">Task Category 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="category-form">
        <h3 id="form-title">Add New Category</h3>
        <form id="categoryForm" method="post">
          <input type="hidden" name="action" id="formAction" value="add">
          <input type="hidden" name="id" id="categoryId">
          
          <div class="form-group">
            <label for="name">Category Name</label>
            <input type="text" id="name" name="name" class="form-control" required>
          </div>
          
          <div class="form-group" id="statusGroup" style="display: none;">
            <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-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 Category
            </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>Task Categories</h3>
        <?php if (empty($categories)): ?>
          <p>No categories found. Add your first category above.</p>
        <?php else: ?>
          <table class="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Status</th>
                <th>Created</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($categories as $category): ?>
                <tr>
                  <td><?= htmlspecialchars($category['id']) ?></td>
                  <td><?= htmlspecialchars($category['name']) ?></td>
                  <td>
                    <span class="status-<?= htmlspecialchars($category['status']) ?>">
                      <?= ucfirst(htmlspecialchars($category['status'])) ?>
                    </span>
                  </td>
                  <td><?= date('M d, Y', strtotime($category['created_at'])) ?></td>
                  <td class="action-buttons">
                    <button onclick="editCategory(<?= htmlspecialchars(json_encode($category)) ?>)" 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="deleteCategory(<?= $category['id'] ?>, '<?= addslashes($category['name']) ?>')" 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 editCategory(category) {
      document.getElementById('form-title').textContent = 'Edit Category';
      document.getElementById('formAction').value = 'update';
      document.getElementById('categoryId').value = category.id;
      document.getElementById('name').value = category.name;
      document.getElementById('status').value = category.status;
      document.getElementById('statusGroup').style.display = 'block';
      document.getElementById('submitBtn').textContent = 'Update Category';
      document.getElementById('cancelBtn').style.display = 'inline-block';
      
      // Scroll to form
      document.querySelector('.category-form').scrollIntoView({ behavior: 'smooth' });
      document.getElementById('name').focus();
    }
    
    function resetForm() {
      document.getElementById('categoryForm').reset();
      document.getElementById('form-title').textContent = 'Add New Category';
      document.getElementById('formAction').value = 'add';
      document.getElementById('statusGroup').style.display = 'none';
      document.getElementById('submitBtn').textContent = 'Add Category';
      document.getElementById('cancelBtn').style.display = 'none';
      document.getElementById('categoryId').value = '';
    }
    
    function deleteCategory(id, name) {
      if (confirm(`Are you sure you want to delete the category "${name}"?`)) {
        document.getElementById('deleteId').value = id;
        document.getElementById('deleteForm').submit();
      }
    }
  </script>
</body>
</html>
