<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>

<div class="container my-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0"><?= esc($title ?? ($isCreate ? 'Create Inventory Movement' : 'Edit Inventory Movement')) ?></h3>
    <a href="<?= site_url('inventory/movements') ?>" class="btn btn-outline-secondary">Back to List</a>
  </div>

  <?php if (session()->getFlashdata('status')): ?>
    <div class="alert alert-<?= session('status') === 'success' ? 'success' : 'danger' ?>">
      <?= esc(session('message')) ?>
    </div>
  <?php endif; ?>

  <?php if (isset($validation) && $validation->getErrors()): ?>
    <div class="alert alert-danger">
      <ul class="mb-0">
        <?php foreach ($validation->getErrors() as $e): ?>
          <li><?= esc($e) ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

  <form action="<?= esc($action) ?>" method="post" class="card shadow-sm">
    <?= csrf_field() ?>
    <div class="card-body">
      <!-- =============== Item =============== -->
      <div class="mb-3">
        <label class="form-label">Item <span class="text-danger">*</span></label>

        <?php if (!empty($isCreate)): ?>
          <select name="item_id" class="form-select" required>
            <option value="">-- Select Item --</option>
            <?php
              $oldItem = old('item_id', $movement['item_id'] ?? '');
              foreach ($items as $it):
                $selected = (string)$oldItem === (string)$it['id'] ? 'selected' : '';
            ?>
              <option value="<?= esc($it['id']) ?>" <?= $selected ?>>
                <?= esc($it['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        <?php else: ?>
          <!-- Lock item on edit (history integrity). Keep hidden field to submit original value -->
          <input type="hidden" name="item_id" value="<?= esc($movement['item_id']) ?>">
          <input type="text" class="form-control" value="<?= esc($movement['item_name'] ?? $movement['item_id']) ?>" disabled>
          <div class="form-text">Item cannot be changed after creation.</div>
        <?php endif; ?>
      </div>

      <!-- =============== Qty Change & Type =============== -->
      <div class="row">
        <div class="col-md-6 mb-3">
          <label class="form-label">Quantity Change <span class="text-danger">*</span></label>
          <input
            type="number"
            name="qty_change"
            required
            class="form-control"
            value="<?= esc(old('qty_change', $movement['qty_change'] ?? 0)) ?>"
          >
          <div class="form-text">
            Use negative values for outbound movements if type is <code>out</code> (or set type accordingly).
          </div>
        </div>

        <div class="col-md-6 mb-3">
          <label class="form-label">Movement Type <span class="text-danger">*</span></label>
          <select name="movement_type" class="form-select" required>
            <?php
              $oldType = old('movement_type', $movement['movement_type'] ?? 'adjust');
              foreach ($movementTypes as $t):
                $sel = $oldType === $t ? 'selected' : '';
            ?>
              <option value="<?= esc($t) ?>" <?= $sel ?>><?= ucfirst($t) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <!-- =============== Reason & Note =============== -->
      <div class="mb-3">
        <label class="form-label">Reason</label>
        <input
          type="text"
          name="reason"
          maxlength="120"
          class="form-control"
          value="<?= esc(old('reason', $movement['reason'] ?? '')) ?>"
          placeholder="Short reason (max 120 chars)"
        >
      </div>

      <div class="mb-3">
        <label class="form-label">Note</label>
        <textarea
          name="note"
          class="form-control"
          rows="3"
          placeholder="Any additional details about this movement..."
        ><?= esc(old('note', $movement['note'] ?? '')) ?></textarea>
      </div>

      <!-- =============== Semester & School Year =============== -->
      <div class="row">
        <div class="col-md-6 mb-3">
          <label class="form-label">Semester</label>
          <select name="semester" class="form-select">
            <option value="">-- None --</option>
            <?php
              $oldSem = old('semester', $movement['semester'] ?? '');
              foreach ($semesters as $sem):
                $sel = $oldSem === $sem ? 'selected' : '';
            ?>
              <option value="<?= esc($sem) ?>" <?= $sel ?>><?= esc($sem) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-6 mb-3">
          <label class="form-label">School Year</label>
          <input
            type="text"
            name="school_year"
            class="form-control"
            value="<?= esc(old('school_year', $movement['school_year'] ?? '')) ?>"
            placeholder="e.g., 2025-2026"
          >
        </div>
      </div>

      <!-- =============== Optional Relations =============== -->
      <div class="row">
        <!-- Teachers / TAs from TeacherModel::getTeachersAndTAs() -->
        <div class="col-md-4 mb-3">
          <label class="form-label">Teacher (optional)</label>
          <select name="teacher_id" class="form-select">
            <option value="">-- None --</option>
            <?php
              $oldTeacher = (string) old('teacher_id', (string) ($movement['teacher_id'] ?? ''));
              foreach ($teachers as $t):
                $sel = $oldTeacher === (string)$t['id'] ? 'selected' : '';
            ?>
              <option value="<?= esc($t['id']) ?>" <?= $sel ?>>
                <?= esc($t['fullname']) ?> (<?= esc(ucfirst($t['role'])) ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Students (expects id + fullname; adjust if your array key is different) -->
        <div class="col-md-4 mb-3">
          <label class="form-label">Student (optional)</label>
          <select name="student_id" class="form-select">
            <option value="">-- None --</option>
            <?php
              $oldStudent = (string) old('student_id', (string) ($movement['student_id'] ?? ''));
              foreach ($students as $s):
                $sel = $oldStudent !== '' && $oldStudent === (string)$s['id'] ? 'selected' : '';
            ?>
              <option value="<?= esc($s['id']) ?>" <?= $sel ?>><?= esc($s['fullname']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-4 mb-3">
          <label class="form-label">Class Section (optional)</label>
          <select name="class_section_id" class="form-select">
            <option value="">-- None --</option>
            <?php
              $oldSection = (string) old('class_section_id', (string) ($movement['class_section_id'] ?? ''));
              foreach ($classSections as $cs):
                $value = (string)$cs['class_section_id']; // using CODE per your schema
                $sel   = $oldSection !== '' && $oldSection === $value ? 'selected' : '';
            ?>
              <option value="<?= esc($value) ?>" <?= $sel ?>><?= esc($cs['class_section_name']) ?></option>
            <?php endforeach; ?>
          </select>
          <div class="form-text">Uses the <strong>class_section_id</strong> code (not PK).</div>
        </div>
      </div>

      <?php if (!$isCreate): ?>
        <hr>
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Performed By</label>
            <input type="text" class="form-control"
                   value="<?= esc($movement['performed_by_name'] ?? $movement['performed_by'] ?? '—') ?>" disabled>
          </div>
          <div class="col-md-4">
            <label class="form-label">Created At</label>
            <input type="text" class="form-control" value="<?= esc(!empty($movement['created_at']) ? local_datetime($movement['created_at'], 'm-d-Y H:i') : '—') ?>" disabled>
          </div>
          <div class="col-md-4">
            <label class="form-label">Last Updated</label>
            <input type="text" class="form-control" value="<?= esc(!empty($movement['updated_at']) ? local_datetime($movement['updated_at'], 'm-d-Y H:i') : '—') ?>" disabled>
          </div>
        </div>
      <?php endif; ?>
    </div>

    <div class="card-footer d-flex gap-2">
      <button type="submit" class="btn btn-primary"><?= $isCreate ? 'Create Movement' : 'Save Changes' ?></button>
      <a href="<?= site_url('inventory/movements') ?>" class="btn btn-secondary">Cancel</a>
    </div>
  </form>
</div>

<?= $this->endSection() ?>
