<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── AJAX handler ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $title    = sanitize($_POST['title'] ?? '');
        $desc     = sanitize($_POST['description'] ?? '');
        $subId    = (int)($_POST['subject_id'] ?? 0) ?: null;
        $due      = $_POST['due_date'] ?? '';
        $priority = in_array($_POST['priority'] ?? '', ['low','medium','high']) ? $_POST['priority'] : 'medium';

        if ($title === '')
            jsonResponse(['success'=>false, 'message'=>'Task title is required.']);

        $pdo->prepare("INSERT INTO tasks (user_id,subject_id,title,description,due_date,priority) VALUES (?,?,?,?,?,?)")
            ->execute([$uid, $subId, $title, $desc, $due ?: null, $priority]);

        jsonResponse(['success'=>true, 'message'=>'Task added!']);
    }

    if ($action === 'status') {
        $id     = (int)($_POST['id'] ?? 0);
        $status = in_array($_POST['status'] ?? '', ['pending','in_progress','completed']) ? $_POST['status'] : 'pending';
        $pdo->prepare("UPDATE tasks SET status=? WHERE id=? AND user_id=?")->execute([$status, $id, $uid]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'delete') {
        $pdo->prepare("DELETE FROM tasks WHERE id=? AND user_id=?")->execute([(int)($_POST['id'] ?? 0), $uid]);
        jsonResponse(['success'=>true]);
    }

    jsonResponse(['success'=>false, 'message'=>'Unknown action.']);
}

// ── Page data ────────────────────────────────────────────────────────
$filter = $_GET['filter'] ?? 'pending';
$allowed = ['pending','in_progress','completed','all'];
if (!in_array($filter, $allowed)) $filter = 'pending';

$sql = "SELECT t.*, s.name AS subject_name, s.color
        FROM tasks t
        LEFT JOIN subjects s ON t.subject_id = s.id
        WHERE t.user_id = ?";
$params = [$uid];
if ($filter !== 'all') { $sql .= " AND t.status = ?"; $params[] = $filter; }
$sql .= " ORDER BY FIELD(t.priority,'high','medium','low'), t.due_date ASC, t.created_at DESC";

$tasksQ = $pdo->prepare($sql); $tasksQ->execute($params); $tasks = $tasksQ->fetchAll();

$subjectsQ = $pdo->prepare("SELECT id, name FROM subjects WHERE user_id=? ORDER BY name");
$subjectsQ->execute([$uid]); $subjectsList = $subjectsQ->fetchAll();

require_once 'includes/header.php';
renderHeader('Tasks', 'tasks');
?>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px">
  <div class="period-selector">
    <a href="?filter=pending"     class="period-btn <?= $filter==='pending'    ?'active':'' ?>">Pending</a>
    <a href="?filter=in_progress" class="period-btn <?= $filter==='in_progress'?'active':'' ?>">In Progress</a>
    <a href="?filter=completed"   class="period-btn <?= $filter==='completed'  ?'active':'' ?>">Done</a>
    <a href="?filter=all"         class="period-btn <?= $filter==='all'        ?'active':'' ?>">All</a>
  </div>
  <button class="btn btn-primary" onclick="openModal('addTaskModal')">+ Add Task</button>
</div>

<?php if ($tasks): ?>
<div style="display:flex;flex-direction:column;gap:12px">
<?php foreach ($tasks as $t):
  $pBadge  = ['high'=>'red','medium'=>'yellow','low'=>'cyan'][$t['priority']] ?? 'cyan';
  $overdue = $t['due_date'] && $t['due_date'] < date('Y-m-d') && $t['status'] !== 'completed';
?>
<div class="card" style="padding:18px;<?= $overdue ? 'border-color:rgba(239,68,68,0.4)' : '' ?>">
  <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
    <div style="display:flex;align-items:center;gap:12px;flex:1;min-width:0">
      <span style="font-size:22px;flex-shrink:0">
        <?= $t['status']==='completed' ? '✅' : ($t['status']==='in_progress' ? '🔄' : '<span style="opacity:.5">⭕</span>') ?>
      </span>
      <div style="min-width:0">
        <div style="font-weight:600;color:var(--text-primary);font-size:15px;<?= $t['status']==='completed'?'text-decoration:line-through;opacity:0.6':'' ?>">
          <?= htmlspecialchars($t['title']) ?>
        </div>
        <div style="display:flex;gap:8px;align-items:center;margin-top:4px;flex-wrap:wrap">
          <?php if ($t['subject_name']): ?>
          <span style="font-size:12px;color:var(--text-muted)">
            <span class="subject-dot" style="background:<?= htmlspecialchars($t['color']) ?>"></span>
            <?= htmlspecialchars($t['subject_name']) ?>
          </span>
          <?php endif; ?>
          <?php if ($t['due_date']): ?>
          <span style="font-size:12px;color:<?= $overdue?'var(--danger)':'var(--text-muted)' ?>">
            📅 <?= date('M j, Y', strtotime($t['due_date'])) ?><?= $overdue?' ⚠️ Overdue':'' ?>
          </span>
          <?php endif; ?>
          <span class="badge badge-<?= $pBadge ?>" style="font-size:11px"><?= ucfirst($t['priority']) ?></span>
        </div>
      </div>
    </div>
    <div style="display:flex;gap:8px;flex-shrink:0;align-items:center">
      <?php if ($t['status'] !== 'completed'): ?>
      <select class="form-control" style="padding:6px 10px;font-size:13px;width:auto"
              onchange="changeStatus(<?= $t['id'] ?>, this.value)">
        <option value="pending"     <?= $t['status']==='pending'    ?'selected':'' ?>>Pending</option>
        <option value="in_progress" <?= $t['status']==='in_progress'?'selected':'' ?>>In Progress</option>
        <option value="completed">Completed</option>
      </select>
      <?php endif; ?>
      <button class="btn btn-danger btn-sm btn-icon" onclick="deleteTask(<?= $t['id'] ?>)">🗑️</button>
    </div>
  </div>
  <?php if ($t['description']): ?>
  <div style="margin-top:10px;padding-top:10px;border-top:1px solid var(--border);font-size:13px;color:var(--text-secondary)">
    <?= htmlspecialchars($t['description']) ?>
  </div>
  <?php endif; ?>
</div>
<?php endforeach; ?>
</div>

<?php else: ?>
<div class="card">
  <div class="empty-state">
    <div class="empty-icon">✅</div>
    <h3>No <?= $filter === 'all' ? '' : $filter.' ' ?>tasks</h3>
    <p><?= $filter === 'completed' ? 'Complete tasks will appear here' : 'Click "Add Task" to create one' ?></p>
  </div>
</div>
<?php endif; ?>

<!-- ── Add Task Modal ─────────────────────────────────────────────── -->
<div class="modal-overlay" id="addTaskModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">➕ Add Task</div>
      <button class="modal-close" onclick="closeModal('addTaskModal')">✕</button>
    </div>
    <div id="taskMsgBox" style="display:none" class="alert"></div>
    <div class="form-group">
      <label class="form-label">Task Title *</label>
      <input type="text" id="task_title" class="form-control" placeholder="What needs to be done?">
    </div>
    <div class="form-group">
      <label class="form-label">Description (optional)</label>
      <textarea id="task_desc" class="form-control" rows="2" placeholder="Details..."></textarea>
    </div>
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Subject (optional)</label>
        <select id="task_subject" class="form-control">
          <option value="">None</option>
          <?php foreach ($subjectsList as $sub): ?>
          <option value="<?= $sub['id'] ?>"><?= htmlspecialchars($sub['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Priority</label>
        <select id="task_priority" class="form-control">
          <option value="low">Low</option>
          <option value="medium" selected>Medium</option>
          <option value="high">High</option>
        </select>
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Due Date (optional)</label>
      <input type="date" id="task_due" class="form-control">
    </div>
    <button id="taskSaveBtn" class="btn btn-primary btn-full" onclick="saveTask()">Add Task</button>
  </div>
</div>

<script>
function showTaskMsg(msg, type) {
  const el = document.getElementById('taskMsgBox');
  el.className = 'alert alert-' + type;
  el.innerHTML = (type==='error' ? '⚠️ ' : '✅ ') + msg;
  el.style.display = 'flex';
}

async function saveTask() {
  const title = document.getElementById('task_title').value.trim();
  if (!title) { showTaskMsg('Please enter a task title.', 'error'); return; }

  const btn = document.getElementById('taskSaveBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span>&nbsp; Saving...';

  try {
    const fd = new FormData();
    fd.append('action',      'add');
    fd.append('title',       title);
    fd.append('description', document.getElementById('task_desc').value);
    fd.append('subject_id',  document.getElementById('task_subject').value);
    fd.append('priority',    document.getElementById('task_priority').value);
    fd.append('due_date',    document.getElementById('task_due').value);

    const res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const ct   = res.headers.get('content-type') || '';
    if (!ct.includes('application/json')) throw new Error('Server error ' + res.status);
    const data = await res.json();

    if (data.success) {
      showTaskMsg(data.message, 'success');
      document.getElementById('task_title').value = '';
      document.getElementById('task_desc').value  = '';
      setTimeout(() => { closeModal('addTaskModal'); location.reload(); }, 900);
    } else {
      showTaskMsg(data.message, 'error');
      btn.disabled = false;
      btn.innerHTML = 'Add Task';
    }
  } catch(err) {
    console.error(err);
    showTaskMsg('Connection error. Please try again.', 'error');
    btn.disabled = false;
    btn.innerHTML = 'Add Task';
  }
}

document.getElementById('task_title').addEventListener('keydown', e => {
  if (e.key === 'Enter') saveTask();
});

async function changeStatus(id, status) {
  try {
    const fd = new FormData();
    fd.append('action', 'status');
    fd.append('id', id);
    fd.append('status', status);
    const res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const ct   = res.headers.get('content-type') || '';
    if (!ct.includes('application/json')) throw new Error('Server error ' + res.status);
    const data = await res.json();
    if (data.success) location.reload();
  } catch(err) { console.error(err); }
}

async function deleteTask(id) {
  if (!(await stConfirm('Delete this task?'))) return;
  try {
    const fd = new FormData();
    fd.append('action', 'delete');
    fd.append('id', id);
    const res  = await fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const ct   = res.headers.get('content-type') || '';
    if (!ct.includes('application/json')) throw new Error('Server error ' + res.status);
    const data = await res.json();
    if (data.success) location.reload();
  } catch(err) { console.error(err); alert('Error. Please try again.'); }
}
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
