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

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

    if ($action === 'add') {
        $title   = sanitize($_POST['title'] ?? '');
        $type    = sanitize($_POST['type'] ?? 'custom');
        $target  = (float)($_POST['target_value'] ?? 0);
        $unit    = sanitize($_POST['unit'] ?? '');
        $subId   = (int)($_POST['subject_id'] ?? 0) ?: null;
        $deadline= sanitize($_POST['deadline'] ?? '') ?: null;
        if (!$title)    jsonResponse(['success'=>false,'message'=>'Please enter a goal title.']);
        if ($target<=0) jsonResponse(['success'=>false,'message'=>'Target must be greater than 0.']);
        $pdo->prepare("INSERT INTO goals (user_id,subject_id,title,type,target_value,unit,deadline) VALUES (?,?,?,?,?,?,?)")
            ->execute([$uid,$subId,$title,$type,$target,$unit,$deadline]);
        checkGoalAchievement($pdo, $uid);
        jsonResponse(['success'=>true,'message'=>'Goal created!']);
    }

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

    if ($action === 'update_progress') {
        $id  = (int)($_POST['id'] ?? 0);
        $val = (float)($_POST['value'] ?? 0);
        $pdo->prepare("UPDATE goals SET current_value=? WHERE id=? AND user_id=?")->execute([$val,$id,$uid]);
        $pdo->prepare("UPDATE goals SET status='completed' WHERE id=? AND user_id=? AND current_value>=target_value AND status='active'")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }

    jsonResponse(['success'=>false]);
}

function checkGoalAchievement($pdo, $uid) {
    $cnt = $pdo->prepare("SELECT COUNT(*) FROM goals WHERE user_id=?");
    $cnt->execute([$uid]);
    if ($cnt->fetchColumn() >= 1) awardAchievement($pdo, $uid, 'first_goal');
}
function awardAchievement($pdo, $uid, $key) {
    $ach = $pdo->prepare("SELECT id FROM achievement_defs WHERE `key`=?");
    $ach->execute([$key]); $row = $ach->fetch();
    if (!$row) return;
    try {
        $pdo->prepare("INSERT IGNORE INTO user_achievements (user_id,achievement_id) VALUES (?,?)")->execute([$uid,$row['id']]);
        $pdo->prepare("UPDATE users SET xp_points = xp_points + (SELECT xp_reward FROM achievement_defs WHERE id=?) WHERE id=?")->execute([$row['id'],$uid]);
    } catch(Exception $e){}
}

function autoUpdateGoals($pdo, $uid) {
    $goals = $pdo->prepare("SELECT * FROM goals WHERE user_id=? AND status='active'");
    $goals->execute([$uid]);
    foreach ($goals->fetchAll() as $g) {
        $cur = 0;
        if ($g['type'] === 'study_hours') {
            $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0)/60 FROM study_sessions WHERE user_id=?" . ($g['subject_id'] ? " AND subject_id=?" : ""));
            $p = [$uid]; if ($g['subject_id']) $p[] = $g['subject_id'];
            $q->execute($p); $cur = round($q->fetchColumn(), 1);
        } elseif ($g['type'] === 'mark_target') {
            $q = $pdo->prepare("SELECT COALESCE(AVG(marks_obtained/total_marks*100),0) FROM marks WHERE user_id=?" . ($g['subject_id'] ? " AND subject_id=?" : ""));
            $p = [$uid]; if ($g['subject_id']) $p[] = $g['subject_id'];
            $q->execute($p); $cur = round($q->fetchColumn(), 1);
        } elseif ($g['type'] === 'streak') {
            $q = $pdo->prepare("SELECT COUNT(*) FROM study_streaks WHERE user_id=?"); $q->execute([$uid]); $cur = (int)$q->fetchColumn();
        }
        if ($cur > 0) {
            $pdo->prepare("UPDATE goals SET current_value=? WHERE id=?")->execute([$cur, $g['id']]);
            if ($cur >= $g['target_value']) $pdo->prepare("UPDATE goals SET status='completed' WHERE id=?")->execute([$g['id']]);
        }
    }
}

autoUpdateGoals($pdo, $uid);

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

$goals = $pdo->prepare("
    SELECT g.*, s.name as subject_name, s.color as subject_color
    FROM goals g LEFT JOIN subjects s ON g.subject_id=s.id
    WHERE g.user_id=? ORDER BY g.status ASC, g.created_at DESC
");
$goals->execute([$uid]); $goals = $goals->fetchAll();

$active    = array_values(array_filter($goals, fn($g) => $g['status'] === 'active'));
$completed = array_values(array_filter($goals, fn($g) => $g['status'] === 'completed'));

// Avg progress
$totalPct = 0; $pCnt = 0;
foreach ($active as $g) {
    if ($g['target_value'] > 0) { $totalPct += min(100, ($g['current_value']/$g['target_value'])*100); $pCnt++; }
}
$avgPct = $pCnt ? round($totalPct/$pCnt) : 0;

// Type config
$typeConfig = [
    'study_hours' => ['icon'=>'📚','label'=>'Study Hours',  'color'=>'rgba(99,102,241,.15)',  'accent'=>'#818cf8'],
    'mark_target' => ['icon'=>'📊','label'=>'Mark Target',  'color'=>'rgba(52,211,153,.15)',  'accent'=>'#34d399'],
    'streak'      => ['icon'=>'🔥','label'=>'Study Streak', 'color'=>'rgba(249,115,22,.15)',  'accent'=>'#fb923c'],
    'custom'      => ['icon'=>'✏️','label'=>'Custom Goal',  'color'=>'rgba(139,92,246,.15)',  'accent'=>'#a78bfa'],
];

require_once 'includes/header.php';
renderHeader('Goals', 'goals');
?>

<style>
/* ── Goal card ──────────────────────────────────────────── */
.gl-list { display: flex; flex-direction: column; gap: 12px; }

.gl-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  padding: 18px 20px;
  transition: border-color .18s, transform .18s, box-shadow .18s;
  animation: glIn .25s ease both;
  position: relative;
  overflow: hidden;
}
.gl-card::before {
  content: '';
  position: absolute;
  left: 0; top: 0; bottom: 0;
  width: 3px;
  border-radius: 99px 0 0 99px;
}
.gl-card:hover {
  border-color: var(--border-light);
  transform: translateX(2px);
  box-shadow: var(--shadow);
}
@keyframes glIn {
  from { opacity:0; transform:translateY(8px); }
  to   { opacity:1; transform:translateY(0); }
}

/* card top row */
.gl-card-top {
  display: flex;
  align-items: flex-start;
  gap: 14px;
  margin-bottom: 14px;
}
.gl-type-icon {
  width: 40px; height: 40px;
  border-radius: 11px;
  display: flex; align-items: center; justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}
.gl-info { flex: 1; min-width: 0; }
.gl-title {
  font-size: 15px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.gl-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}
.gl-meta-chip {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 11px;
  font-weight: 600;
  color: var(--text-muted);
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 99px;
  padding: 2px 9px;
}
.gl-pct {
  font-size: 22px;
  font-weight: 800;
  font-family: 'Sora', sans-serif;
  line-height: 1;
  flex-shrink: 0;
  text-align: right;
}
.gl-pct-sub {
  font-size: 11px;
  color: var(--text-muted);
  text-align: right;
  margin-top: 2px;
}

/* progress bar */
.gl-bar-wrap { margin-bottom: 6px; }
.gl-bar-labels {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  font-size: 11px;
  color: var(--text-muted);
}
.gl-bar-cur { font-weight: 700; color: var(--text-secondary); }

/* actions row */
.gl-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
  gap: 10px;
}
.gl-deadline {
  font-size: 11px;
  color: var(--text-muted);
  display: flex;
  align-items: center;
  gap: 5px;
}
.gl-deadline.overdue { color: var(--danger); }
.gl-delete-btn {
  width: 28px; height: 28px;
  border-radius: 7px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  color: var(--text-muted);
  cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  transition: all .15s;
  flex-shrink: 0;
}
.gl-delete-btn:hover { border-color: rgba(239,68,68,.4); color: #ef4444; background: rgba(239,68,68,.08); }

/* ── Completed card ─────────────────────────────────────── */
.gl-done-card {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px 18px;
  background: rgba(16,185,129,.04);
  border: 1px solid rgba(16,185,129,.2);
  border-radius: var(--radius-lg);
  animation: glIn .25s ease both;
  transition: all .18s;
}
.gl-done-card:hover { background: rgba(16,185,129,.07); border-color: rgba(16,185,129,.3); }
.gl-done-check {
  width: 36px; height: 36px;
  border-radius: 50%;
  background: rgba(16,185,129,.15);
  border: 1.5px solid rgba(16,185,129,.4);
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
  color: var(--success);
}
.gl-done-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}
.gl-done-sub {
  font-size: 11px;
  color: var(--text-muted);
  margin-top: 3px;
}
.gl-done-badge {
  font-size: 11px;
  font-weight: 700;
  background: rgba(16,185,129,.15);
  color: var(--success);
  border: 1px solid rgba(16,185,129,.3);
  border-radius: 99px;
  padding: 3px 10px;
  flex-shrink: 0;
}

/* ── Section label ──────────────────────────────────────── */
.gl-section-label {
  font-size: 11px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 1px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.gl-section-label::after {
  content: '';
  flex: 1;
  height: 1px;
  background: var(--border);
}

/* ── Quick preset buttons ───────────────────────────────── */
.gl-presets {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}
.gl-preset {
  padding: 6px 14px;
  border-radius: 99px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  color: var(--text-secondary);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all .15s;
  font-family: inherit;
}
.gl-preset:hover { border-color: var(--accent); color: var(--accent); background: rgba(99,102,241,.07); }
.gl-preset.active-preset { border-color: var(--accent); color: var(--accent); background: rgba(99,102,241,.12); }
</style>

<!-- Page Header -->
<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:24px;flex-wrap:wrap">
  <div>
    <div style="font-size:22px;font-weight:800;color:var(--text-primary);font-family:'Sora',sans-serif;letter-spacing:-.3px">
      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="color:var(--accent);margin-right:8px;vertical-align:-3px"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>
      Study Goals
    </div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:4px"><?= count($active) ?> active · <?= count($completed) ?> completed</div>
  </div>
  <button class="btn btn-primary" onclick="openModal('goalModal')">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:6px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    New Goal
  </button>
</div>

<!-- Stats -->
<div class="stats-grid" style="margin-bottom:22px">
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(99,102,241,.12)">🎯</div>
    <div class="stat-value"><?= count($active) ?></div>
    <div class="stat-label">Active Goals</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(16,185,129,.12)">✅</div>
    <div class="stat-value"><?= count($completed) ?></div>
    <div class="stat-label">Completed</div>
  </div>
  <div class="stat-card">
    <div class="stat-icon" style="background:rgba(245,158,11,.12)">📊</div>
    <div class="stat-value"><?= $avgPct ?>%</div>
    <div class="stat-label">Avg Progress</div>
  </div>
</div>

<?php if (!$goals): ?>
<!-- Empty -->
<div class="card">
  <div class="empty-state">
    <div class="empty-icon">🎯</div>
    <h3>No goals yet</h3>
    <p>Set your first study goal to stay focused and motivated!</p>
    <button class="btn btn-primary" onclick="openModal('goalModal')" style="margin-top:18px">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:6px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
      Set your first goal
    </button>
  </div>
</div>
<?php endif; ?>

<?php if ($active): ?>
<!-- Active Goals -->
<div class="gl-section-label">🔥 Active Goals <span style="background:rgba(99,102,241,.12);color:var(--accent);border:1px solid rgba(99,102,241,.2);border-radius:99px;padding:1px 9px;font-size:10px"><?= count($active) ?></span></div>
<div class="gl-list" style="margin-bottom:24px">
  <?php foreach ($active as $i => $g):
    $pct      = $g['target_value'] > 0 ? min(100, round(($g['current_value']/$g['target_value'])*100)) : 0;
    $tc       = $typeConfig[$g['type']] ?? $typeConfig['custom'];
    $daysLeft = $g['deadline'] ? ceil((strtotime($g['deadline'])-time())/86400) : null;
    $barColor = $pct >= 100 ? 'var(--success)' : ($pct >= 60 ? 'var(--warning)' : ($pct >= 30 ? 'var(--accent)' : 'var(--danger)'));
    $pctColor = $pct >= 75 ? '#34d399' : ($pct >= 40 ? '#fbbf24' : '#818cf8');
  ?>
  <div class="gl-card" style="animation-delay:<?= $i*0.05 ?>s">
    <!-- left accent line color -->
    <style>.gl-card:nth-child(<?= $i+1 ?>)::before { background: <?= $tc['accent'] ?>; }</style>

    <div class="gl-card-top">
      <!-- Type icon -->
      <div class="gl-type-icon" style="background:<?= $tc['color'] ?>"><?= $tc['icon'] ?></div>

      <!-- Info -->
      <div class="gl-info">
        <div class="gl-title"><?= htmlspecialchars($g['title']) ?></div>
        <div class="gl-meta">
          <span class="gl-meta-chip" style="border-color:<?= $tc['accent'] ?>33;color:<?= $tc['accent'] ?>">
            <?= $tc['icon'] ?> <?= $tc['label'] ?>
          </span>
          <?php if ($g['subject_name']): ?>
          <span class="gl-meta-chip">
            <span style="width:7px;height:7px;border-radius:50%;background:<?= htmlspecialchars($g['subject_color']) ?>;display:inline-block"></span>
            <?= htmlspecialchars($g['subject_name']) ?>
          </span>
          <?php endif; ?>
        </div>
      </div>

      <!-- Percentage -->
      <div>
        <div class="gl-pct" style="color:<?= $pctColor ?>"><?= $pct ?>%</div>
        <div class="gl-pct-sub"><?= $g['current_value'] ?> / <?= $g['target_value'] ?> <?= htmlspecialchars($g['unit']) ?></div>
      </div>
    </div>

    <!-- Progress bar -->
    <div class="gl-bar-wrap">
      <div class="gl-bar-labels">
        <span class="gl-bar-cur"><?= $g['current_value'] ?> <?= htmlspecialchars($g['unit']) ?> reached</span>
        <span>Target: <?= $g['target_value'] ?> <?= htmlspecialchars($g['unit']) ?></span>
      </div>
      <div class="progress-bar" style="height:8px">
        <div class="progress-fill" style="width:<?= $pct ?>%;background:<?= $barColor ?>;transition:width .6s cubic-bezier(.4,0,.2,1)"></div>
      </div>
    </div>

    <!-- Actions -->
    <div class="gl-actions">
      <div class="gl-deadline <?= $daysLeft !== null && $daysLeft <= 0 ? 'overdue' : '' ?>">
        <?php if ($daysLeft !== null): ?>
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
        <?php if ($daysLeft > 0): ?>
          <?= $daysLeft ?> day<?= $daysLeft !== 1 ? 's' : '' ?> left
        <?php elseif ($daysLeft === 0): ?>
          Due today
        <?php else: ?>
          Overdue by <?= abs($daysLeft) ?> day<?= abs($daysLeft) !== 1 ? 's' : '' ?>
        <?php endif; ?>
        <?php else: ?>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
          No deadline
        <?php endif; ?>
      </div>
      <button class="gl-delete-btn" onclick="deleteGoal(<?= $g['id'] ?>)" title="Delete goal">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
      </button>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<?php if ($completed): ?>
<!-- Completed Goals -->
<div class="gl-section-label">✅ Completed Goals <span style="background:rgba(16,185,129,.12);color:var(--success);border:1px solid rgba(16,185,129,.2);border-radius:99px;padding:1px 9px;font-size:10px"><?= count($completed) ?></span></div>
<div class="gl-list">
  <?php foreach ($completed as $i => $g):
    $tc = $typeConfig[$g['type']] ?? $typeConfig['custom'];
  ?>
  <div class="gl-done-card" style="animation-delay:<?= $i*0.04 ?>s">
    <div class="gl-done-check">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg>
    </div>
    <div style="flex:1;min-width:0">
      <div class="gl-done-title"><?= htmlspecialchars($g['title']) ?></div>
      <div class="gl-done-sub">
        <?= $tc['icon'] ?> <?= $g['target_value'] ?> <?= htmlspecialchars($g['unit']) ?> achieved
        <?php if ($g['subject_name']): ?> · <?= htmlspecialchars($g['subject_name']) ?><?php endif; ?>
      </div>
    </div>
    <div class="gl-done-badge">✓ Done</div>
    <button class="gl-delete-btn" onclick="deleteGoal(<?= $g['id'] ?>)" title="Remove">
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
    </button>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ── Add Goal Modal ──────────────────────────────────────────── -->
<div class="modal-overlay" id="goalModal">
  <div class="modal" style="max-width:480px">
    <div class="modal-header">
      <span class="modal-title">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="margin-right:8px;vertical-align:-2px"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>
        New Study Goal
      </span>
      <button class="modal-close" onclick="closeModal('goalModal')">✕</button>
    </div>

    <!-- Quick preset goals -->
    <div style="margin-bottom:18px">
      <div style="font-size:11px;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px">Quick Presets</div>
      <div class="gl-presets">
        <button class="gl-preset" onclick="applyPreset('study_hours','Study 50 hours',50,'hours')">📚 50h Study</button>
        <button class="gl-preset" onclick="applyPreset('study_hours','Study 100 hours',100,'hours')">📚 100h Study</button>
        <button class="gl-preset" onclick="applyPreset('mark_target','Reach 75% Average',75,'%')">📊 75% Avg</button>
        <button class="gl-preset" onclick="applyPreset('mark_target','Reach 90% Average',90,'%')">📊 90% Avg</button>
        <button class="gl-preset" onclick="applyPreset('streak','7-Day Streak',7,'days')">🔥 7-Day Streak</button>
        <button class="gl-preset" onclick="applyPreset('streak','30-Day Streak',30,'days')">🔥 30-Day Streak</button>
      </div>
    </div>

    <div id="goalMsg" class="alert" style="display:none"></div>

    <div class="form-group">
      <label class="form-label">Goal Title <span style="color:var(--danger)">*</span></label>
      <input type="text" id="gTitle" class="form-control" placeholder="e.g. Study 50 hours this month">
    </div>

    <div class="form-group">
      <label class="form-label">Goal Type</label>
      <select id="gType" class="form-control" onchange="updateUnit()">
        <option value="study_hours">📚 Study Hours</option>
        <option value="mark_target">📊 Average Mark %</option>
        <option value="streak">🔥 Study Streak (days)</option>
        <option value="custom">✏️ Custom</option>
      </select>
    </div>

    <div class="form-grid-2">
      <div class="form-group">
        <label class="form-label">Target Value <span style="color:var(--danger)">*</span></label>
        <input type="number" id="gTarget" class="form-control" placeholder="e.g. 50" min="1" step="any">
      </div>
      <div class="form-group">
        <label class="form-label">Unit</label>
        <input type="text" id="gUnit" class="form-control" placeholder="hours" value="hours">
      </div>
    </div>

    <div class="form-grid-2">
      <div class="form-group">
        <label class="form-label">Subject <span style="color:var(--text-muted);font-weight:400">— optional</span></label>
        <select id="gSubject" class="form-control">
          <option value="">— All subjects —</option>
          <?php foreach ($subjects as $s): ?>
          <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Deadline <span style="color:var(--text-muted);font-weight:400">— optional</span></label>
        <input type="date" id="gDeadline" class="form-control" min="<?= date('Y-m-d') ?>">
      </div>
    </div>

    <button class="btn btn-primary btn-full" onclick="saveGoal()" id="goalSaveBtn" style="margin-top:4px">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:6px"><polyline points="20 6 9 17 4 12"/></svg>
      Create Goal
    </button>
  </div>
</div>

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

<script>
// ── Unit auto-fill ─────────────────────────────────────────────────
function updateUnit() {
  var units = { study_hours:'hours', mark_target:'%', streak:'days', custom:'' };
  document.getElementById('gUnit').value = units[document.getElementById('gType').value] || '';
}

// ── Quick preset fill ──────────────────────────────────────────────
function applyPreset(type, title, target, unit) {
  document.getElementById('gType').value   = type;
  document.getElementById('gTitle').value  = title;
  document.getElementById('gTarget').value = target;
  document.getElementById('gUnit').value   = unit;
  document.querySelectorAll('.gl-preset').forEach(b => b.classList.remove('active-preset'));
  event.target.classList.add('active-preset');
}

// ── Save goal ──────────────────────────────────────────────────────
async function saveGoal() {
  var title  = document.getElementById('gTitle').value.trim();
  var target = document.getElementById('gTarget').value;
  if (!title)  { showGoalMsg('Please enter a goal title.', 'error'); return; }
  if (!target || parseFloat(target) <= 0) { showGoalMsg('Target must be greater than 0.', 'error'); return; }

  var btn = document.getElementById('goalSaveBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Creating…';

  var fd = new FormData();
  fd.append('action',       'add');
  fd.append('title',        title);
  fd.append('type',         document.getElementById('gType').value);
  fd.append('target_value', target);
  fd.append('unit',         document.getElementById('gUnit').value);
  fd.append('subject_id',   document.getElementById('gSubject').value);
  fd.append('deadline',     document.getElementById('gDeadline').value);

  try {
    var res  = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd });
    var data = await res.json();
    if (data.success) {
      showGoalMsg(data.message, 'success');
      btn.innerHTML = '✓ Created!';
      setTimeout(() => { closeModal('goalModal'); location.reload(); }, 800);
    } else {
      showGoalMsg(data.message, 'error');
      btn.disabled = false;
      btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:6px"><polyline points="20 6 9 17 4 12"/></svg>Create Goal';
    }
  } catch(e) {
    showGoalMsg('Connection error. Try again.', 'error');
    btn.disabled = false;
    btn.innerHTML = 'Create Goal';
  }
}

function showGoalMsg(msg, type) {
  var el = document.getElementById('goalMsg');
  el.className = 'alert alert-' + (type === 'error' ? 'error' : 'success');
  el.innerHTML = (type === 'error' ? '⚠️ ' : '✅ ') + msg;
  el.style.display = 'flex';
}

// ── Delete goal ────────────────────────────────────────────────────
async function deleteGoal(id) {
  if (!(await stConfirm('Delete this goal?'))) return;
  var fd = new FormData();
  fd.append('action', 'delete');
  fd.append('id', id);
  await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd });
  // Animate out
  var cards = document.querySelectorAll('.gl-card, .gl-done-card');
  cards.forEach(function(card) {
    if (card.querySelector('[onclick*="deleteGoal(' + id + ')"]')) {
      card.style.transition = 'opacity .25s, transform .25s';
      card.style.opacity = '0';
      card.style.transform = 'translateX(20px)';
      setTimeout(function() { location.reload(); }, 280);
    }
  });
}

// spinner
var _s = document.createElement('style');
_s.textContent = '.spinner{display:inline-block;width:13px;height:13px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:_sp .65s linear infinite;vertical-align:middle}@keyframes _sp{to{transform:rotate(360deg)}}';
document.head.appendChild(_s);

// Enter key on title
document.getElementById('gTitle').addEventListener('keydown', function(e) {
  if (e.key === 'Enter') saveGoal();
});
</script>