<?php
session_start();

const CREDS     = ['user' => 'ecoadmin', 'pass' => 'ch11may'];
const DATA_FILE = __DIR__ . '/tasks.json';

// ── Helpers ──────────────────────────────────────────────────────────────────
function readTasks(): array {
    if (!file_exists(DATA_FILE)) return [];
    return json_decode(file_get_contents(DATA_FILE), true) ?: [];
}
function writeTasks(array $tasks): void {
    file_put_contents(DATA_FILE, json_encode(array_values($tasks), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
function isAuth(): bool { return !empty($_SESSION['ecolist']); }
function jsonOut(array $d, int $s = 200): never {
    http_response_code($s);
    header('Content-Type: application/json');
    echo json_encode($d);
    exit;
}
function esc(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

$page   = $_GET['page']   ?? '';
$method = $_SERVER['REQUEST_METHOD'];

// ── API ───────────────────────────────────────────────────────────────────────
if ($page === 'api') {
    if (!isAuth()) jsonOut(['error' => 'Unauthorized'], 401);
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
    $id    = $_GET['id'] ?? '';
    $tasks = readTasks();

    if ($method === 'GET')  jsonOut($tasks);

    if ($method === 'POST') {
        $task = [
            'id'       => uniqid('t', true),
            'title'    => trim($input['title'] ?? '') ?: 'Untitled Task',
            'category' => $input['category'] ?? 'General',
            'done'     => false,
            'urgent'   => 'low',
            'notes'    => '',
        ];
        $tasks[] = $task;
        writeTasks($tasks);
        jsonOut($task);
    }

    if ($method === 'PUT' && $id) {
        $allowed = ['title', 'done', 'urgent', 'category', 'notes'];
        foreach ($tasks as &$t) {
            if ($t['id'] !== $id) continue;
            foreach ($allowed as $k) { if (array_key_exists($k, $input)) $t[$k] = $input[$k]; }
            writeTasks($tasks);
            jsonOut($t);
        }
        jsonOut(['error' => 'Not found'], 404);
    }

    if ($method === 'DELETE' && $id) {
        $tasks = array_filter($tasks, fn($t) => $t['id'] !== $id);
        writeTasks($tasks);
        jsonOut(['success' => true]);
    }

    jsonOut(['error' => 'Bad request'], 400);
}

// ── Auth ──────────────────────────────────────────────────────────────────────
$loginError = '';

if ($page === 'login' && $method === 'POST') {
    $u = $_POST['user'] ?? '';
    $p = $_POST['pass'] ?? '';
    if ($u === CREDS['user'] && $p === CREDS['pass']) {
        $_SESSION['ecolist'] = true;
        header('Location: /ecolist/');
        exit;
    }
    $loginError = 'Invalid credentials';
}

if ($page === 'logout') {
    session_destroy();
    header('Location: /ecolist/login');
    exit;
}

if (!isAuth() && $page !== 'login') {
    header('Location: /ecolist/login');
    exit;
}

$tasks     = isAuth() ? readTasks() : [];
$showLogin = !isAuth() || $page === 'login';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ecolist<?= $showLogin ? ' — Login' : ' — Team Checklist' ?></title>
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600&family=Playfair+Display:ital,wght@0,400;1,400&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    :root {
      --bg:        #f9f6f0;
      --bg-card:   #ffffff;
      --bg-2:      #f2ede5;
      --border:    rgba(0,0,0,0.08);
      --text:      #1a1612;
      --text-dim:  rgba(26,22,18,0.65);
      --text-muted:rgba(26,22,18,0.42);
      --emerald:   #16a34a;
      --emerald-d: #15803d;
      --emerald-bg:rgba(22,163,74,0.09);
      --amber:     #d97706;
      --amber-bg:  rgba(217,119,6,0.09);
      --red:       #dc2626;
      --red-bg:    rgba(220,38,38,0.09);
      --ff-body:   'Outfit', system-ui, sans-serif;
      --ff-disp:   'Playfair Display', Georgia, serif;
    }
    body { background: var(--bg); font-family: var(--ff-body); min-height: 100vh; color: var(--text); }

    /* ── LOGIN ── */
    .login-wrap { display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 24px; }
    .login-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 14px; padding: 40px 36px; width: 100%; max-width: 380px; box-shadow: 0 2px 20px rgba(0,0,0,0.07); }
    .login-logo { display: flex; align-items: center; gap: 10px; justify-content: center; margin-bottom: 28px; text-decoration: none; color: var(--text); }
    .login-logo span { font-family: var(--ff-disp); font-size: 22px; letter-spacing: -0.02em; }
    .login-logo span em { color: var(--emerald); font-style: normal; }
    .login-title { font-family: var(--ff-disp); font-size: 26px; font-weight: 400; text-align: center; margin-bottom: 6px; }
    .login-sub { font-size: 14px; color: var(--text-dim); text-align: center; margin-bottom: 28px; }
    .err-box { background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c; border-radius: 8px; padding: 10px 14px; font-size: 13.5px; margin-bottom: 18px; }
    .field { margin-bottom: 16px; }
    .field label { display: block; font-size: 13px; font-weight: 500; color: var(--text-dim); margin-bottom: 6px; }
    .field input { width: 100%; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--ff-body); font-size: 15px; color: var(--text); background: var(--bg); outline: none; transition: border-color .15s; }
    .field input:focus { border-color: var(--emerald); }
    .btn-login { width: 100%; padding: 12px; background: var(--emerald); color: #fff; border: none; border-radius: 8px; font-family: var(--ff-body); font-size: 15px; font-weight: 500; cursor: pointer; margin-top: 8px; transition: background .15s; }
    .btn-login:hover { background: var(--emerald-d); }

    /* ── HEADER ── */
    .header { background: var(--bg-card); border-bottom: 1px solid var(--border); padding: 0 24px; display: flex; align-items: center; justify-content: space-between; height: 56px; position: sticky; top: 0; z-index: 10; }
    .header-logo { display: flex; align-items: center; gap: 9px; text-decoration: none; color: var(--text); }
    .header-logo span { font-family: var(--ff-disp); font-size: 19px; letter-spacing: -0.02em; }
    .header-logo span em { color: var(--emerald); font-style: normal; }
    .header-right { display: flex; align-items: center; gap: 20px; }
    .hstat { font-size: 13px; color: var(--text-dim); }
    .hstat strong { color: var(--text); }
    .logout-link { font-size: 13px; color: var(--text-muted); text-decoration: none; padding: 5px 10px; border: 1px solid var(--border); border-radius: 6px; transition: all .15s; }
    .logout-link:hover { color: var(--red); border-color: var(--red); }

    /* ── CONTAINER ── */
    .container { max-width: 860px; margin: 0 auto; padding: 28px 20px; }

    /* ── ADD FORM ── */
    .add-form { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; padding: 18px 20px; margin-bottom: 22px; display: flex; gap: 10px; flex-wrap: wrap; }
    .add-form input[type="text"] { flex: 1; min-width: 180px; padding: 9px 14px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--ff-body); font-size: 14.5px; color: var(--text); background: var(--bg); outline: none; transition: border-color .15s; }
    .add-form input:focus { border-color: var(--emerald); }
    .add-form select { padding: 9px 12px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--ff-body); font-size: 14px; color: var(--text); background: var(--bg); outline: none; cursor: pointer; }
    .btn-add { padding: 9px 20px; background: var(--emerald); color: #fff; border: none; border-radius: 8px; font-family: var(--ff-body); font-size: 14.5px; font-weight: 500; cursor: pointer; transition: background .15s; white-space: nowrap; }
    .btn-add:hover { background: var(--emerald-d); }

    /* ── FILTERS ── */
    .filters { display: flex; gap: 7px; flex-wrap: wrap; margin-bottom: 18px; align-items: center; }
    .filters-label { font-size: 12px; font-weight: 500; color: var(--text-muted); text-transform: uppercase; letter-spacing: .06em; }
    .f-btn { padding: 5px 12px; border: 1px solid var(--border); border-radius: 20px; font-family: var(--ff-body); font-size: 13px; color: var(--text-dim); background: var(--bg-card); cursor: pointer; transition: all .15s; }
    .f-btn:hover { background: var(--bg-2); }
    .f-btn.active { background: var(--text); color: #fff; border-color: var(--text); }
    .sep { width: 1px; height: 16px; background: var(--border); }

    /* ── TASK CARD ── */
    .tasks { display: flex; flex-direction: column; gap: 10px; }
    .task-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; overflow: hidden; transition: box-shadow .15s; }
    .task-card:hover { box-shadow: 0 2px 12px rgba(0,0,0,0.07); }
    .task-card.is-done { opacity: .52; }
    .task-card.is-done .task-title { text-decoration: line-through; color: var(--text-muted); }
    .task-card[data-urgent="high"]   { border-left: 3px solid var(--red); }
    .task-card[data-urgent="medium"] { border-left: 3px solid var(--amber); }
    .task-card[data-urgent="low"]    { border-left: 3px solid var(--emerald); }
    .task-card.filtered-out { display: none; }

    .task-main { display: flex; align-items: center; gap: 12px; padding: 13px 16px; }
    .done-btn { flex-shrink: 0; width: 26px; height: 26px; border-radius: 50%; border: 2px solid var(--border); background: transparent; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all .15s; }
    .done-btn:hover { border-color: var(--emerald); }
    .done-btn.done { background: var(--emerald); border-color: var(--emerald); }
    .done-btn .material-icons { font-size: 15px; color: #fff; display: none; }
    .done-btn.done .material-icons { display: block; }
    .task-body { flex: 1; min-width: 0; }
    .task-title { font-size: 14.5px; line-height: 1.45; margin-bottom: 5px; }
    .task-meta { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }

    .badge-urgent { padding: 3px 9px; border-radius: 20px; font-size: 11.5px; font-weight: 500; cursor: pointer; border: none; font-family: var(--ff-body); transition: opacity .15s; }
    .badge-urgent:hover { opacity: .8; }
    .badge-urgent[data-level="high"]   { background: var(--red-bg);    color: var(--red); }
    .badge-urgent[data-level="medium"] { background: var(--amber-bg);  color: var(--amber); }
    .badge-urgent[data-level="low"]    { background: var(--emerald-bg);color: var(--emerald); }
    .badge-cat { padding: 3px 9px; border-radius: 20px; font-size: 11.5px; font-weight: 500; background: var(--bg-2); color: var(--text-dim); }

    .task-actions { display: flex; gap: 4px; flex-shrink: 0; }
    .icon-btn { width: 32px; height: 32px; border: none; background: transparent; cursor: pointer; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: var(--text-muted); transition: all .15s; }
    .icon-btn:hover { background: var(--bg-2); color: var(--text); }
    .icon-btn.del-btn:hover { background: #fef2f2; color: var(--red); }
    .icon-btn.notes-open { color: var(--emerald); }
    .icon-btn .material-icons { font-size: 18px; }

    /* ── NOTES PANEL ── */
    .notes-panel { overflow: hidden; max-height: 0; transition: max-height .25s ease; }
    .notes-panel.open { max-height: 220px; }
    .notes-inner { padding: 0 16px 14px 54px; }
    .notes-ta { width: 100%; min-height: 74px; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--ff-body); font-size: 13.5px; color: var(--text); background: var(--bg); resize: vertical; outline: none; line-height: 1.5; transition: border-color .15s; }
    .notes-ta:focus { border-color: var(--emerald); }
    .notes-hint { font-size: 11.5px; color: var(--text-muted); margin-top: 5px; }

    /* ── EMPTY ── */
    .empty { text-align: center; padding: 60px 20px; color: var(--text-muted); display: none; }
    .empty .material-icons { font-size: 40px; display: block; margin-bottom: 10px; }

    @media (max-width: 600px) {
      .hstat { display: none; }
      .add-form { gap: 8px; }
      .notes-inner { padding-left: 16px; }
    }
  </style>
</head>
<body>

<?php if ($showLogin): ?>
<!-- ── LOGIN VIEW ── -->
<div class="login-wrap">
  <div class="login-card">
    <a class="login-logo" href="/">
      <svg width="28" height="28" viewBox="0 0 26 26" fill="none">
        <circle cx="13" cy="13" r="12" stroke="#1a1612" stroke-width="1"/>
        <path d="M7 13C7 9.686 9.686 7 13 7s6 2.686 6 6-2.686 6-6 6" stroke="#16a34a" stroke-width="1.5" stroke-linecap="round"/>
        <circle cx="13" cy="13" r="2" fill="#16a34a"/>
      </svg>
      <span>eco<em>list</em></span>
    </a>
    <h1 class="login-title">Team Checklist</h1>
    <p class="login-sub">Internal access only</p>
    <?php if ($loginError): ?><div class="err-box"><?= esc($loginError) ?></div><?php endif; ?>
    <form method="POST" action="/ecolist/login">
      <div class="field"><label>Login</label><input type="text" name="user" autocomplete="username" required></div>
      <div class="field"><label>Password</label><input type="password" name="pass" autocomplete="current-password" required></div>
      <button type="submit" class="btn-login">Enter →</button>
    </form>
  </div>
</div>

<?php else: ?>
<!-- ── CHECKLIST VIEW ── -->
<header class="header">
  <a class="header-logo" href="/ecolist/">
    <svg width="24" height="24" viewBox="0 0 26 26" fill="none">
      <circle cx="13" cy="13" r="12" stroke="#1a1612" stroke-width="1"/>
      <path d="M7 13C7 9.686 9.686 7 13 7s6 2.686 6 6-2.686 6-6 6" stroke="#16a34a" stroke-width="1.5" stroke-linecap="round"/>
      <circle cx="13" cy="13" r="2" fill="#16a34a"/>
    </svg>
    <span>eco<em>list</em></span>
  </a>
  <div class="header-right">
    <span class="hstat"><strong id="statTotal"><?= count($tasks) ?></strong> tasks</span>
    <span class="hstat"><strong id="statDone"><?= count(array_filter($tasks, fn($t) => $t['done'])) ?></strong> done</span>
    <a class="logout-link" href="/ecolist/logout">Logout</a>
  </div>
</header>

<div class="container">
  <!-- Add task -->
  <div class="add-form">
    <input type="text" id="newTitle" placeholder="New task title…">
    <select id="newCat">
      <option>Admin</option>
      <option>IT</option>
      <option>Back Office</option>
      <option>Finances</option>
      <option>General</option>
    </select>
    <button class="btn-add" onclick="addTask()">+ Add Task</button>
  </div>

  <!-- Filters -->
  <div class="filters">
    <span class="filters-label">Filter:</span>
    <button class="f-btn active" data-f="all">All</button>
    <button class="f-btn" data-f="pending">Pending</button>
    <button class="f-btn" data-f="done">Done</button>
    <button class="f-btn" data-f="urgent-high">🔴 Very Urgent</button>
    <button class="f-btn" data-f="urgent-medium">🟡 Urgent</button>
    <span class="sep"></span>
    <button class="f-btn" data-f="cat-Admin">Admin</button>
    <button class="f-btn" data-f="cat-IT">IT</button>
    <button class="f-btn" data-f="cat-Back Office">Back Office</button>
    <button class="f-btn" data-f="cat-Finances">Finances</button>
  </div>

  <!-- Tasks -->
  <div class="tasks" id="taskList">
    <?php foreach ($tasks as $t):
      $doneClass = $t['done'] ? 'is-done' : '';
      $notesOpen = !empty($t['notes']) ? 'open' : '';
    ?>
    <div class="task-card <?= $doneClass ?>" data-id="<?= esc($t['id']) ?>" data-urgent="<?= esc($t['urgent']) ?>" data-cat="<?= esc($t['category']) ?>" data-done="<?= $t['done'] ? '1' : '0' ?>">
      <div class="task-main">
        <button class="done-btn <?= $t['done'] ? 'done' : '' ?>" onclick="toggleDone(this)">
          <span class="material-icons">check</span>
        </button>
        <div class="task-body">
          <div class="task-title"><?= esc($t['title']) ?></div>
          <div class="task-meta">
            <button class="badge-urgent" data-level="<?= esc($t['urgent']) ?>" onclick="cycleUrgent(this)">
              <?= $t['urgent'] === 'high' ? '🔴 Very Urgent' : ($t['urgent'] === 'medium' ? '🟡 Urgent' : '🟢 Not Urgent') ?>
            </button>
            <span class="badge-cat"><?= esc($t['category']) ?></span>
          </div>
        </div>
        <div class="task-actions">
          <button class="icon-btn <?= $notesOpen ? 'notes-open' : '' ?>" onclick="toggleNotes(this)" title="Notes">
            <span class="material-icons">notes</span>
          </button>
          <button class="icon-btn del-btn" onclick="deleteTask(this)" title="Delete">
            <span class="material-icons">delete_outline</span>
          </button>
        </div>
      </div>
      <div class="notes-panel <?= $notesOpen ?>">
        <div class="notes-inner">
          <textarea class="notes-ta" placeholder="Notes or explanation…" onblur="saveNotes(this)"><?= esc($t['notes'] ?? '') ?></textarea>
          <div class="notes-hint">Auto-saves on blur</div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <div class="empty" id="emptyMsg">
    <span class="material-icons">checklist</span>
    <p>No tasks match this filter.</p>
  </div>
</div>

<script>
const API = '/ecolist/api';
let activeFilter = 'all';

async function api(method, id, body) {
  const url = id ? API + '/' + id : API;
  const r = await fetch(url, {
    method,
    headers: body ? { 'Content-Type': 'application/json' } : {},
    body: body ? JSON.stringify(body) : undefined
  });
  return r.ok ? r.json() : null;
}

// ── Done toggle ───────────────────────────────────────────────────────────────
function toggleDone(btn) {
  const card = btn.closest('.task-card');
  const now = card.dataset.done !== '1';
  card.dataset.done = now ? '1' : '0';
  card.classList.toggle('is-done', now);
  btn.classList.toggle('done', now);
  api('PUT', card.dataset.id, { done: now });
  updateStats(); applyFilter();
}

// ── Urgency cycle ─────────────────────────────────────────────────────────────
const URGENCY = [
  { level: 'high',   label: '🔴 Very Urgent' },
  { level: 'medium', label: '🟡 Urgent' },
  { level: 'low',    label: '🟢 Not Urgent' },
];
function cycleUrgent(btn) {
  const card = btn.closest('.task-card');
  const cur  = URGENCY.findIndex(u => u.level === btn.dataset.level);
  const next = URGENCY[(cur + 1) % URGENCY.length];
  btn.dataset.level = next.level;
  btn.textContent   = next.label;
  card.dataset.urgent = next.level;
  api('PUT', card.dataset.id, { urgent: next.level });
}

// ── Notes toggle ──────────────────────────────────────────────────────────────
function toggleNotes(btn) {
  const card  = btn.closest('.task-card');
  const panel = card.querySelector('.notes-panel');
  const open  = panel.classList.toggle('open');
  btn.classList.toggle('notes-open', open);
  if (open) card.querySelector('.notes-ta').focus();
}
function saveNotes(ta) {
  const card = ta.closest('.task-card');
  api('PUT', card.dataset.id, { notes: ta.value });
}

// ── Delete ────────────────────────────────────────────────────────────────────
async function deleteTask(btn) {
  if (!confirm('Delete this task?')) return;
  const card = btn.closest('.task-card');
  const ok = await api('DELETE', card.dataset.id);
  if (ok) { card.remove(); updateStats(); applyFilter(); }
}

// ── Add task ──────────────────────────────────────────────────────────────────
async function addTask() {
  const title = document.getElementById('newTitle').value.trim();
  if (!title) { document.getElementById('newTitle').focus(); return; }
  const category = document.getElementById('newCat').value;
  const task = await api('POST', null, { title, category });
  if (!task) return;
  document.getElementById('newTitle').value = '';
  document.getElementById('taskList').insertAdjacentHTML('beforeend', makeCard(task));
  updateStats(); applyFilter();
}
document.getElementById('newTitle').addEventListener('keydown', e => { if (e.key === 'Enter') addTask(); });

function esc(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function makeCard(t) {
  return `<div class="task-card" data-id="${esc(t.id)}" data-urgent="low" data-cat="${esc(t.category)}" data-done="0">
    <div class="task-main">
      <button class="done-btn" onclick="toggleDone(this)"><span class="material-icons">check</span></button>
      <div class="task-body">
        <div class="task-title">${esc(t.title)}</div>
        <div class="task-meta">
          <button class="badge-urgent" data-level="low" onclick="cycleUrgent(this)">🟢 Not Urgent</button>
          <span class="badge-cat">${esc(t.category)}</span>
        </div>
      </div>
      <div class="task-actions">
        <button class="icon-btn" onclick="toggleNotes(this)"><span class="material-icons">notes</span></button>
        <button class="icon-btn del-btn" onclick="deleteTask(this)"><span class="material-icons">delete_outline</span></button>
      </div>
    </div>
    <div class="notes-panel"><div class="notes-inner">
      <textarea class="notes-ta" placeholder="Notes or explanation…" onblur="saveNotes(this)"></textarea>
      <div class="notes-hint">Auto-saves on blur</div>
    </div></div>
  </div>`;
}

// ── Filters ───────────────────────────────────────────────────────────────────
document.querySelectorAll('.f-btn').forEach(btn => btn.addEventListener('click', () => {
  document.querySelectorAll('.f-btn').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  activeFilter = btn.dataset.f;
  applyFilter();
}));

function applyFilter() {
  let visible = 0;
  document.querySelectorAll('.task-card').forEach(c => {
    const f = activeFilter;
    let show = true;
    if      (f === 'pending')       show = c.dataset.done !== '1';
    else if (f === 'done')          show = c.dataset.done === '1';
    else if (f === 'urgent-high')   show = c.dataset.urgent === 'high'   && c.dataset.done !== '1';
    else if (f === 'urgent-medium') show = c.dataset.urgent === 'medium' && c.dataset.done !== '1';
    else if (f.startsWith('cat-'))  show = c.dataset.cat === f.slice(4);
    c.classList.toggle('filtered-out', !show);
    if (show) visible++;
  });
  document.getElementById('emptyMsg').style.display = visible === 0 ? 'block' : 'none';
}

function updateStats() {
  document.getElementById('statTotal').textContent = document.querySelectorAll('.task-card').length;
  document.getElementById('statDone').textContent  = document.querySelectorAll('.task-card.is-done').length;
}

applyFilter();
</script>
<?php endif; ?>
</body>
</html>
