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

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

    if ($action === 'add') {
        $subjectId = (int)($_POST['subject_id'] ?? 0);
        $classDate = $_POST['class_date'] ?? date('Y-m-d');
        $startTime = $_POST['start_time'] ?? '';
        $endTime   = $_POST['end_time'] ?? '';
        $classType = $_POST['class_type'] ?? 'regular';
        $notes     = sanitize($_POST['notes'] ?? '');
        $attended  = isset($_POST['attended']) ? (int)$_POST['attended'] : 1;

        if (!$subjectId || !$classDate || !$startTime || !$endTime)
            jsonResponse(['success' => false, 'message' => 'Please fill in all required fields.']);

        $duration = 0;
        $s = strtotime($startTime); $e = strtotime($endTime);
        if ($e > $s) $duration = (int)(($e - $s) / 60);
        if ($duration <= 0)
            jsonResponse(['success' => false, 'message' => 'End time must be after start time.']);

        $stmt = $pdo->prepare("INSERT INTO class_hours (user_id,subject_id,class_date,start_time,end_time,duration_minutes,class_type,notes,attended) VALUES (?,?,?,?,?,?,?,?,?)");
        $stmt->execute([$uid, $subjectId, $classDate, $startTime, $endTime, $duration, $classType, $notes, $attended]);
        jsonResponse(['success' => true, 'message' => 'Class logged!', 'id' => $pdo->lastInsertId()]);
    }

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

    if ($action === 'toggle_attend') {
        $pdo->prepare("UPDATE class_hours SET attended = NOT attended WHERE id=? AND user_id=?")->execute([(int)($_POST['id']??0), $uid]);
        jsonResponse(['success' => true]);
    }

    if ($action === 'add_slot') {
        $subId = (int)($_POST['subject_id'] ?? 0) ?: null;
        $day   = sanitize($_POST['day'] ?? '');
        $start = sanitize($_POST['start_time'] ?? '');
        $end   = sanitize($_POST['end_time'] ?? '');
        $label = sanitize($_POST['label'] ?? '');
        $color = sanitize($_POST['color'] ?? '#38bdf8');

        $validDays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
        if (!in_array($day, $validDays)) jsonResponse(['success'=>false,'message'=>'Invalid day.']);
        if (!$start || !$end)           jsonResponse(['success'=>false,'message'=>'Please set start and end time.']);
        if ($start >= $end)             jsonResponse(['success'=>false,'message'=>'End time must be after start time.']);

        $stmt = $pdo->prepare("INSERT INTO timetable (user_id,subject_id,day_of_week,start_time,end_time,label,color) VALUES (?,?,?,?,?,?,?)");
        $stmt->execute([$uid,$subId,$day,$start,$end,$label,$color]);
        jsonResponse(['success'=>true,'message'=>'Class added to schedule!','id'=>$pdo->lastInsertId()]);
    }

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

// ── FILTERS ───────────────────────────────────────────────────────
$period        = $_GET['period'] ?? 'month';
$subjectFilter = (int)($_GET['subject'] ?? 0);

$dateSQL    = match($period) {
    'today' => 'AND ch.class_date = CURDATE()',
    'week'  => 'AND ch.class_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)',
    'month' => 'AND ch.class_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)',
    default => ''
};
$subjectSQL = $subjectFilter ? "AND ch.subject_id = $subjectFilter" : '';

// ── DATA ──────────────────────────────────────────────────────────
$classesQ = $pdo->prepare("
    SELECT ch.*, s.name as subject_name, s.color as subject_color
    FROM class_hours ch
    JOIN subjects s ON ch.subject_id = s.id
    WHERE ch.user_id = ? $dateSQL $subjectSQL
    ORDER BY ch.class_date DESC, ch.start_time DESC
");
$classesQ->execute([$uid]);
$classes = $classesQ->fetchAll();

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

$totalMins     = array_sum(array_column($classes, 'duration_minutes'));
$totalClasses  = count($classes);
$attendedCount = count(array_filter($classes, fn($c) => $c['attended']));
$attendedMins  = array_sum(array_map(fn($c) => $c['attended'] ? $c['duration_minutes'] : 0, $classes));
$missedCount   = $totalClasses - $attendedCount;
$attendRate    = $totalClasses > 0 ? round(($attendedCount / $totalClasses) * 100) : 0;

// Subject-wise summary
$subStatsQ = $pdo->prepare("
    SELECT s.name, s.color, s.id,
           COUNT(ch.id) as total_classes,
           SUM(ch.attended) as attended_classes,
           COALESCE(SUM(ch.duration_minutes),0) as total_mins,
           COALESCE(SUM(CASE WHEN ch.attended=1 THEN ch.duration_minutes ELSE 0 END),0) as attended_mins
    FROM subjects s
    LEFT JOIN class_hours ch ON s.id = ch.subject_id AND ch.user_id = ?
    WHERE s.user_id = ?
    GROUP BY s.id
    HAVING total_classes > 0
    ORDER BY total_mins DESC
");
$subStatsQ->execute([$uid, $uid]);
$subStats = $subStatsQ->fetchAll();

// ── TIMETABLE DATA ─────────────────────────────────────────────────
$slotsQ = $pdo->prepare("
    SELECT t.*, s.name as subject_name, s.color as subject_color
    FROM timetable t
    LEFT JOIN subjects s ON t.subject_id = s.id
    WHERE t.user_id = ? AND t.is_active = 1
    ORDER BY FIELD(t.day_of_week,'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'), t.start_time
");
$slotsQ->execute([$uid]);
$allSlots = $slotsQ->fetchAll();

$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$slotsByDay = array_fill_keys($days, []);
foreach ($allSlots as $sl) $slotsByDay[$sl['day_of_week']][] = $sl;

$todayDay = date('l');

require_once 'includes/header.php';
renderHeader('Class Hours', 'class-hours');
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800;900&family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap');

:root {
  --ch-df: 'Outfit', sans-serif;
  --ch-db: 'Plus Jakarta Sans', sans-serif;
  --ch-r: 16px;
  --ch-lg: 22px;
  --ch-xl: 28px;
  --ch-g: 16px;
}

.chp { font-family: var(--ch-db); padding-bottom: 48px; max-width: 1280px; }

/* ── Stats ── */
.ch-stats { display:grid; grid-template-columns:repeat(4,1fr); gap:var(--ch-g); margin-bottom:var(--ch-g); }
@media(max-width:900px){ .ch-stats { grid-template-columns:repeat(2,1fr); } }

.ch-st {
  background:var(--bg-card); border:1px solid var(--border); border-radius:var(--ch-lg);
  padding:22px 22px 18px; position:relative; overflow:hidden;
  transition:transform .2s,box-shadow .2s,border-color .2s;
  animation:ch-rise .5s ease both; cursor:default;
}
.ch-st:nth-child(1){animation-delay:.10s} .ch-st:nth-child(2){animation-delay:.15s}
.ch-st:nth-child(3){animation-delay:.20s} .ch-st:nth-child(4){animation-delay:.25s}
.ch-st:hover { transform:translateY(-4px); box-shadow:0 16px 40px rgba(0,0,0,.2); border-color:var(--border-light); }
.ch-st::before { content:''; position:absolute; width:120px; height:120px; border-radius:50%; top:-30px; right:-30px; pointer-events:none; }
.ch-st1::before{background:rgba(99,102,241,.16)} .ch-st2::before{background:rgba(6,182,212,.14)}
.ch-st3::before{background:rgba(16,185,129,.14)} .ch-st4::before{background:rgba(239,68,68,.14)}
.ch-st::after { content:''; position:absolute; bottom:0; left:0; right:0; height:2px; opacity:0; transition:opacity .2s; }
.ch-st:hover::after{opacity:1}
.ch-st1::after{background:linear-gradient(90deg,#6366f1,#a855f7)}
.ch-st2::after{background:linear-gradient(90deg,#06b6d4,#6366f1)}
.ch-st3::after{background:linear-gradient(90deg,#10b981,#06b6d4)}
.ch-st4::after{background:linear-gradient(90deg,#ef4444,#f59e0b)}

.ch-sth { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:16px; }
.ch-sti { width:42px; height:42px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:19px; }
.ch-stag { font-size:11px; font-weight:700; padding:3px 9px; border-radius:99px; }
.tg{background:rgba(16,185,129,.12);color:#10b981;} .ta{background:rgba(245,158,11,.12);color:#f59e0b;}
.tr{background:rgba(239,68,68,.12);color:#ef4444;} .tc{background:rgba(6,182,212,.12);color:#06b6d4;}
.ch-stv { font-family:var(--ch-df); font-size:30px; font-weight:800; color:var(--text-primary); line-height:1; letter-spacing:-.5px; }
.ch-stv .du { font-size:14px; color:var(--text-muted); font-weight:500; font-family:var(--ch-db); }
.ch-stl { font-size:12px; color:var(--text-muted); margin-top:6px; font-weight:500; }

/* ── Card ── */
.ch-card {
  background:var(--bg-card); border:1px solid var(--border); border-radius:var(--ch-lg);
  padding:22px; margin-bottom:var(--ch-g); animation:ch-rise .5s ease both;
}
.ch-card-hd { display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; gap:12px; flex-wrap:wrap; }
.ch-card-t { font-family:var(--ch-df); font-size:15px; font-weight:700; color:var(--text-primary); letter-spacing:-.2px; display:flex; align-items:center; gap:8px; }
.ch-card-l { font-size:12px; font-weight:600; color:var(--accent); text-decoration:none; padding:5px 12px; border-radius:8px; border:1px solid rgba(99,102,241,.25); transition:all .16s; white-space:nowrap; cursor:pointer; background:none; }
.ch-card-l:hover { background:rgba(99,102,241,.1); border-color:rgba(99,102,241,.4); }

/* ── Timetable ── */
.ch-day-tabs {
  display:flex; overflow-x:auto; gap:4px; padding:0 0 16px;
  scrollbar-width:none; -ms-overflow-style:none;
  border-bottom:1px solid var(--border); margin-bottom:16px;
}
.ch-day-tabs::-webkit-scrollbar { display:none; }

.ch-dtab {
  flex-shrink:0; padding:9px 16px; border:1px solid var(--border); border-radius:10px;
  background:transparent; cursor:pointer; font-family:var(--ch-db);
  font-size:12px; font-weight:600; color:var(--text-muted);
  transition:all .18s; white-space:nowrap; display:flex; align-items:center; gap:6px;
}
.ch-dtab:hover { border-color:var(--border-light); color:var(--text-secondary); background:var(--bg-secondary); }
.ch-dtab.active {
  background:rgba(99,102,241,.12); border-color:rgba(99,102,241,.35);
  color:var(--accent); font-weight:700;
}
.ch-dtab .ch-dcnt {
  background:rgba(99,102,241,.2); color:var(--accent);
  border-radius:99px; padding:1px 7px; font-size:10px; font-weight:800;
}
.ch-dtab.today-tab { border-color:rgba(99,102,241,.25); }
.ch-dtab.today-tab .ch-today-dot {
  width:6px; height:6px; border-radius:50%; background:#22c55e; flex-shrink:0;
}

/* Day panels */
.ch-day-panel { display:none; }
.ch-day-panel.visible { display:block; animation:ch-rise .3s ease both; }

.ch-empty-day {
  text-align:center; padding:32px 20px; color:var(--text-muted);
}
.ch-empty-day .ch-ei { font-size:32px; margin-bottom:10px; }
.ch-empty-day p { font-size:13px; margin-bottom:14px; }

.ch-slot {
  display:flex; align-items:center; gap:16px; padding:14px 16px;
  background:var(--bg-secondary); border-radius:14px;
  border-left:4px solid var(--slot-color, #6366f1);
  margin-bottom:10px; transition:transform .15s, box-shadow .15s;
}
.ch-slot:last-child { margin-bottom:0; }
.ch-slot:hover { transform:translateX(3px); box-shadow:4px 0 16px rgba(0,0,0,.12); }

.ch-slot-time {
  min-width:80px; text-align:center;
  background:var(--bg-card); border-radius:10px; padding:10px 8px;
}
.ch-slot-t { font-family:var(--ch-df); font-size:13px; font-weight:700; color:var(--text-primary); }
.ch-slot-sep { font-size:10px; color:var(--text-muted); margin:2px 0; }
.ch-slot-info { flex:1; min-width:0; }
.ch-slot-name { font-size:14px; font-weight:700; color:var(--text-primary); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.ch-slot-sub { font-size:12px; color:var(--text-muted); margin-top:3px; display:flex; align-items:center; gap:5px; }
.ch-slot-dot { width:7px; height:7px; border-radius:50%; flex-shrink:0; }
.ch-slot-dur { font-size:11px; color:var(--text-muted); margin-top:2px; display:flex; align-items:center; gap:4px; }

.ch-slot-actions { display:flex; gap:6px; flex-shrink:0; }
.ch-btn-log {
  background:rgba(99,102,241,.12); color:var(--accent); border:none;
  border-radius:9px; padding:7px 13px; font-size:12px; font-weight:700;
  cursor:pointer; transition:all .15s; display:flex; align-items:center; gap:5px;
}
.ch-btn-log:hover { background:rgba(99,102,241,.22); transform:translateY(-1px); }
.ch-btn-del {
  background:rgba(239,68,68,.1); color:#ef4444; border:none;
  border-radius:9px; padding:7px 10px; cursor:pointer; transition:all .15s;
}
.ch-btn-del:hover { background:rgba(239,68,68,.2); }

.ch-add-more {
  background:none; border:1px dashed var(--border); border-radius:10px;
  color:var(--text-muted); font-size:12px; font-weight:600;
  padding:9px; cursor:pointer; transition:all .15s; width:100%; margin-top:8px;
}
.ch-add-more:hover { border-color:rgba(99,102,241,.35); color:var(--accent); background:rgba(99,102,241,.05); }

/* ── Period tabs ── */
.ch-period { display:flex; background:var(--bg-secondary); border-radius:10px; padding:3px; gap:2px; }
.ch-ptb {
  padding:6px 14px; border-radius:8px; border:none; font-family:var(--ch-db);
  font-size:12px; font-weight:600; cursor:pointer; background:transparent;
  color:var(--text-muted); transition:all .16s;
}
.ch-ptb.active { background:var(--bg-card); color:var(--text-primary); box-shadow:0 1px 4px rgba(0,0,0,.18); }

/* ── Subject cards ── */
.ch-sub-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(200px,1fr)); gap:14px; }

.ch-sub-card {
  background:var(--bg-secondary); border:1px solid var(--border);
  border-radius:var(--ch-r); padding:16px;
  border-top:3px solid var(--sub-color, #6366f1);
  transition:transform .18s, box-shadow .18s;
  animation:ch-rise .5s ease both;
}
.ch-sub-card:hover { transform:translateY(-3px); box-shadow:0 10px 28px rgba(0,0,0,.15); }
.ch-sub-name {
  font-size:13px; font-weight:700; color:var(--text-primary);
  margin-bottom:10px; display:flex; align-items:center; gap:7px;
  white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.ch-sub-pct {
  font-family:var(--ch-df); font-size:28px; font-weight:800; line-height:1; margin-bottom:4px;
}
.ch-sub-meta { font-size:11px; color:var(--text-muted); margin-bottom:10px; }
.ch-pbar { height:5px; background:var(--bg-card); border-radius:99px; overflow:hidden; }
.ch-pbar-fill { height:100%; border-radius:99px; transition:width .8s cubic-bezier(.4,0,.2,1); }

/* ── Class log table ── */
.ch-log-hd {
  display:grid; grid-template-columns:90px 1fr 110px 80px 90px 80px;
  gap:8px; padding:0 0 10px; border-bottom:1px solid var(--border);
  font-size:11px; font-weight:700; color:var(--text-muted);
  text-transform:uppercase; letter-spacing:.8px;
}
.ch-log-row {
  display:grid; grid-template-columns:90px 1fr 110px 80px 90px 80px;
  gap:8px; padding:12px 0; border-bottom:1px solid var(--border);
  align-items:center; transition:background .12s;
}
.ch-log-row:last-child { border-bottom:none; }
.ch-log-row:hover { background:var(--bg-secondary); border-radius:10px; padding-left:8px; padding-right:8px; }
.ch-log-row.missed { opacity:.55; }

@media(max-width:700px){
  .ch-log-hd { display:none; }
  .ch-log-row {
    display:grid;
    grid-template-columns:1fr auto;
    grid-template-rows:auto auto auto;
    grid-template-areas:"date att" "subj att" "meta att";
    gap:3px 12px;
    background:var(--bg-secondary); border:1px solid var(--border) !important;
    border-radius:12px; padding:12px 14px !important; margin-bottom:8px;
  }
  .ch-log-row:last-child{ margin-bottom:0; border-bottom:1px solid var(--border) !important; }
  .ch-log-date{grid-area:date;}
  .ch-log-subj{grid-area:subj;}
  .ch-log-meta{grid-area:meta;display:flex;gap:8px;}
  .ch-log-att{grid-area:att;display:flex;align-items:center;justify-content:flex-end;}
  .ch-log-time,.ch-log-type,.ch-log-act{display:none;}
}

.ch-log-date { font-size:12px; color:var(--text-muted); }
.ch-log-date strong { font-size:13px; color:var(--text-primary); font-weight:600; display:block; }
.ch-log-subj { font-size:13px; color:var(--text-primary); display:flex; align-items:center; gap:7px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
.ch-log-time { font-size:12px; color:var(--text-muted); }
.ch-log-dur { font-weight:700; color:var(--accent); font-size:13px; white-space:nowrap; }
.ch-log-type span {
  padding:3px 10px; border-radius:99px; font-size:11px; font-weight:700; display:inline-block;
}
.ch-att-btn {
  cursor:pointer; border:none; padding:4px 12px; border-radius:20px;
  font-size:12px; font-weight:700; transition:all .15s;
}
.ch-log-act button {
  background:rgba(239,68,68,.1); color:#ef4444; border:none;
  border-radius:7px; padding:5px 9px; cursor:pointer; transition:all .15s;
}
.ch-log-act button:hover { background:rgba(239,68,68,.2); }

/* ── Modal overrides ── */
.ch-modal-overlay {
  position:fixed; inset:0; background:rgba(0,0,0,.6); backdrop-filter:blur(6px);
  z-index:9990; display:flex; align-items:center; justify-content:center;
  padding:16px; opacity:0; pointer-events:none; transition:opacity .2s;
}
.ch-modal-overlay.active { opacity:1; pointer-events:auto; }
.ch-modal {
  background:var(--bg-card); border:1px solid rgba(99,102,241,.25);
  border-radius:22px; padding:28px; max-width:480px; width:100%;
  box-shadow:0 32px 80px rgba(0,0,0,.5);
  transform:scale(.95) translateY(12px); transition:transform .28s cubic-bezier(.34,1.3,.64,1);
  max-height:90vh; overflow-y:auto;
}
.ch-modal-overlay.active .ch-modal { transform:scale(1) translateY(0); }

.ch-modal-hd { display:flex; align-items:center; justify-content:space-between; margin-bottom:24px; }
.ch-modal-title {
  font-family:var(--ch-df); font-size:17px; font-weight:800;
  color:var(--text-primary); display:flex; align-items:center; gap:10px;
}
.ch-modal-close {
  background:var(--bg-secondary); border:1px solid var(--border); border-radius:8px;
  color:var(--text-muted); font-size:14px; padding:5px 9px; cursor:pointer; transition:all .15s;
}
.ch-modal-close:hover { color:var(--text-primary); border-color:var(--border-light); }

.ch-fg { margin-bottom:16px; }
.ch-fg label { display:block; font-size:12px; font-weight:700; color:var(--text-muted); letter-spacing:.5px; text-transform:uppercase; margin-bottom:7px; }
.ch-inp {
  width:100%; background:var(--bg-secondary); border:1px solid var(--border);
  border-radius:10px; padding:10px 14px; font-family:var(--ch-db);
  font-size:13px; color:var(--text-primary); transition:border-color .15s;
  outline:none; box-sizing:border-box;
}
.ch-inp:focus { border-color:rgba(99,102,241,.5); box-shadow:0 0 0 3px rgba(99,102,241,.08); }
.ch-fg2 { display:grid; grid-template-columns:1fr 1fr; gap:12px; }

.ch-dur-preview {
  background:rgba(99,102,241,.08); border:1px solid rgba(99,102,241,.15);
  border-radius:10px; padding:10px 14px; font-size:13px;
  color:var(--text-secondary); text-align:center; margin-bottom:16px; display:none;
}
.ch-dur-preview strong { color:var(--accent); }

.ch-alert { padding:10px 14px; border-radius:10px; font-size:13px; font-weight:600; margin-bottom:16px; display:none; }
.ch-alert.success { background:rgba(16,185,129,.1); border:1px solid rgba(16,185,129,.2); color:#10b981; }
.ch-alert.error { background:rgba(239,68,68,.1); border:1px solid rgba(239,68,68,.2); color:#ef4444; }

.ch-btn-primary {
  width:100%; background:linear-gradient(135deg,#6366f1,#8b5cf6);
  color:#fff; border:none; border-radius:12px; padding:13px;
  font-family:var(--ch-db); font-size:14px; font-weight:700;
  cursor:pointer; transition:all .18s;
  box-shadow:0 4px 14px rgba(99,102,241,.3);
}
.ch-btn-primary:hover { transform:translateY(-2px); box-shadow:0 8px 24px rgba(99,102,241,.4); }

/* ── Filter bar ── */
.ch-filter-bar {
  display:flex; flex-wrap:wrap; gap:10px; align-items:center;
  padding:16px 22px; background:var(--bg-card); border:1px solid var(--border);
  border-radius:var(--ch-lg); margin-bottom:var(--ch-g);
  animation:ch-rise .4s ease both;
}

/* ── Empty ── */
.ch-empty { text-align:center; padding:48px 20px; }
.ch-empty .ch-ei { font-size:44px; margin-bottom:14px; }
.ch-empty h3 { font-size:15px; font-weight:700; color:var(--text-secondary); margin-bottom:6px; }
.ch-empty p { font-size:13px; color:var(--text-muted); }

/* ── Main grid ── */
.ch-mg { display:grid; grid-template-columns:1fr 340px; gap:var(--ch-g); align-items:start; margin-bottom:var(--ch-g); }
@media(max-width:960px){
  .ch-mg { grid-template-columns:1fr !important; }
  .ch-mg > * { width:100% !important; min-width:0 !important; max-width:100% !important; box-sizing:border-box; }
}
@media(max-width:600px){
  .ch-dtab { padding:8px 12px; font-size:12px; }
  .ch-slot { flex-wrap:wrap; gap:10px; }
  .ch-slot-time { min-width:70px; }
  .ch-day-tabs { -webkit-overflow-scrolling:touch; }
}

/* ── Animations ── */
@keyframes ch-rise { from{opacity:0;transform:translateY(18px)} to{opacity:1;transform:translateY(0)} }

/* ── Back ── */
.bm-back {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 600;
  text-decoration: none;
  margin-bottom: 26px;
  transition: color .18s;
}
.bm-back:hover { color: var(--text-primary); }
</style>

<div class="chp">

  <!-- Back -->
  <a href="javascript:history.back()" class="bm-back">
    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
      <path d="M19 12H5M12 5l-7 7 7 7"/>
    </svg>
    Back
  </a>

<!-- ── STATS ── -->
<div class="ch-stats">
  <div class="ch-st ch-st1">
    <div class="ch-sth">
      <div class="ch-sti" style="background:rgba(99,102,241,.12)">🏫</div>
      <span class="ch-stag tc">Total</span>
    </div>
    <div class="ch-stv"><?= $totalClasses ?><span class="du"> classes</span></div>
    <div class="ch-stl">
      <?= floor($totalMins/60) ?>h <?= $totalMins%60 ?>m total time
    </div>
  </div>
  <div class="ch-st ch-st2">
    <div class="ch-sth">
      <div class="ch-sti" style="background:rgba(6,182,212,.12)">✅</div>
      <span class="ch-stag tc">Attended</span>
    </div>
    <div class="ch-stv"><?= $attendedCount ?><span class="du"> classes</span></div>
    <div class="ch-stl"><?= floor($attendedMins/60) ?>h <?= $attendedMins%60 ?>m attended</div>
  </div>
  <div class="ch-st ch-st3">
    <div class="ch-sth">
      <div class="ch-sti" style="background:rgba(16,185,129,.12)">📈</div>
      <span class="ch-stag <?= $attendRate>=75?'tg':($attendRate>=50?'ta':'tr') ?>">
        <?= $attendRate>=75?'Good':($attendRate>=50?'Okay':'Low') ?>
      </span>
    </div>
    <div class="ch-stv"><?= $attendRate ?><span class="du">%</span></div>
    <div class="ch-stl">Attendance Rate</div>
  </div>
  <div class="ch-st ch-st4">
    <div class="ch-sth">
      <div class="ch-sti" style="background:rgba(239,68,68,.12)">❌</div>
      <span class="ch-stag <?= $missedCount>3?'tr':($missedCount>0?'ta':'tg') ?>">
        <?= $missedCount>0?'Missed':'Perfect!' ?>
      </span>
    </div>
    <div class="ch-stv"><?= $missedCount ?><span class="du"> classes</span></div>
    <div class="ch-stl">Missed Classes</div>
  </div>
</div>


<!-- ── Filter Bar + Log Button ── -->
<div class="ch-filter-bar" style="animation-delay:.12s">
  <div class="ch-period" id="chPeriodTabs">
    <?php foreach (['today'=>'Today','week'=>'Week','month'=>'Month','all'=>'All'] as $k=>$v): ?>
    <button class="ch-ptb <?= $period===$k?'active':'' ?>"
      onclick="location.href='?period=<?= $k ?><?= $subjectFilter?'&subject='.$subjectFilter:'' ?>'"><?= $v ?></button>
    <?php endforeach; ?>
  </div>
  <select onchange="location.href='?period=<?= $period ?>&subject='+this.value"
    class="ch-inp" style="max-width:180px;padding:7px 12px">
    <option value="0">All Subjects</option>
    <?php foreach ($subjects as $sub): ?>
    <option value="<?= $sub['id'] ?>" <?= $subjectFilter==$sub['id']?'selected':'' ?>>
      <?= htmlspecialchars($sub['name']) ?>
    </option>
    <?php endforeach; ?>
  </select>
  <button onclick="openModal()" class="ch-btn-primary" style="width:auto;padding:9px 20px">＋ Log Class</button>
</div>


<!-- ── MAIN GRID: Timetable + Subject Summary ── -->
<div class="ch-mg">

  <!-- Weekly Timetable Card -->
  <div class="ch-card" style="animation-delay:.1s">
    <div class="ch-card-hd">
      <div class="ch-card-t">
        📅 Weekly Schedule
      </div>
      <button class="ch-card-l" onclick="openSlotModal()">＋ Add Class</button>
    </div>

    <!-- Day tabs -->
    <div class="ch-day-tabs">
      <?php foreach ($days as $d):
        $isToday = ($d === $todayDay);
        $cnt = count($slotsByDay[$d]);
      ?>
      <button onclick="chSwitchDay('<?= $d ?>')" id="chtab-<?= $d ?>"
        class="ch-dtab <?= $isToday?'today-tab':'' ?>">
        <?php if($isToday): ?><span class="ch-today-dot"></span><?php endif; ?>
        <?= substr($d,0,3) ?>
        <?php if($cnt>0): ?><span class="ch-dcnt"><?= $cnt ?></span><?php endif; ?>
      </button>
      <?php endforeach; ?>
    </div>

    <!-- Day panels -->
    <?php foreach ($days as $d): ?>
    <div id="chpanel-<?= $d ?>" class="ch-day-panel">
      <?php if (empty($slotsByDay[$d])): ?>
      <div class="ch-empty-day">
        <div class="ch-ei">📭</div>
        <p>No classes on <?= $d ?></p>
        <button onclick="openSlotModal('<?= $d ?>')" class="ch-card-l">
          ＋ Add class for <?= substr($d,0,3) ?>
        </button>
      </div>
      <?php else: ?>
        <?php foreach ($slotsByDay[$d] as $sl):
          $sc  = $sl['subject_color'] ?: $sl['color'] ?: '#6366f1';
          $sn  = $sl['label'] ?: ($sl['subject_name'] ?: 'Class');
          $dur = (strtotime($sl['end_time']) - strtotime($sl['start_time'])) / 60;
        ?>
        <div class="ch-slot" style="--slot-color:<?= htmlspecialchars($sc) ?>">
          <div class="ch-slot-time">
            <div class="ch-slot-t"><?= date('g:i', strtotime($sl['start_time'])) ?></div>
            <div class="ch-slot-sep">↕</div>
            <div class="ch-slot-t"><?= date('g:i a', strtotime($sl['end_time'])) ?></div>
          </div>
          <div class="ch-slot-info">
            <div class="ch-slot-name"><?= htmlspecialchars($sn) ?></div>
            <?php if($sl['subject_name']): ?>
            <div class="ch-slot-sub">
              <span class="ch-slot-dot" style="background:<?= htmlspecialchars($sc) ?>"></span>
              <?= htmlspecialchars($sl['subject_name']) ?>
            </div>
            <?php endif; ?>
            <div class="ch-slot-dur">
              ⏱ <?= floor($dur/60) ?>h <?= $dur%60 ?>m
            </div>
          </div>
          <div class="ch-slot-actions">
            <button class="ch-btn-log" onclick="quickLogFromSlot('<?= addslashes($sl['start_time']) ?>','<?= addslashes($sl['end_time']) ?>',<?= (int)($sl['subject_id']??0) ?>)">
              ✏️ Log
            </button>
            <button class="ch-btn-del" onclick="deleteSlot(<?= $sl['id'] ?>)" title="Remove">🗑</button>
          </div>
        </div>
        <?php endforeach; ?>
        <button onclick="openSlotModal('<?= $d ?>')" class="ch-add-more">
          ＋ Add another class on <?= $d ?>
        </button>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- Subject Summary -->
  <div class="ch-card" style="animation-delay:.18s">
    <div class="ch-card-hd">
      <div class="ch-card-t">📊 Subject Attendance</div>
    </div>
    <?php if (!empty($subStats)): ?>
    <div style="display:flex;flex-direction:column;gap:14px">
      <?php foreach ($subStats as $ss):
        $attPct = $ss['total_classes'] > 0 ? round(($ss['attended_classes']/$ss['total_classes'])*100) : 0;
        $col = $attPct>=75?'#22c55e':($attPct>=50?'#f59e0b':'#ef4444');
      ?>
      <div>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
          <span style="font-size:13px;font-weight:600;color:var(--text-primary);display:flex;align-items:center;gap:7px">
            <span style="width:8px;height:8px;border-radius:50%;background:<?= htmlspecialchars($ss['color']) ?>;flex-shrink:0;display:inline-block"></span>
            <?= htmlspecialchars($ss['name']) ?>
          </span>
          <span style="font-family:var(--ch-df);font-size:15px;font-weight:800;color:<?= $col ?>"><?= $attPct ?>%</span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--text-muted);margin-bottom:6px">
          <span><?= $ss['attended_classes'] ?>/<?= $ss['total_classes'] ?> classes</span>
          <span><?= floor($ss['attended_mins']/60) ?>h <?= $ss['attended_mins']%60 ?>m</span>
        </div>
        <div class="ch-pbar">
          <div class="ch-pbar-fill" style="width:<?= $attPct ?>%;background:<?= $col ?>"></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div class="ch-empty" style="padding:24px">
      <div class="ch-ei" style="font-size:32px">📚</div>
      <h3>No data yet</h3>
      <p>Log classes to see subject attendance</p>
    </div>
    <?php endif; ?>
  </div>

</div><!-- .ch-mg -->


<!-- ── Class Log ── -->
<div class="ch-card" style="animation-delay:.28s">
  <div class="ch-card-hd">
    <div class="ch-card-t">
      📋 Class Log
    </div>
    <span style="font-size:12px;color:var(--text-muted);font-weight:600">
      <?= $totalClasses ?> classes &bull; <?= floor($totalMins/60) ?>h <?= $totalMins%60 ?>m
    </span>
  </div>

  <?php if (empty($classes)): ?>
  <div class="ch-empty">
    <div class="ch-ei">🏫</div>
    <h3>No classes logged yet</h3>
    <p>Click "＋ Log Class" above to start tracking your attendance</p>
  </div>
  <?php else: ?>
  <!-- Header row (desktop) -->
  <div class="ch-log-hd">
    <span>Date</span>
    <span>Subject</span>
    <span>Time</span>
    <span>Duration</span>
    <span>Type</span>
    <span>Attended</span>
  </div>

  <?php
  $typeMap = [
    'regular'  => ['Regular',  '#6366f1'],
    'revision' => ['Revision', '#f59e0b'],
    'practical'=> ['Practical','#22c55e'],
    'tutorial' => ['Tutorial', '#a855f7'],
    'online'   => ['Online',   '#38bdf8'],
  ];
  foreach ($classes as $c):
    $t = $typeMap[$c['class_type']] ?? ['Other','#6366f1'];
  ?>
  <div class="ch-log-row <?= !$c['attended']?'missed':'' ?>">
    <div class="ch-log-date">
      <strong><?= date('M j, Y', strtotime($c['class_date'])) ?></strong>
      <?= date('D', strtotime($c['class_date'])) ?>
    </div>
    <div class="ch-log-subj">
      <span style="width:9px;height:9px;border-radius:50%;background:<?= htmlspecialchars($c['subject_color']) ?>;flex-shrink:0;display:inline-block"></span>
      <?= htmlspecialchars($c['subject_name']) ?>
    </div>
    <div class="ch-log-time" style="font-size:12px;color:var(--text-muted)">
      <?= date('g:i a', strtotime($c['start_time'])) ?>–<?= date('g:i a', strtotime($c['end_time'])) ?>
    </div>
    <div class="ch-log-dur">
      <?= floor($c['duration_minutes']/60) ?>h <?= $c['duration_minutes']%60 ?>m
    </div>
    <div class="ch-log-type">
      <span style="background:<?= $t[1] ?>22;color:<?= $t[1] ?>;padding:3px 10px;border-radius:99px;font-size:11px;font-weight:700">
        <?= $t[0] ?>
      </span>
    </div>
    <div class="ch-log-att" style="display:flex;align-items:center;gap:8px">
      <button onclick="toggleAttend(<?= $c['id'] ?>)"
        class="ch-att-btn"
        style="background:<?= $c['attended']?'rgba(34,197,94,.15)':'rgba(239,68,68,.15)' ?>;color:<?= $c['attended']?'#22c55e':'#ef4444' ?>">
        <?= $c['attended']?'✓ Yes':'✗ No' ?>
      </button>
      <button onclick="deleteClass(<?= $c['id'] ?>)" style="background:rgba(239,68,68,.1);color:#ef4444;border:none;border-radius:7px;padding:5px 8px;cursor:pointer;transition:all .15s" title="Delete">🗑</button>
    </div>
  </div>
  <?php endforeach; ?>
  <?php endif; ?>
</div>


<!-- ════ LOG CLASS MODAL ════ -->
<div class="ch-modal-overlay" id="ttModal">
  <div class="ch-modal">
    <div class="ch-modal-hd">
      <div class="ch-modal-title">🏫 Log Class</div>
      <button class="ch-modal-close" onclick="closeModal()">✕</button>
    </div>
    <div id="chMsg" class="ch-alert"></div>

    <div class="ch-fg2">
      <div class="ch-fg">
        <label>Date</label>
        <input type="date" id="chDate" class="ch-inp" value="<?= date('Y-m-d') ?>">
      </div>
      <div class="ch-fg">
        <label>Subject</label>
        <select id="chSubject" class="ch-inp">
          <option value="">— Select —</option>
          <?php foreach ($subjects as $sub): ?>
          <option value="<?= $sub['id'] ?>"><?= htmlspecialchars($sub['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div class="ch-fg2">
      <div class="ch-fg">
        <label>Start Time</label>
        <input type="time" id="chStart" class="ch-inp" value="08:00">
      </div>
      <div class="ch-fg">
        <label>End Time</label>
        <input type="time" id="chEnd" class="ch-inp" value="10:00">
      </div>
    </div>

    <div class="ch-dur-preview" id="durPreview">
      ⏱️ Duration: <strong id="durText"></strong>
    </div>

    <div class="ch-fg2">
      <div class="ch-fg">
        <label>Type</label>
        <select id="chType" class="ch-inp">
          <option value="regular">Regular</option>
          <option value="revision">Revision</option>
          <option value="practical">Practical</option>
          <option value="tutorial">Tutorial</option>
          <option value="online">Online</option>
        </select>
      </div>
      <div class="ch-fg">
        <label>Attended?</label>
        <select id="chAttended" class="ch-inp">
          <option value="1">✓ Yes</option>
          <option value="0">✗ No (Missed)</option>
        </select>
      </div>
    </div>

    <div class="ch-fg">
      <label>Notes <span style="text-transform:none;letter-spacing:0;font-weight:400">(optional)</span></label>
      <textarea id="chNotes" class="ch-inp" rows="2" style="resize:vertical" placeholder="Topics covered, teacher notes..."></textarea>
    </div>

    <button class="ch-btn-primary" onclick="saveClass()">Save Class</button>
  </div>
</div>


<!-- ════ ADD SCHEDULE SLOT MODAL ════ -->
<div class="ch-modal-overlay" id="slotModal">
  <div class="ch-modal">
    <div class="ch-modal-hd">
      <div class="ch-modal-title">📅 Add to Schedule</div>
      <button class="ch-modal-close" onclick="closeSlotModal()">✕</button>
    </div>
    <div id="slotMsg" class="ch-alert"></div>

    <div class="ch-fg">
      <label>Day of Week</label>
      <select id="slotDay" class="ch-inp">
        <?php foreach ($days as $d): ?>
        <option value="<?= $d ?>"><?= $d ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="ch-fg">
      <label>Subject <span style="text-transform:none;letter-spacing:0;font-weight:400">(optional)</span></label>
      <select id="slotSubject" class="ch-inp" onchange="syncSlotColor(this)">
        <option value="">— No subject —</option>
        <?php foreach ($subjects as $sub): ?>
        <option value="<?= $sub['id'] ?>" data-color="<?= htmlspecialchars($sub['color']) ?>">
          <?= htmlspecialchars($sub['name']) ?>
        </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="ch-fg">
      <label>Class Label <span style="text-transform:none;letter-spacing:0;font-weight:400">(optional)</span></label>
      <input type="text" id="slotLabel" class="ch-inp" placeholder="e.g. Maths Theory, Bio Practical...">
    </div>
    <div class="ch-fg2">
      <div class="ch-fg">
        <label>Start Time</label>
        <input type="time" id="slotStart" class="ch-inp" value="08:00">
      </div>
      <div class="ch-fg">
        <label>End Time</label>
        <input type="time" id="slotEnd" class="ch-inp" value="10:00">
      </div>
    </div>
    <div class="ch-dur-preview" id="slotDurPreview">
      ⏱️ Duration: <strong id="slotDurText"></strong>
    </div>
    <div class="ch-fg">
      <label>Color</label>
      <input type="color" id="slotColor" class="ch-inp" value="#38bdf8" style="height:42px;cursor:pointer;padding:4px">
    </div>
    <button class="ch-btn-primary" onclick="saveSlot()">Add to Schedule</button>
  </div>
</div>

</div><!-- .chp -->

<script>
// ── Day tab switching ──────────────────────────────────────────────
const CH_TODAY = '<?= $todayDay ?>';

function chSwitchDay(day) {
  document.querySelectorAll('[id^="chpanel-"]').forEach(p => p.classList.remove('visible'));
  const panel = document.getElementById('chpanel-' + day);
  if (panel) panel.classList.add('visible');
  document.querySelectorAll('[id^="chtab-"]').forEach(t => t.classList.remove('active'));
  const tab = document.getElementById('chtab-' + day);
  if (tab) tab.classList.add('active');
}
// Use window.onload to ensure everything (incl. footer scripts) is done
window.addEventListener('load', () => chSwitchDay(CH_TODAY));
// Also run immediately in case load already fired
chSwitchDay(CH_TODAY);


// ── Log class modal ────────────────────────────────────────────────
function openModal()  { document.getElementById('ttModal').classList.add('active'); }
function closeModal() { document.getElementById('ttModal').classList.remove('active'); }

function updateDuration() {
  const s = document.getElementById('chStart').value;
  const e = document.getElementById('chEnd').value;
  if (!s || !e) return;
  const diff = (new Date('1970-01-01T'+e) - new Date('1970-01-01T'+s)) / 60000;
  const prev = document.getElementById('durPreview');
  if (diff > 0) {
    prev.style.display = 'block';
    document.getElementById('durText').textContent = Math.floor(diff/60)+'h '+(diff%60)+'m';
  } else { prev.style.display = 'none'; }
}
document.getElementById('chStart').addEventListener('change', updateDuration);
document.getElementById('chEnd').addEventListener('change', updateDuration);
updateDuration();

async function saveClass() {
  const fd = new FormData();
  fd.append('action',     'add');
  fd.append('class_date', document.getElementById('chDate').value);
  fd.append('subject_id', document.getElementById('chSubject').value);
  fd.append('start_time', document.getElementById('chStart').value);
  fd.append('end_time',   document.getElementById('chEnd').value);
  fd.append('class_type', document.getElementById('chType').value);
  fd.append('attended',   document.getElementById('chAttended').value);
  fd.append('notes',      document.getElementById('chNotes').value);

  const msg = document.getElementById('chMsg');
  msg.style.display = 'none';
  try {
    const res  = await fetch(location.href, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd});
    const data = await res.json();
    msg.style.display = 'block';
    msg.className = 'ch-alert ' + (data.success ? 'success' : 'error');
    msg.textContent = data.message;
    if (data.success) setTimeout(() => location.reload(), 800);
  } catch(e) { msg.style.display='block'; msg.className='ch-alert error'; msg.textContent='Network error.'; }
}

async function toggleAttend(id) {
  const fd = new FormData(); fd.append('action','toggle_attend'); fd.append('id', id);
  await fetch(location.href, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd});
  location.reload();
}

async function deleteClass(id) {
  if (!(await stConfirm('Delete this class log?'))) return;
  const fd = new FormData(); fd.append('action','delete'); fd.append('id', id);
  await fetch(location.href, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd});
  location.reload();
}


// ── Schedule slot modal ────────────────────────────────────────────
function openSlotModal(day) {
  if (day) document.getElementById('slotDay').value = day;
  document.getElementById('slotMsg').style.display = 'none';
  document.getElementById('slotModal').classList.add('active');
}
function closeSlotModal() {
  document.getElementById('slotModal').classList.remove('active');
}

function syncSlotColor(sel) {
  const c = sel.options[sel.selectedIndex].dataset.color;
  if (c) document.getElementById('slotColor').value = c;
}

function updateSlotDur() {
  const s = document.getElementById('slotStart').value;
  const e = document.getElementById('slotEnd').value;
  if (!s || !e) return;
  const diff = (new Date('1970-01-01T'+e) - new Date('1970-01-01T'+s)) / 60000;
  const prev = document.getElementById('slotDurPreview');
  if (diff > 0) {
    prev.style.display = 'block';
    document.getElementById('slotDurText').textContent = Math.floor(diff/60)+'h '+(diff%60)+'m';
  } else { prev.style.display = 'none'; }
}
document.getElementById('slotStart').addEventListener('change', updateSlotDur);
document.getElementById('slotEnd').addEventListener('change', updateSlotDur);

async function saveSlot() {
  const fd = new FormData();
  fd.append('action',     'add_slot');
  fd.append('day',        document.getElementById('slotDay').value);
  fd.append('subject_id', document.getElementById('slotSubject').value);
  fd.append('label',      document.getElementById('slotLabel').value);
  fd.append('start_time', document.getElementById('slotStart').value);
  fd.append('end_time',   document.getElementById('slotEnd').value);
  fd.append('color',      document.getElementById('slotColor').value);

  const msg = document.getElementById('slotMsg');
  msg.style.display = 'none';
  try {
    const res  = await fetch(location.href, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd});
    const data = await res.json();
    msg.style.display = 'block';
    msg.className = 'ch-alert ' + (data.success ? 'success' : 'error');
    msg.textContent = data.message;
    if (data.success) setTimeout(() => location.reload(), 700);
  } catch(e) { msg.style.display='block'; msg.className='ch-alert error'; msg.textContent='Network error.'; }
}

async function deleteSlot(id) {
  if (!(await stConfirm('Remove this class from schedule?'))) return;
  const fd = new FormData(); fd.append('action','delete_slot'); fd.append('id', id);
  await fetch(location.href, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd});
  location.reload();
}

// ── Quick log: pre-fill modal from timetable slot ─────────────────
function quickLogFromSlot(startTime, endTime, subjectId) {
  document.getElementById('chDate').value  = new Date().toISOString().split('T')[0];
  document.getElementById('chStart').value = startTime.substring(0,5);
  document.getElementById('chEnd').value   = endTime.substring(0,5);
  if (subjectId) document.getElementById('chSubject').value = subjectId;
  updateDuration();
  document.getElementById('chMsg').style.display = 'none';
  openModal();
}

// Close modals on backdrop click
['ttModal','slotModal'].forEach(id => {
  document.getElementById(id).addEventListener('click', function(e){
    if (e.target === this) this.classList.remove('active');
  });
});
</script>

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