<?php
require_once __DIR__ . '/Includes.php';

$sessionRole = (string)($_SESSION['role'] ?? '');
$isAdminReadOnlyView = $sessionRole === 'admin' && (string)($_GET['admin_view'] ?? '') === '1';
if ($sessionRole === 'admin' && !$isAdminReadOnlyView) {
  header('Location: admin.php');
  exit;
}
check_login(['hop', 'admin']);

$pdo->exec("CREATE TABLE IF NOT EXISTS classes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS subjects (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  class_id INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_subjects_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  role ENUM('admin', 'teacher', 'hop', 'accountant', 'parent') NOT NULL DEFAULT 'teacher',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

try {
  $pdo->exec("ALTER TABLE users MODIFY role ENUM('admin', 'teacher', 'hop', 'accountant', 'parent') NOT NULL DEFAULT 'teacher'");
} catch (PDOException $e) {
  // Keep idempotent.
}

$pdo->exec("CREATE TABLE IF NOT EXISTS teacher_subjects (
  id INT AUTO_INCREMENT PRIMARY KEY,
  teacher_id INT NOT NULL,
  subject_id INT NOT NULL,
  class_id INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_ts_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_ts_subject FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
  CONSTRAINT fk_ts_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  UNIQUE KEY uq_teacher_subject_class (teacher_id, subject_id, class_id)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS hop_profiles (
  user_id INT NOT NULL PRIMARY KEY,
  department_name VARCHAR(150) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_hop_profiles_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS teacher_hop_assignments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  hop_user_id INT NOT NULL,
  teacher_id INT NOT NULL UNIQUE,
  assigned_by INT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_tha_hop_user FOREIGN KEY (hop_user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_tha_teacher_user FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_tha_assigned_by FOREIGN KEY (assigned_by) REFERENCES users(id) ON DELETE SET NULL,
  INDEX idx_tha_hop_user (hop_user_id)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS teacher_documents (
  id INT AUTO_INCREMENT PRIMARY KEY,
  teacher_id INT NOT NULL,
  class_id INT NOT NULL,
  subject_id INT NULL,
  document_type VARCHAR(40) NOT NULL,
  title VARCHAR(180) NOT NULL,
  description TEXT NULL,
  original_name VARCHAR(255) NOT NULL,
  file_path VARCHAR(255) NOT NULL,
  mime_type VARCHAR(120) NULL,
  file_size BIGINT NULL,
  status ENUM('submitted','reviewed','needs_correction','approved') NOT NULL DEFAULT 'submitted',
  hop_status ENUM('submitted','reviewed','needs_correction','approved') NOT NULL DEFAULT 'submitted',
  admin_comment TEXT NULL,
  hop_comment TEXT NULL,
  reviewed_by INT NULL,
  hop_reviewed_by INT NULL,
  reviewed_at DATETIME NULL,
  hop_reviewed_at DATETIME NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_td_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_td_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  CONSTRAINT fk_td_subject FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE SET NULL,
  CONSTRAINT fk_td_reviewer FOREIGN KEY (reviewed_by) REFERENCES users(id) ON DELETE SET NULL,
  CONSTRAINT fk_td_hop_reviewer FOREIGN KEY (hop_reviewed_by) REFERENCES users(id) ON DELETE SET NULL,
  INDEX idx_td_teacher_created (teacher_id, created_at),
  INDEX idx_td_status (status)
)");

$hopDocumentColumnsToEnsure = [
  "hop_status ENUM('submitted','reviewed','needs_correction','approved') NOT NULL DEFAULT 'submitted'",
  "hop_comment TEXT NULL",
  "hop_reviewed_by INT NULL",
  "hop_reviewed_at DATETIME NULL"
];
foreach ($hopDocumentColumnsToEnsure as $columnSql) {
  try {
    $pdo->exec("ALTER TABLE teacher_documents ADD COLUMN " . $columnSql);
  } catch (PDOException $e) {
    // Ignore duplicate column errors.
  }
}

try {
  $pdo->exec("ALTER TABLE teacher_documents ADD CONSTRAINT fk_td_hop_reviewer FOREIGN KEY (hop_reviewed_by) REFERENCES users(id) ON DELETE SET NULL");
} catch (PDOException $e) {
  // Ignore if already exists.
}

$pdo->exec("CREATE TABLE IF NOT EXISTS learners (
  reg_number VARCHAR(30) NOT NULL PRIMARY KEY,
  id INT NOT NULL AUTO_INCREMENT UNIQUE,
  class_id INT NOT NULL,
  full_name VARCHAR(150) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_learners_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS learner_marks (
  id INT AUTO_INCREMENT PRIMARY KEY,
  learner_id INT NOT NULL,
  teacher_id INT NOT NULL,
  class_id INT NOT NULL,
  subject_id INT NOT NULL,
  assessment_type ENUM(
    'daily_exercise',
    'weekly_test',
    'end_of_month_test',
    'end_of_term_exam',
    'midyear_exam',
    'end_of_year_exam'
  ) NOT NULL,
  term_name VARCHAR(30) NOT NULL,
  assessment_date DATE NOT NULL,
  score DECIMAL(6,2) NOT NULL,
  max_score DECIMAL(6,2) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_marks_learner FOREIGN KEY (learner_id) REFERENCES learners(id) ON DELETE CASCADE,
  CONSTRAINT fk_marks_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_marks_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  CONSTRAINT fk_marks_subject FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
  INDEX idx_marks_teacher_date (teacher_id, assessment_date)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS inventory_records (
  id INT AUTO_INCREMENT PRIMARY KEY,
  teacher_id INT NOT NULL,
  class_id INT NOT NULL,
  category ENUM('textbook','furniture','equipment','other') NOT NULL DEFAULT 'other',
  item_name VARCHAR(180) NOT NULL,
  quantity_recorded INT UNSIGNED NOT NULL DEFAULT 0,
  item_condition VARCHAR(80) NULL,
  inventory_note TEXT NULL,
  status ENUM('submitted','verified','discrepancy') NOT NULL DEFAULT 'submitted',
  stock_take_quantity INT UNSIGNED NULL,
  accountant_review TEXT NULL,
  reviewed_by INT NULL,
  reviewed_at DATETIME NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_ir_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_ir_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  CONSTRAINT fk_ir_reviewer FOREIGN KEY (reviewed_by) REFERENCES users(id) ON DELETE SET NULL,
  INDEX idx_ir_teacher_created (teacher_id, created_at)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS school_assets_register (
  id INT AUTO_INCREMENT PRIMARY KEY,
  source_inventory_id INT NOT NULL UNIQUE,
  teacher_id INT NOT NULL,
  class_id INT NOT NULL,
  category ENUM('textbook','furniture','equipment','other') NOT NULL DEFAULT 'other',
  item_name VARCHAR(180) NOT NULL,
  quantity INT UNSIGNED NOT NULL DEFAULT 0,
  item_condition VARCHAR(80) NULL,
  inventory_note TEXT NULL,
  approved_by INT NULL,
  approved_at DATETIME NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_sar_source_inventory FOREIGN KEY (source_inventory_id) REFERENCES inventory_records(id) ON DELETE CASCADE,
  CONSTRAINT fk_sar_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_sar_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE
)");

$alerts = [];
$activeHopId = (int)($_SESSION['user_id'] ?? 0);

if ($isAdminReadOnlyView) {
  $hopProfileStmt = $pdo->query("SELECT u.id, u.name, u.email, hp.department_name
    FROM users u
    LEFT JOIN hop_profiles hp ON hp.user_id = u.id
    WHERE u.role = 'hop'
    ORDER BY u.name ASC
    LIMIT 1");
  $activeHop = $hopProfileStmt ? $hopProfileStmt->fetch() : false;
  if ($activeHop) {
    $activeHopId = (int)$activeHop['id'];
  } else {
    $activeHop = [
      'id' => 0,
      'name' => 'HOP profile not found',
      'email' => '',
      'department_name' => ''
    ];
    $alerts[] = ['type' => 'error', 'text' => 'No HOP user profile exists yet for admin preview.'];
  }
} else {
  $hopProfileStmt = $pdo->prepare("SELECT u.id, u.name, u.email, u.password_hash, hp.department_name
    FROM users u
    LEFT JOIN hop_profiles hp ON hp.user_id = u.id
    WHERE u.id = ? AND u.role = 'hop'
    LIMIT 1");
  $hopProfileStmt->execute([$activeHopId]);
  $activeHop = $hopProfileStmt->fetch();

  if (!$activeHop) {
    logout_user();
    header('Location: index.php');
    exit;
  }
}

if ($activeHop && !$isAdminReadOnlyView && isset($_POST['save_hop_profile'])) {
  $profileName = trim((string)($_POST['profile_name'] ?? ''));
  $profileEmail = trim((string)($_POST['profile_email'] ?? ''));

  if ($profileName === '' || $profileEmail === '') {
    $alerts[] = ['type' => 'error', 'text' => 'Profile name and email are required.'];
  } elseif (!filter_var($profileEmail, FILTER_VALIDATE_EMAIL)) {
    $alerts[] = ['type' => 'error', 'text' => 'Please provide a valid email address.'];
  } else {
    $emailExistsStmt = $pdo->prepare("SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id <> ? LIMIT 1");
    $emailExistsStmt->execute([$profileEmail, $activeHopId]);
    if ($emailExistsStmt->fetch()) {
      $alerts[] = ['type' => 'error', 'text' => 'That email is already used by another account.'];
    } else {
      $updateProfileStmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ? AND role = 'hop' LIMIT 1");
      $updateProfileStmt->execute([$profileName, $profileEmail, $activeHopId]);
      $_SESSION['name'] = $profileName;
      $activeHop['name'] = $profileName;
      $activeHop['email'] = $profileEmail;
      $alerts[] = ['type' => 'success', 'text' => 'HOP profile updated successfully.'];
    }
  }
}

if ($activeHop && !$isAdminReadOnlyView && isset($_POST['change_hop_password'])) {
  $currentPassword = (string)($_POST['current_password'] ?? '');
  $newPassword = (string)($_POST['new_password'] ?? '');
  $confirmPassword = (string)($_POST['confirm_password'] ?? '');

  if ($currentPassword === '' || $newPassword === '' || $confirmPassword === '') {
    $alerts[] = ['type' => 'error', 'text' => 'Current password, new password, and confirmation are required.'];
  } elseif (!password_verify($currentPassword, (string)$activeHop['password_hash'])) {
    $alerts[] = ['type' => 'error', 'text' => 'Current password is incorrect.'];
  } elseif (!mavela_password_is_strong($newPassword)) {
    $alerts[] = ['type' => 'error', 'text' => 'Use at least 10 characters with uppercase, lowercase, and a number.'];
  } elseif ($newPassword !== $confirmPassword) {
    $alerts[] = ['type' => 'error', 'text' => 'New password and confirmation do not match.'];
  } else {
    $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
    $updatePasswordStmt = $pdo->prepare("UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ? AND role = 'hop' LIMIT 1");
    $updatePasswordStmt->execute([$newHash, $activeHopId]);
    $_SESSION['must_change_password'] = false;
    $activeHop['password_hash'] = $newHash;
    $alerts[] = ['type' => 'success', 'text' => 'HOP password changed successfully.'];
  }
}

$assignedTeachers = [];
if ($activeHopId > 0) {
  $assignedTeachersStmt = $pdo->prepare("SELECT u.id, u.name, u.email
    FROM teacher_hop_assignments tha
    JOIN users u ON u.id = tha.teacher_id
    WHERE tha.hop_user_id = ?
    ORDER BY u.name");
  $assignedTeachersStmt->execute([$activeHopId]);
  $assignedTeachers = $assignedTeachersStmt->fetchAll();
}
$assignedTeacherIds = array_map(static function (array $row): int {
  return (int)$row['id'];
}, $assignedTeachers);
$assignedTeacherLookup = [];
foreach ($assignedTeacherIds as $teacherId) {
  $assignedTeacherLookup[$teacherId] = true;
}

$classes = $pdo->query("SELECT id, name FROM classes ORDER BY id")->fetchAll();
$subjects = $pdo->query("SELECT id, name, class_id FROM subjects ORDER BY class_id, name")->fetchAll();

if (isset($_POST['hop_assign_teacher_subjects']) && !$isAdminReadOnlyView) {
  $teacherId = (int)($_POST['teacher_id'] ?? 0);
  $classId = (int)($_POST['class_id'] ?? 0);
  $subjectIds = $_POST['subjects'] ?? [];

  if ($teacherId <= 0 || $classId <= 0) {
    $alerts[] = ['type' => 'error', 'text' => 'Choose both teacher and class before assigning subjects.'];
  } elseif (!isset($assignedTeacherLookup[$teacherId])) {
    $alerts[] = ['type' => 'error', 'text' => 'You can only assign teachers linked to your HOP profile.'];
  } else {
    $classCheckStmt = $pdo->prepare("SELECT id FROM classes WHERE id = ? LIMIT 1");
    $classCheckStmt->execute([$classId]);
    if (!$classCheckStmt->fetch()) {
      $alerts[] = ['type' => 'error', 'text' => 'Selected class does not exist.'];
    } else {
      try {
        $pdo->beginTransaction();

        $pdo->prepare("DELETE FROM teacher_subjects WHERE teacher_id = ? AND class_id = ?")
          ->execute([$teacherId, $classId]);

        if (is_array($subjectIds) && !empty($subjectIds)) {
          $subjectVerifyStmt = $pdo->prepare("SELECT id FROM subjects WHERE id = ? AND class_id = ? LIMIT 1");
          $assignStmt = $pdo->prepare("INSERT INTO teacher_subjects (teacher_id, subject_id, class_id) VALUES (?, ?, ?)");

          foreach ($subjectIds as $subjectIdRaw) {
            $subjectId = (int)$subjectIdRaw;
            if ($subjectId <= 0) {
              continue;
            }
            $subjectVerifyStmt->execute([$subjectId, $classId]);
            if ($subjectVerifyStmt->fetch()) {
              $assignStmt->execute([$teacherId, $subjectId, $classId]);
            }
          }
        }

        $pdo->commit();
        $alerts[] = ['type' => 'success', 'text' => 'Teacher class-subject assignment saved successfully.'];
      } catch (PDOException $e) {
        if ($pdo->inTransaction()) {
          $pdo->rollBack();
        }
        $alerts[] = ['type' => 'error', 'text' => 'Could not save assignment: ' . mavela_exception_detail($e)];
      }
    }
  }
}

if (isset($_POST['hop_review_teacher_document']) && !$isAdminReadOnlyView) {
  $documentId = (int)($_POST['teacher_document_id'] ?? 0);
  $documentStatus = trim((string)($_POST['teacher_document_hop_status'] ?? 'reviewed'));
  $documentComment = trim((string)($_POST['teacher_document_hop_comment'] ?? ''));

  if ($documentId <= 0) {
    $alerts[] = ['type' => 'error', 'text' => 'Invalid teacher document selected.'];
  } elseif (!in_array($documentStatus, ['reviewed', 'needs_correction', 'approved'], true)) {
    $alerts[] = ['type' => 'error', 'text' => 'Invalid HOP review status selected.'];
  } elseif (empty($assignedTeacherIds)) {
    $alerts[] = ['type' => 'error', 'text' => 'No teachers are assigned to your HOP profile yet.'];
  } else {
    $in = implode(',', array_fill(0, count($assignedTeacherIds), '?'));
    $docCheckSql = "SELECT id FROM teacher_documents WHERE id = ? AND teacher_id IN ($in) LIMIT 1";
    $docCheckStmt = $pdo->prepare($docCheckSql);
    $docCheckStmt->execute(array_merge([$documentId], $assignedTeacherIds));

    if (!$docCheckStmt->fetch()) {
      $alerts[] = ['type' => 'error', 'text' => 'Teacher document not found in your department scope.'];
    } else {
      $reviewStmt = $pdo->prepare("UPDATE teacher_documents
        SET hop_status = ?, hop_comment = ?, hop_reviewed_by = ?, hop_reviewed_at = NOW()
        WHERE id = ?");
      $reviewStmt->execute([
        $documentStatus,
        $documentComment === '' ? null : $documentComment,
        $activeHopId,
        $documentId
      ]);
      $alerts[] = ['type' => 'success', 'text' => 'Teacher document feedback sent back to teacher from HOP desk.'];
    }
  }
}

$currentAssignments = [];
$teacherDocuments = [];
$teacherMarks = [];
$inventoryRows = [];
$assetRows = [];

if (!empty($assignedTeacherIds)) {
  $in = implode(',', array_fill(0, count($assignedTeacherIds), '?'));

  $assignmentStmt = $pdo->prepare("SELECT ts.id, t.name AS teacher_name, t.email AS teacher_email,
      c.name AS class_name, s.name AS subject_name
    FROM teacher_subjects ts
    JOIN users t ON t.id = ts.teacher_id
    JOIN classes c ON c.id = ts.class_id
    JOIN subjects s ON s.id = ts.subject_id
    WHERE ts.teacher_id IN ($in)
    ORDER BY t.name, c.name, s.name");
  $assignmentStmt->execute($assignedTeacherIds);
  $currentAssignments = $assignmentStmt->fetchAll();

  $docStmt = $pdo->prepare("SELECT td.id, td.created_at, td.document_type, td.title, td.description,
      td.original_name, td.file_path, td.file_size,
      td.status, td.admin_comment, td.reviewed_at,
      td.hop_status, td.hop_comment, td.hop_reviewed_at,
      t.name AS teacher_name, t.email AS teacher_email,
      c.name AS class_name, s.name AS subject_name
    FROM teacher_documents td
    JOIN users t ON t.id = td.teacher_id
    JOIN classes c ON c.id = td.class_id
    LEFT JOIN subjects s ON s.id = td.subject_id
    WHERE td.teacher_id IN ($in)
    ORDER BY td.created_at DESC
    LIMIT 400");
  $docStmt->execute($assignedTeacherIds);
  $teacherDocuments = $docStmt->fetchAll();

  $marksStmt = $pdo->prepare("SELECT lm.assessment_date, lm.assessment_type, lm.term_name,
      lm.score, lm.max_score,
      t.name AS teacher_name,
      l.reg_number, l.full_name AS learner_name,
      c.name AS class_name,
      s.name AS subject_name
    FROM learner_marks lm
    JOIN users t ON t.id = lm.teacher_id
    JOIN learners l ON l.id = lm.learner_id
    JOIN classes c ON c.id = lm.class_id
    JOIN subjects s ON s.id = lm.subject_id
    WHERE lm.teacher_id IN ($in)
    ORDER BY lm.assessment_date DESC, lm.created_at DESC
    LIMIT 600");
  $marksStmt->execute($assignedTeacherIds);
  $teacherMarks = $marksStmt->fetchAll();

  $inventoryStmt = $pdo->prepare("SELECT ir.created_at, ir.category, ir.item_name, ir.quantity_recorded,
      ir.item_condition, ir.status, ir.stock_take_quantity, ir.accountant_review,
      t.name AS teacher_name, c.name AS class_name
    FROM inventory_records ir
    JOIN users t ON t.id = ir.teacher_id
    JOIN classes c ON c.id = ir.class_id
    WHERE ir.teacher_id IN ($in)
    ORDER BY ir.created_at DESC
    LIMIT 500");
  $inventoryStmt->execute($assignedTeacherIds);
  $inventoryRows = $inventoryStmt->fetchAll();

  $assetsStmt = $pdo->prepare("SELECT sar.created_at, sar.approved_at, sar.category, sar.item_name, sar.quantity,
      sar.item_condition, t.name AS teacher_name, c.name AS class_name
    FROM school_assets_register sar
    JOIN users t ON t.id = sar.teacher_id
    JOIN classes c ON c.id = sar.class_id
    WHERE sar.teacher_id IN ($in)
    ORDER BY sar.approved_at DESC, sar.created_at DESC
    LIMIT 500");
  $assetsStmt->execute($assignedTeacherIds);
  $assetRows = $assetsStmt->fetchAll();
}

if ($isAdminReadOnlyView && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
  $alerts[] = ['type' => 'error', 'text' => 'Admin preview mode is read-only on HOP dashboard.'];
}

$docCorrections = 0;
foreach ($teacherDocuments as $docRow) {
  if (($docRow['hop_status'] ?? '') === 'needs_correction') {
    $docCorrections++;
  }
}

$themePalette = get_school_theme_palette($pdo);
$paletteBgCream = (string)($themePalette['bg_cream'] ?? '#F7FBF7');
$paletteBgSand = (string)($themePalette['bg_sand'] ?? '#E5F0E6');
$paletteInk = (string)($themePalette['ink'] ?? '#173122');
$paletteMuted = (string)($themePalette['muted'] ?? '#4F6656');
$paletteBrandNavy = (string)($themePalette['brand_navy'] ?? '#2E8B45');
$paletteBrandNavyDeep = (string)($themePalette['brand_navy_deep'] ?? '#1D6A33');
$paletteBrandIce = (string)($themePalette['brand_ice'] ?? '#EEF7EF');
$palettePatchSky = (string)($themePalette['patch_sky'] ?? '#7CC9FF');
$palettePatchSkySoft = (string)($themePalette['patch_sky_soft'] ?? '#D6EEFF');
$palettePatchYellow = (string)($themePalette['patch_yellow'] ?? '#FFD447');

$departmentName = trim((string)($activeHop['department_name'] ?? ''));
if ($departmentName === '') {
  $departmentName = 'Department not set';
}

$totalTeachers = count($assignedTeachers);
$totalAssignments = count($currentAssignments);
$totalDocuments = count($teacherDocuments);
$totalMarks = count($teacherMarks);
$totalInventory = count($inventoryRows);
$totalAssets = count($assetRows);

$subjectDirectory = [];
foreach ($subjects as $subjectRow) {
  $classId = (int)$subjectRow['class_id'];
  if (!isset($subjectDirectory[$classId])) {
    $subjectDirectory[$classId] = [];
  }
  $subjectDirectory[$classId][] = [
    'id' => (int)$subjectRow['id'],
    'name' => (string)$subjectRow['name']
  ];
}

function format_file_size_hop($bytes): string {
  $size = (float)$bytes;
  if ($size <= 0) {
    return '0 B';
  }
  $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  $power = min((int)floor(log($size, 1024)), count($units) - 1);
  $value = $size / pow(1024, $power);
  return number_format($value, $value >= 100 || $power === 0 ? 0 : 1) . ' ' . $units[$power];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HOP Dashboard</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: <?= h($paletteBgCream) ?>;
      --bg-soft: <?= h($paletteBgSand) ?>;
      --ink: <?= h($paletteInk) ?>;
      --muted: <?= h($paletteMuted) ?>;
      --brand: <?= h($paletteBrandNavy) ?>;
      --brand-dark: <?= h($paletteBrandNavyDeep) ?>;
      --accent: <?= h($palettePatchYellow) ?>;
      --line: <?= h($palettePatchSkySoft) ?>;
      --patch-sky: <?= h($palettePatchSky) ?>;
      --panel: #ffffff;
      --danger: #9f1239;
      --success: #166534;
    }

    * { box-sizing: border-box; }

    body {
      margin: 0;
      font-family: 'Outfit', sans-serif;
      background:
        radial-gradient(circle at 10% 10%, rgba(124, 201, 255, 0.24) 0, rgba(124, 201, 255, 0) 34%),
        radial-gradient(circle at 85% 10%, rgba(46, 139, 69, 0.2) 0, rgba(46, 139, 69, 0) 35%),
        linear-gradient(170deg, var(--bg) 0%, var(--bg-soft) 100%);
      color: var(--ink);
      padding: 18px;
    }

    .shell {
      max-width: 1240px;
      margin: 0 auto;
      display: grid;
      gap: 14px;
    }

    .header {
      border-radius: 18px;
      padding: 18px;
      background: linear-gradient(122deg, var(--brand-dark), var(--brand));
      color: #fff;
      display: flex;
      justify-content: space-between;
      gap: 12px;
      flex-wrap: wrap;
      align-items: center;
    }

    .title {
      margin: 0;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: clamp(1.2rem, 2.5vw, 1.8rem);
    }

    .sub {
      margin: 5px 0 0;
      font-size: 0.94rem;
      opacity: 0.95;
    }

    .chip {
      border-radius: 999px;
      border: 1px solid #f8b400;
      padding: 7px 12px;
      font-size: 0.82rem;
      color: #12386d;
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      gap: 8px;
      background: #ffd447;
      font-weight: 700;
    }

    .alerts {
      display: grid;
      gap: 8px;
    }

    .alert {
      border-radius: 11px;
      border: 1px solid;
      padding: 10px 12px;
      font-weight: 600;
      font-size: 0.92rem;
      background: #fff;
    }

    .alert.success { color: var(--success); border-color: #8dd3a1; }
    .alert.error { color: var(--danger); border-color: #f6a5ba; }

    .cards {
      display: grid;
      grid-template-columns: repeat(6, minmax(0, 1fr));
      gap: 10px;
    }

    .card {
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: 14px;
      padding: 12px;
      box-shadow: 0 10px 24px rgba(20, 58, 37, 0.1);
    }

    .card small {
      display: block;
      color: var(--muted);
      text-transform: uppercase;
      letter-spacing: 0.06em;
      font-size: 0.74rem;
      font-weight: 700;
      margin-bottom: 6px;
    }

    .card strong {
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: 1.45rem;
    }

    .layout {
      display: grid;
      grid-template-columns: 250px minmax(0, 1fr);
      gap: 12px;
      align-items: start;
    }

    .sidebar {
      position: sticky;
      top: 12px;
      background: #fff;
      border: 1px solid var(--line);
      border-radius: 14px;
      padding: 10px;
      box-shadow: 0 10px 24px rgba(20, 58, 37, 0.08);
    }

    .menu {
      display: grid;
      gap: 6px;
    }

    .menu button {
      border: 1px solid #cde0d1;
      border-radius: 10px;
      background: #f3faf5;
      color: #123a24;
      padding: 8px 10px;
      text-align: left;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: 0.84rem;
      font-weight: 700;
      cursor: pointer;
      transition: transform 140ms ease, background 140ms ease, color 140ms ease;
    }

    .menu button.active {
      background: linear-gradient(112deg, var(--brand), var(--brand-dark));
      color: #fff;
      border-color: var(--brand-dark);
    }

    .menu button:hover {
      background: #dff4ff;
      color: #083b78;
      border-color: #7cc9ff;
    }

    .main {
      display: grid;
      gap: 12px;
      min-width: 0;
    }

    .view {
      display: none !important;
      visibility: hidden;
      height: 0;
      overflow: hidden;
    }
    .view.active {
      display: grid !important;
      gap: 12px;
      visibility: visible;
      height: auto;
      overflow: visible;
    }

    .panel {
      background: #fff;
      border: 1px solid var(--line);
      border-radius: 16px;
      box-shadow: 0 10px 24px rgba(20, 58, 37, 0.08);
      padding: 16px;
    }

    .panel h2 {
      margin: 0;
      font-size: 1.05rem;
      font-family: 'Plus Jakarta Sans', sans-serif;
    }

    .hint {
      color: var(--muted);
      margin: 8px 0 12px;
      font-size: 0.92rem;
    }

    .field {
      display: grid;
      gap: 5px;
      margin-bottom: 10px;
    }

    label {
      font-size: 0.78rem;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      color: var(--muted);
      font-weight: 700;
    }

    input, select, textarea {
      width: 100%;
      border: 1px solid #c8d9cb;
      border-radius: 10px;
      padding: 9px 10px;
      font-family: inherit;
      font-size: 0.94rem;
      color: var(--ink);
      background: #fff;
    }

    input[type="search"] {
      background:
        url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%234f6656' stroke-width='2.1' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='7'/%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'/%3E%3C/svg%3E") no-repeat 10px center,
        linear-gradient(90deg, #ffffff 0%, #f1f8f2 70%, #e8f7ee 100%);
      background-size: 15px 15px, auto;
      padding-left: 34px;
    }

    textarea { min-height: 88px; resize: vertical; }

    button.submit {
      border: 0;
      border-radius: 10px;
      padding: 10px 12px;
      color: #fff;
      background: linear-gradient(112deg, var(--brand), var(--brand-dark));
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-weight: 700;
      cursor: pointer;
    }

    .subject-grid {
      border: 1px solid #d8e6db;
      border-radius: 10px;
      background: #f7fbf8;
      padding: 10px;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
      gap: 8px;
      min-height: 48px;
    }

    .subject-item {
      display: flex;
      align-items: center;
      gap: 7px;
      border: 1px solid #cfe2d4;
      border-radius: 9px;
      padding: 6px 8px;
      background: #fff;
    }

    .table-wrap {
      border: 1px solid var(--line);
      border-radius: 12px;
      overflow-x: auto;
      background: #fff;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.91rem;
    }

    th {
      text-align: left;
      padding: 10px;
      background: #eff8f1;
      color: #1a4e30;
      font-size: 0.78rem;
      text-transform: uppercase;
      letter-spacing: 0.06em;
    }

    td {
      border-top: 1px solid #edf4ef;
      padding: 9px 10px;
      color: #224430;
      vertical-align: top;
    }

    .badge {
      display: inline-block;
      border-radius: 999px;
      padding: 3px 10px;
      font-size: 0.76rem;
      font-weight: 700;
      background: #e7f4ea;
      color: #1d5d37;
      border: 1px solid #c8e3d0;
    }

    .correction {
      background: #fff1f4;
      border-color: #f2b3c6;
      color: #9f1239;
    }

    a:hover,
    button:hover,
    input:hover,
    select:hover,
    textarea:hover,
    [role="button"]:hover,
    .button:hover,
    .btn:hover,
    .submit:hover,
    .chip:hover,
    .meta-chip:hover,
    .side-btn:hover,
    .desk-nav-btn:not(.active):hover,
    .menu button:hover,
    table tbody tr:hover td,
    table tbody tr:hover th,
    .card:hover,
    .panel:hover,
    .item:hover,
    .metric:hover,
    .stat:hover {
      background-color: #dff4ff !important;
      border-color: #7cc9ff !important;
      color: #083b78 !important;
    }

    @media (max-width: 1100px) {
      .cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
    }

    @media (max-width: 900px) {
      .layout { grid-template-columns: 1fr; }
      .sidebar { position: static; }
    }

    @media (max-width: 620px) {
      .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    }

    @media (max-width: 480px) {
      body { padding: 12px; }
      .cards { grid-template-columns: 1fr; }
      .header { padding: 14px; }

      input,
      select,
      textarea {
        font-size: 16px;
      }

      .side-btn,
      .chip,
      .desk-nav-btn {
        min-height: 44px;
      }
    }
  </style>
</head>
<body>
  <div class="shell">
    <header class="header">
      <div>
        <h1 class="title">HOP Dashboard</h1>
        <p class="sub">Signed in as <?= h($activeHop['name']) ?> | Department: <?= h($departmentName) ?></p>
      </div>
      <div style="display:flex; gap:8px; flex-wrap:wrap;">
        <span class="chip" id="hopDeskProgressChip">Step 1 of 6</span>
        <?php if ($isAdminReadOnlyView): ?>
          <span class="chip">Admin Preview (Read Only)</span>
        <?php endif; ?>
        <a class="chip" href="logout.php">Logout</a>
        <span class="chip"><?= h(date('D, d M Y')) ?></span>
      </div>
    </header>

    <?php if (!empty($alerts)): ?>
      <section class="alerts">
        <?php foreach ($alerts as $alert): ?>
          <div class="alert <?= $alert['type'] === 'success' ? 'success' : 'error' ?>"><?= h($alert['text']) ?></div>
        <?php endforeach; ?>
      </section>
    <?php endif; ?>

    <section class="cards">
      <article class="card"><small>Assigned Teachers</small><strong><?= h($totalTeachers) ?></strong></article>
      <article class="card"><small>Teacher Assignments</small><strong><?= h($totalAssignments) ?></strong></article>
      <article class="card"><small>Teacher Documents</small><strong><?= h($totalDocuments) ?></strong></article>
      <article class="card"><small>Need Correction</small><strong><?= h($docCorrections) ?></strong></article>
      <article class="card"><small>Marks Uploaded</small><strong><?= h($totalMarks) ?></strong></article>
      <article class="card"><small>Assets Records</small><strong><?= h($totalAssets) ?></strong></article>
    </section>

    <div class="layout">
      <aside class="sidebar">
        <nav class="menu" id="hopMenu">
          <button type="button" class="active" data-target="hopHomeView">Summary</button>
          <button type="button" data-target="hopProfileView">My Profile</button>
          <button type="button" data-target="hopAssignmentsView">Teacher Class and Subject Assignment</button>
          <button type="button" data-target="hopDocumentsView">Teacher Documents Review</button>
          <button type="button" data-target="hopMarksView">Teacher Marks Monitor</button>
          <button type="button" data-target="hopInventoryView">Department Assets Register</button>
        </nav>
      </aside>

      <main class="main">
        <section id="hopHomeView" class="view active panel">
          <h2>Department Scope</h2>
          <p class="hint">HOP can work only with teachers assigned by Admin. Use this desk to allocate class-subject loads, review documents, and monitor marks and assets from those teachers.</p>
          <?php if (empty($assignedTeachers)): ?>
            <p class="hint">No teachers are assigned to this HOP profile yet. Ask Admin to link teachers first.</p>
          <?php else: ?>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Teacher</th>
                    <th>Email</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($assignedTeachers as $teacher): ?>
                    <tr>
                      <td><?= h($teacher['name']) ?></td>
                      <td><?= h($teacher['email']) ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </section>

        <section id="hopProfileView" class="view panel">
          <h2>My HOP Profile</h2>
          <?php if ($isAdminReadOnlyView): ?>
            <p class="hint">Profile editing is disabled in admin read-only preview mode.</p>
          <?php else: ?>
            <p class="hint">Update your HOP account details and change your password here.</p>
            <div class="cards" style="margin-top:12px;">
              <article class="card" style="grid-column: span 3;">
                <form method="POST" autocomplete="off">
                  <div class="field">
                    <label for="hop_profile_name">Full Name</label>
                    <input id="hop_profile_name" name="profile_name" value="<?= h((string)$activeHop['name']) ?>" required>
                  </div>
                  <div class="field">
                    <label for="hop_profile_email">Email Address</label>
                    <input id="hop_profile_email" type="email" name="profile_email" value="<?= h((string)$activeHop['email']) ?>" required>
                  </div>
                  <button class="submit" type="submit" name="save_hop_profile">Save Profile</button>
                </form>
              </article>

              <article class="card" style="grid-column: span 3;">
                <form method="POST" autocomplete="off">
                  <div class="field">
                    <label for="hop_current_password">Current Password</label>
                    <input id="hop_current_password" type="password" name="current_password" required>
                  </div>
                  <div class="field">
                    <label for="hop_new_password">New Password</label>
                    <input id="hop_new_password" type="password" name="new_password" minlength="10" autocomplete="new-password" required>
                  </div>
                  <div class="field">
                    <label for="hop_confirm_password">Confirm New Password</label>
                    <input id="hop_confirm_password" type="password" name="confirm_password" minlength="10" autocomplete="new-password" required>
                  </div>
                  <button class="submit" type="submit" name="change_hop_password">Change Password</button>
                </form>
              </article>
            </div>
          <?php endif; ?>
        </section>

        <section id="hopAssignmentsView" class="view panel">
          <h2>Assign Classes and Subjects to Teachers</h2>
          <p class="hint">Choose one teacher in your department, choose a class, and tick subjects for that class. Saving replaces the teacher's subject list for that class.</p>

          <form method="POST" autocomplete="off">
            <div class="field">
              <label for="teacher_id">Teacher</label>
              <input type="search" id="hopTeacherSearch" placeholder="Search teacher name or email...">
              <select id="teacher_id" name="teacher_id" required>
                <option value="">Choose teacher</option>
                <?php foreach ($assignedTeachers as $teacher): ?>
                  <option value="<?= h($teacher['id']) ?>"><?= h($teacher['name']) ?> (<?= h($teacher['email']) ?>)</option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field">
              <label for="class_id">Class</label>
              <input type="search" id="hopClassSearch" placeholder="Search class...">
              <select id="class_id" name="class_id" required>
                <option value="">Choose class</option>
                <?php foreach ($classes as $classRow): ?>
                  <option value="<?= h($classRow['id']) ?>"><?= h($classRow['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field">
              <label>Subjects for Selected Class</label>
              <div id="hopSubjectGrid" class="subject-grid"></div>
            </div>
            <button class="submit" type="submit" name="hop_assign_teacher_subjects">Save HOP Assignment</button>
          </form>

          <div class="table-wrap" style="margin-top:12px;">
            <table>
              <thead>
                <tr>
                  <th>Teacher</th>
                  <th>Class</th>
                  <th>Subject</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($currentAssignments)): ?>
                  <tr><td colspan="3">No class-subject assignments found for assigned teachers.</td></tr>
                <?php else: ?>
                  <?php foreach ($currentAssignments as $row): ?>
                    <tr>
                      <td><?= h($row['teacher_name']) ?></td>
                      <td><?= h($row['class_name']) ?></td>
                      <td><?= h($row['subject_name']) ?></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </section>

        <section id="hopDocumentsView" class="view panel">
          <h2>Teacher Documents from Department</h2>
          <p class="hint">Documents submitted by your assigned teachers arrive here and in Admin desk. Review and send return comments from HOP the same way.</p>

          <div class="table-wrap">
            <table>
              <thead>
                <tr>
                  <th>Submitted</th>
                  <th>Teacher</th>
                  <th>Class</th>
                  <th>Type</th>
                  <th>Title</th>
                  <th>File</th>
                  <th>Admin Status</th>
                  <th>HOP Status</th>
                  <th>HOP Review</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($teacherDocuments)): ?>
                  <tr><td colspan="9">No teacher documents found for your department.</td></tr>
                <?php else: ?>
                  <?php foreach ($teacherDocuments as $doc): ?>
                    <tr>
                      <td><?= h($doc['created_at']) ?></td>
                      <td><?= h($doc['teacher_name']) ?><br><small><?= h($doc['teacher_email']) ?></small></td>
                      <td><?= h($doc['class_name']) ?><?= !empty($doc['subject_name']) ? ' / ' . h($doc['subject_name']) : '' ?></td>
                      <td><?= h($doc['document_type']) ?></td>
                      <td>
                        <strong><?= h($doc['title']) ?></strong>
                        <?php if (!empty($doc['description'])): ?><br><small><?= h($doc['description']) ?></small><?php endif; ?>
                      </td>
                      <td>
                        <a href="<?= h($doc['file_path']) ?>" target="_blank" rel="noopener">Open</a><br>
                        <small><?= h($doc['original_name']) ?> (<?= h(format_file_size_hop($doc['file_size'])) ?>)</small>
                      </td>
                      <td>
                        <span class="badge"><?= h(ucfirst(str_replace('_', ' ', $doc['status']))) ?></span>
                        <?php if (!empty($doc['admin_comment'])): ?><br><small><?= h($doc['admin_comment']) ?></small><?php endif; ?>
                      </td>
                      <td>
                        <?php $hopNeedsCorrection = ($doc['hop_status'] ?? '') === 'needs_correction'; ?>
                        <span class="badge <?= $hopNeedsCorrection ? 'correction' : '' ?>"><?= h(ucfirst(str_replace('_', ' ', (string)$doc['hop_status']))) ?></span>
                        <?php if (!empty($doc['hop_comment'])): ?><br><small><?= h($doc['hop_comment']) ?></small><?php endif; ?>
                      </td>
                      <td>
                        <form method="POST" style="display:grid; gap:6px; min-width:220px;">
                          <input type="hidden" name="teacher_document_id" value="<?= h($doc['id']) ?>">
                          <select name="teacher_document_hop_status" required>
                            <option value="reviewed" <?= $doc['hop_status'] === 'reviewed' ? 'selected' : '' ?>>Reviewed</option>
                            <option value="needs_correction" <?= $doc['hop_status'] === 'needs_correction' ? 'selected' : '' ?>>Needs Correction</option>
                            <option value="approved" <?= $doc['hop_status'] === 'approved' ? 'selected' : '' ?>>Approved</option>
                          </select>
                          <textarea name="teacher_document_hop_comment" placeholder="Comment to teacher..."><?= h((string)($doc['hop_comment'] ?? '')) ?></textarea>
                          <button class="submit" type="submit" name="hop_review_teacher_document">Send to Teacher</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </section>

        <section id="hopMarksView" class="view panel">
          <h2>Marks Uploaded by Department Teachers</h2>
          <p class="hint">This stream helps HOP monitor marks captured by assigned teachers before end-of-term reporting.</p>

          <div class="table-wrap">
            <table>
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Teacher</th>
                  <th>Learner</th>
                  <th>Class</th>
                  <th>Subject</th>
                  <th>Assessment</th>
                  <th>Term</th>
                  <th>Score</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($teacherMarks)): ?>
                  <tr><td colspan="8">No marks uploaded yet by assigned teachers.</td></tr>
                <?php else: ?>
                  <?php foreach ($teacherMarks as $mark): ?>
                    <?php $percent = (float)$mark['max_score'] > 0 ? round(((float)$mark['score'] / (float)$mark['max_score']) * 100, 1) : 0; ?>
                    <tr>
                      <td><?= h($mark['assessment_date']) ?></td>
                      <td><?= h($mark['teacher_name']) ?></td>
                      <td><?= h($mark['learner_name']) ?><br><small><?= h($mark['reg_number']) ?></small></td>
                      <td><?= h($mark['class_name']) ?></td>
                      <td><?= h($mark['subject_name']) ?></td>
                      <td><?= h($mark['assessment_type']) ?></td>
                      <td><?= h($mark['term_name']) ?></td>
                      <td><?= h($mark['score']) ?>/<?= h($mark['max_score']) ?> (<?= h($percent) ?>%)</td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </section>

        <section id="hopInventoryView" class="view panel">
          <h2>Department Assets and Inventory Register</h2>
          <p class="hint">HOP view of teacher inventory submissions and approved assets register for assigned teachers.</p>

          <h2 style="margin-top:4px;">Teacher Inventory Submissions</h2>
          <div class="table-wrap" style="margin-top:8px; margin-bottom:12px;">
            <table>
              <thead>
                <tr>
                  <th>Submitted</th>
                  <th>Teacher</th>
                  <th>Class</th>
                  <th>Category</th>
                  <th>Item</th>
                  <th>Qty</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($inventoryRows)): ?>
                  <tr><td colspan="7">No inventory entries found for your department.</td></tr>
                <?php else: ?>
                  <?php foreach ($inventoryRows as $row): ?>
                    <tr>
                      <td><?= h($row['created_at']) ?></td>
                      <td><?= h($row['teacher_name']) ?></td>
                      <td><?= h($row['class_name']) ?></td>
                      <td><?= h($row['category']) ?></td>
                      <td>
                        <strong><?= h($row['item_name']) ?></strong>
                        <?php if (!empty($row['item_condition'])): ?><br><small><?= h($row['item_condition']) ?></small><?php endif; ?>
                      </td>
                      <td><?= h((int)$row['quantity_recorded']) ?></td>
                      <td><span class="badge"><?= h(ucfirst((string)$row['status'])) ?></span></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <h2>Approved School Assets Register</h2>
          <div class="table-wrap" style="margin-top:8px;">
            <table>
              <thead>
                <tr>
                  <th>Approved</th>
                  <th>Teacher</th>
                  <th>Class</th>
                  <th>Category</th>
                  <th>Item</th>
                  <th>Quantity</th>
                  <th>Condition</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($assetRows)): ?>
                  <tr><td colspan="7">No approved assets found for your department.</td></tr>
                <?php else: ?>
                  <?php foreach ($assetRows as $row): ?>
                    <tr>
                      <td><?= h($row['approved_at'] ?: $row['created_at']) ?></td>
                      <td><?= h($row['teacher_name']) ?></td>
                      <td><?= h($row['class_name']) ?></td>
                      <td><?= h($row['category']) ?></td>
                      <td><?= h($row['item_name']) ?></td>
                      <td><?= h((int)$row['quantity']) ?></td>
                      <td><?= h($row['item_condition'] ?: '-') ?></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </section>
      </main>
    </div>
  </div>

  <script>
    const isAdminReadOnlyView = <?= $isAdminReadOnlyView ? 'true' : 'false' ?>;
    if (isAdminReadOnlyView) {
      Array.from(document.querySelectorAll('form[method="POST"], form[method="post"]')).forEach(form => {
        form.addEventListener('submit', function (event) {
          event.preventDefault();
          window.alert('Admin preview mode is read-only.');
        });

        Array.from(form.querySelectorAll('button[type="submit"], input[type="submit"]')).forEach(btn => {
          btn.disabled = true;
          btn.title = 'Disabled in admin read-only preview mode';
        });
      });
    }

    const subjectDirectory = <?= json_encode($subjectDirectory, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const teacherSelect = document.getElementById('teacher_id');
    const teacherSearch = document.getElementById('hopTeacherSearch');
    const classSelect = document.getElementById('class_id');
    const classSearch = document.getElementById('hopClassSearch');
    const subjectGrid = document.getElementById('hopSubjectGrid');

    function wireSelectSearch(searchEl, selectEl, labels) {
      if (!searchEl || !selectEl) {
        return;
      }

      function applyFilter() {
        const term = searchEl.value.trim().toLowerCase();
        let hasAny = false;
        const visibleOptions = [];
        let changedSelection = false;

        Array.from(selectEl.options).forEach((option, idx) => {
          if (idx === 0) {
            option.style.display = '';
            return;
          }

          const matches = term === '' || option.textContent.toLowerCase().includes(term);
          option.style.display = matches ? '' : 'none';

          if (!matches && option.selected) {
            selectEl.value = String(selectEl.options[0]?.value || '');
            changedSelection = true;
          }

          if (matches) {
            hasAny = true;
            visibleOptions.push(option);
          }
        });

        if (selectEl.options[0]) {
          selectEl.options[0].text = hasAny ? labels.defaultLabel : labels.emptyLabel;
        }

        if (term !== '' && visibleOptions.length > 0) {
          const currentVisible = visibleOptions.some(option => option.value === selectEl.value);
          if (!currentVisible) {
            const startsWithMatch = visibleOptions.find(option => option.textContent.toLowerCase().startsWith(term));
            const nextOption = startsWithMatch || visibleOptions[0];
            if (nextOption && selectEl.value !== nextOption.value) {
              selectEl.value = nextOption.value;
              changedSelection = true;
            }
          }
        }

        if (changedSelection) {
          selectEl.dispatchEvent(new Event('change', { bubbles: true }));
        }
      }

      searchEl.addEventListener('input', applyFilter);
      applyFilter();
    }

    function renderSubjectsForClass() {
      if (!classSelect || !subjectGrid) {
        return;
      }

      const classId = Number(classSelect.value || 0);
      const list = subjectDirectory[classId] || [];

      if (!classId) {
        subjectGrid.innerHTML = '<div class="hint" style="margin:0;">Choose a class to load subjects.</div>';
        return;
      }

      if (!list.length) {
        subjectGrid.innerHTML = '<div class="hint" style="margin:0;">No subjects found for the selected class.</div>';
        return;
      }

      subjectGrid.innerHTML = list.map(subject => {
        return `<label class="subject-item"><input type="checkbox" name="subjects[]" value="${subject.id}"><span>${subject.name}</span></label>`;
      }).join('');
    }

    if (classSelect) {
      classSelect.addEventListener('change', renderSubjectsForClass);
      renderSubjectsForClass();
    }

    wireSelectSearch(teacherSearch, teacherSelect, {
      defaultLabel: 'Choose teacher',
      emptyLabel: 'No matching teachers'
    });

    wireSelectSearch(classSearch, classSelect, {
      defaultLabel: 'Choose class',
      emptyLabel: 'No matching classes'
    });

    const menuButtons = Array.from(document.querySelectorAll('#hopMenu button'));
    const views = Array.from(document.querySelectorAll('.view'));
    const hopDeskProgressChip = document.getElementById('hopDeskProgressChip');

    function openView(viewId) {
      // Explicitly remove active class from ALL views
      views.forEach(view => {
        view.classList.remove('active');
      });
      
      // Explicitly add active class to target view
      if (viewId) {
        const targetView = document.getElementById(viewId);
        if (targetView) {
          targetView.classList.add('active');
        }
      }
      
      // Explicitly remove active class from ALL buttons
      menuButtons.forEach(button => {
        button.classList.remove('active');
      });
      
      // Explicitly add active class to matching button
      if (viewId) {
        const matchingBtn = menuButtons.find(button => button.dataset.target === viewId);
        if (matchingBtn) {
          matchingBtn.classList.add('active');
        }
      }

      const activeIndex = menuButtons.findIndex(button => button.classList.contains('active'));
      if (hopDeskProgressChip && activeIndex >= 0) {
        const activeBtn = menuButtons[activeIndex] || null;
        const activeLabel = String(activeBtn?.childNodes?.[0]?.textContent || activeBtn?.textContent || 'Current Section').trim().replace(/\s+/g, ' ');
        hopDeskProgressChip.textContent = `Step ${activeIndex + 1} of ${menuButtons.length} | ${activeLabel}`;
      }
    }

    menuButtons.forEach(button => {
      button.addEventListener('click', function () {
        openView(String(this.dataset.target || ''));
      });
    });

    openView('hopHomeView');
  </script>
  <?php output_select_search_script(); ?>
  <footer style="text-align:center;padding:14px 0 10px;font-size:0.8rem;color:#8a9ab0;opacity:0.7;">Developed by Ngwenya Jonas &copy; 2026</footer>
</body>
</html>
