<?php
require_once __DIR__ . '/../../admin/_nav.php';
$pageTitle  = htmlspecialchars($teacher['name']);
$sidebarNav = adminNav();
$u = function($p) { return \Core\View::url($p); };
?>
<div class="page-header">
  <div style="display:flex;align-items:center;gap:16px">
    <div class="avatar" style="width:56px;height:56px;font-size:22px"><?= strtoupper(substr($teacher['name'],0,1)) ?></div>
    <div>
      <h1><?= htmlspecialchars($teacher['name']) ?></h1>
      <p>
        <?= htmlspecialchars($teacher['email']) ?>
        <?php if($teacher['tsc_no']): ?> &bull; TSC: <?= htmlspecialchars($teacher['tsc_no']) ?><?php endif; ?>
        &bull; <span class="badge <?= $teacher['is_active']?'badge-success':'badge-danger' ?>"><?= $teacher['is_active']?'Active':'Inactive' ?></span>
      </p>
    </div>
  </div>
  <div style="display:flex;gap:8px">
    <button onclick="openModal('editTeacher')" class="btn btn-outline"><i class="bi bi-pencil"></i> Edit</button>
    <button onclick="openModal('resetPassword')" class="btn btn-secondary"><i class="bi bi-key"></i> Reset Password</button>
    <a href="<?= $u('admin/teachers') ?>" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Back</a>
  </div>
</div>

<!-- Info Cards -->
<div class="grid g4" style="margin-bottom:24px">
  <div class="stat-card">
    <div class="stat-icon si-blue"><i class="bi bi-person-badge"></i></div>
    <div class="stat-info"><h3><?= htmlspecialchars($teacher['tsc_no'] ?? 'N/A') ?></h3><p>TSC Number</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-briefcase"></i></div>
    <div class="stat-info"><h3><?= ucfirst($teacher['employment_type'] ?? 'Permanent') ?></h3><p>Employment Type</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-amber"><i class="bi bi-people"></i></div>
    <div class="stat-info"><h3><?= count($classTeacherOf) ?></h3><p>Class Teacher Of</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-book"></i></div>
    <div class="stat-info"><h3><?= count($subjectAssignments) ?></h3><p>Subject Assignments</p></div>
  </div>
</div>

<div class="grid g2">
  <!-- ── CLASS TEACHER ASSIGNMENT ─────────────────────────── -->
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-people-fill"></i> Class Teacher Assignment</h5>
      <button onclick="openModal('assignClass')" class="btn btn-sm btn-primary"><i class="bi bi-plus"></i> Assign</button>
    </div>
    <div class="card-body" style="padding:0">
      <?php if(empty($classTeacherOf)): ?>
      <div style="padding:30px;text-align:center;color:var(--gray)">
        <i class="bi bi-people" style="font-size:28px;display:block;margin-bottom:8px"></i>
        Not assigned as class teacher yet
      </div>
      <?php else: ?>
      <?php foreach($classTeacherOf as $s): ?>
      <div style="padding:14px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
        <div>
          <div style="font-weight:600"><?= htmlspecialchars($s['full_name']) ?></div>
          <div style="font-size:12px;color:var(--gray)">Capacity: <?= $s['capacity'] ?> learners</div>
        </div>
        <form method="POST" action="<?= $u('admin/teachers/'.$teacher['id'].'/remove-class-teacher') ?>">
          <?= \Core\View::csrf() ?>
          <input type="hidden" name="stream_id" value="<?= $s['id'] ?>">
          <button class="btn btn-sm btn-danger" onclick="return confirm('Remove class teacher assignment?')"><i class="bi bi-x"></i></button>
        </form>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>

  <!-- ── SUBJECT ASSIGNMENTS ─────────────────────────────── -->
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-book-half"></i> Subject Teacher Assignments</h5>
      <button onclick="openModal('assignSubject')" class="btn btn-sm btn-primary"><i class="bi bi-plus"></i> Assign</button>
    </div>
    <div class="card-body" style="padding:0">
      <?php if(empty($subjectAssignments)): ?>
      <div style="padding:30px;text-align:center;color:var(--gray)">
        <i class="bi bi-book" style="font-size:28px;display:block;margin-bottom:8px"></i>
        No subjects assigned yet
      </div>
      <?php else: ?>
      <?php
      // Group by term
      $byTerm = [];
      foreach($subjectAssignments as $a) $byTerm[$a['year_name'].' - '.$a['term_name']][] = $a;
      ?>
      <?php foreach($byTerm as $termLabel => $assignments): ?>
      <div style="padding:8px 20px;background:var(--light);font-size:11px;font-weight:600;color:var(--gray);text-transform:uppercase;letter-spacing:.5px"><?= htmlspecialchars($termLabel) ?></div>
      <?php foreach($assignments as $a): ?>
      <div style="padding:11px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
        <div>
          <div style="font-weight:500;font-size:13px">
            <span class="badge badge-info" style="margin-right:6px"><?= htmlspecialchars($a['code']) ?></span>
            <?= htmlspecialchars($a['subject_name']) ?>
          </div>
          <div style="font-size:12px;color:var(--gray);margin-top:2px"><i class="bi bi-people"></i> <?= htmlspecialchars($a['stream_name']) ?></div>
        </div>
        <form method="POST" action="<?= $u('admin/teachers/'.$teacher['id'].'/remove-subject') ?>">
          <?= \Core\View::csrf() ?>
          <input type="hidden" name="tss_id" value="<?= $a['id'] ?>">
          <button class="btn btn-sm btn-danger" onclick="return confirm('Remove this assignment?')"><i class="bi bi-x"></i></button>
        </form>
      </div>
      <?php endforeach; ?>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══ MODALS ════════════════════════════════════════════════ -->

<!-- Reset Password Modal -->
<div class="modal" id="resetPassword"><div class="modal-box" style="max-width:420px">
  <div class="card-header"><h5><i class="bi bi-key"></i> Reset Password</h5><button onclick="closeModal('resetPassword')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" action="<?= $u('admin/teachers/'.$teacher['id'].'/reset-password') ?>">
      <?= \Core\View::csrf() ?>
      <div class="form-group">
        <label>New Password *</label>
        <input type="password" name="password" required minlength="8" placeholder="Min 8 characters">
      </div>
      <div class="form-group">
        <label>Confirm Password *</label>
        <input type="password" name="password_confirmation" required minlength="8" placeholder="Repeat password">
      </div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-key"></i> Reset Password</button>
    </form>
  </div>
</div></div>
<div class="modal" id="editTeacher"><div class="modal-box" style="max-width:520px">
  <div class="card-header"><h5>Edit Teacher</h5><button onclick="closeModal('editTeacher')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" action="<?= $u('admin/teachers/'.$teacher['id'].'/update') ?>">
      <?= \Core\View::csrf() ?>
      <div class="grid g2">
        <div class="form-group"><label>Full Name *</label><input type="text" name="name" value="<?= htmlspecialchars($teacher['name']) ?>" required></div>
        <div class="form-group"><label>Phone</label><input type="text" name="phone" value="<?= htmlspecialchars($teacher['phone'] ?? '') ?>"></div>
        <div class="form-group"><label>TSC Number</label><input type="text" name="tsc_no" value="<?= htmlspecialchars($teacher['tsc_no'] ?? '') ?>"></div>
        <div class="form-group"><label>Employee No</label><input type="text" name="employee_no" value="<?= htmlspecialchars($teacher['employee_no'] ?? '') ?>"></div>
        <div class="form-group">
          <label>Employment Type</label>
          <select name="employment_type">
            <?php foreach(['permanent','contract','bom'] as $et): ?>
            <option value="<?= $et ?>" <?= ($teacher['employment_type']??'permanent')===$et?'selected':'' ?>><?= ucfirst($et) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group"><label>Joining Date</label><input type="date" name="joining_date" value="<?= $teacher['joining_date'] ?? '' ?>"></div>
      </div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Save Changes</button>
    </form>
  </div>
</div></div>

<!-- Assign Class Teacher -->
<div class="modal" id="assignClass"><div class="modal-box">
  <div class="card-header"><h5><i class="bi bi-people"></i> Assign as Class Teacher</h5><button onclick="closeModal('assignClass')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" action="<?= $u('admin/teachers/'.$teacher['id'].'/assign-class-teacher') ?>">
      <?= \Core\View::csrf() ?>
      <div class="form-group">
        <label>Select Stream / Grade *</label>
        <select name="stream_id" required>
          <option value="">-- Select Grade & Stream --</option>
          <?php foreach($streams as $s): ?>
          <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['full_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <p style="font-size:12px;color:var(--gray);margin-bottom:12px"><i class="bi bi-info-circle"></i> This will replace any existing class teacher for the selected stream.</p>
      <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg"></i> Assign Class Teacher</button>
    </form>
  </div>
</div></div>

<!-- Assign Subject Teacher -->
<div class="modal" id="assignSubject"><div class="modal-box">
  <div class="card-header"><h5><i class="bi bi-book"></i> Assign Subject</h5><button onclick="closeModal('assignSubject')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" action="<?= $u('admin/teachers/'.$teacher['id'].'/assign-subject') ?>">
      <?= \Core\View::csrf() ?>
      <div class="form-group">
        <label>Term *</label>
        <select name="term_id" required>
          <option value="">-- Select Term --</option>
          <?php foreach($terms as $t): ?>
          <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['year_name'].' - '.$t['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Grade Level *</label>
        <select id="filterBand" onchange="filterSubjectsAndStreams()" required>
          <option value="">-- Select Grade Level --</option>
          <option value="pre-primary">Pre-Primary (PP1–PP2)</option>
          <option value="lower-primary">Lower Primary (Grade 1–3)</option>
          <option value="upper-primary">Upper Primary (Grade 4–6)</option>
          <option value="junior-secondary">Junior Secondary (Grade 7–9)</option>
          <option value="senior-secondary">Senior Secondary (Grade 10–12)</option>
        </select>
      </div>
      <div class="form-group">
        <label>Subject / Learning Area *</label>
        <select name="subject_id" id="subjectSelect" required>
          <option value="">-- Select Grade Level first --</option>
        </select>
      </div>
      <div class="form-group">
        <label>Stream *</label>
        <select name="stream_id" id="streamSelect" required>
          <option value="">-- Select Grade Level first --</option>
        </select>
      </div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg"></i> Assign Subject</button>
    </form>
  </div>
</div></div>

<?php
// Build JS data maps
$subjectsByBand = [];
foreach ($subjects as $s) $subjectsByBand[$s['grade_band'] ?? 'other'][] = $s;
$streamsByBand = [];
foreach ($streams as $s) $streamsByBand[$s['grade_band'] ?? 'other'][] = $s;
?>
<?php $extraScripts = '<script>
const subjectsByBand = '.json_encode($subjectsByBand).';
const streamsByBand  = '.json_encode($streamsByBand).';

function filterSubjectsAndStreams() {
  const band = document.getElementById("filterBand").value;
  const subSel = document.getElementById("subjectSelect");
  const stSel  = document.getElementById("streamSelect");

  subSel.innerHTML = "<option value=\'\'>-- Select Subject --</option>";
  stSel.innerHTML  = "<option value=\'\'>-- Select Stream --</option>";

  if (!band) return;

  (subjectsByBand[band] || []).forEach(s => {
    const o = document.createElement("option");
    o.value = s.id;
    o.textContent = s.name + " (" + s.code + ")";
    subSel.appendChild(o);
  });

  (streamsByBand[band] || []).forEach(s => {
    const o = document.createElement("option");
    o.value = s.id;
    o.textContent = s.full_name || (s.class_name + " " + s.name);
    stSel.appendChild(o);
  });
}
</script>'; ?>
