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

<?php
  // Safe defaults so "create" doesn't blow up
  $item   = isset($item) && is_array($item) ? $item : [];
  $isEdit = !empty($item['id']);
  $itemId = $isEdit ? (int)$item['id'] : null;
  $action = $isEdit ? site_url('inventory/update/'.$itemId) : site_url('inventory/store');

  // Buckets / on-hand (robust defaults)
  $onHand         = (int)($item['quantity'] ?? 0);
  $needsRepairQty = (int)($item['needs_repair_qty'] ?? 0);
  $lossQty        = (int)($item['need_replace_qty'] ?? 0);
  $missingQty     = (int)($item['cannot_find_qty']  ?? 0);
  $goodCalc       = max(0, $onHand - $needsRepairQty);

  // Lists
  $categories       = isset($categories) && is_array($categories) ? $categories : [];
  $conditionOptions = isset($conditionOptions) && is_array($conditionOptions) ? $conditionOptions : [
    'good'          => 'Good condition',
    'needs_repair'  => 'Needs repair',
    'need_replace'  => 'Need replace',
    'cannot_find'   => 'Cannot find',
  ];
?>

<div class="container my-4">
  <!-- Top bar: Items / Adjust / Audit -->
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0"><?= $isEdit ? 'Edit' : 'Add' ?> Classroom Item</h3>
    <div class="btn-group">
      <a class="btn btn-sm btn-outline-secondary" href="<?= site_url('inventory/classroom') ?>">Items</a>
      <?php if ($isEdit): ?>
        <a class="btn btn-sm btn-outline-secondary" href="<?= site_url('inventory/adjust/'.$itemId) ?>">Adjust Stock</a>
        <a class="btn btn-sm btn-outline-secondary" href="<?= site_url('inventory/classroom/audit/'.$itemId) ?>">Audit</a>
      <?php endif; ?>
    </div>
  </div>

  <?= view('partials/flash_messages') ?>

  <form method="post" action="<?= $action ?>">
    <?= csrf_field() ?>
    <input type="hidden" name="type" value="classroom">

    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label">Name</label>
        <input class="form-control" name="name" required value="<?= esc($item['name'] ?? '') ?>">
      </div>

      <div class="col-md-6">
        <label class="form-label">Category</label>
        <select class="form-select" name="category_id">
          <option value="">— None —</option>
          <?php foreach ($categories as $c): ?>
            <option value="<?= esc($c['id'] ?? '') ?>"
              <?= isset($item['category_id']) && (int)$item['category_id'] === (int)($c['id'] ?? 0) ? 'selected' : '' ?>>
              <?= esc($c['name'] ?? '') ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-4">
        <label class="form-label">Condition (overall)</label>
        <select class="form-select" name="condition">
          <option value="">— Select —</option>
          <?php foreach ($conditionOptions as $val => $label): ?>
            <option value="<?= esc($val) ?>"
              <?= (isset($item['condition']) && $item['condition'] === $val) ? 'selected' : '' ?>>
              <?= esc($label) ?>
            </option>
          <?php endforeach; ?>
        </select>
        <div class="form-text">Quick overall tag. Detailed states shown below.</div>
      </div>

      <div class="col-md-2">
        <label class="form-label">Quantity</label>
        <input type="number" min="0" class="form-control" name="quantity"
               value="<?= esc($onHand) ?>" <?= $isEdit ? 'readonly' : '' ?>>
        <?php if ($isEdit): ?>
          <div class="form-text">
            Change on-hand via <a href="<?= site_url('inventory/adjust/'.$itemId) ?>">Adjust Stock</a>.
          </div>
        <?php endif; ?>
      </div>

      <div class="col-md-2">
        <label class="form-label">Unit</label>
        <input class="form-control" name="unit" placeholder="pcs, set, box" value="<?= esc($item['unit'] ?? '') ?>">
      </div>

      <div class="col-md-4">
        <label class="form-label">SKU</label>
        <input class="form-control" name="sku" value="<?= esc($item['sku'] ?? '') ?>">
      </div>

      <div class="col-12">
        <label class="form-label">Description / Notes</label>
        <textarea class="form-control" rows="3" name="description"><?= esc($item['description'] ?? '') ?></textarea>
      </div>
    </div>

    <!-- Item State table -->
    <div class="card mt-4">
      <div class="card-header">Item State</div>
      <div class="card-body table-responsive">
        <table class="table table-sm align-middle">
          <thead class="table-light">
            <tr>
              <th>State</th>
              <th class="text-end">Count</th>
              <th>Included in On-Hand?</th>
              <th>Notes</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><strong>On Hand (now)</strong></td>
              <td class="text-end"><strong><?= $onHand ?></strong></td>
              <td>—</td>
              <td>Sum of movements; authoritative stock.</td>
            </tr>
            <tr>
              <td>Good</td>
              <td class="text-end"><?= $goodCalc ?></td>
              <td>Yes</td>
              <td>Available to use (derived = On Hand − Needs Repair).</td>
            </tr>
            <tr>
              <td>Needs Repair</td>
              <td class="text-end"><?= $needsRepairQty ?></td>
              <td>Yes</td>
              <td>Unavailable until fixed.</td>
            </tr>
            <tr>
              <td>Total Loss</td>
              <td class="text-end"><?= $lossQty ?></td>
              <td>No</td>
              <td>Deducted via audit (Out).</td>
            </tr>
            <tr>
              <td>Cannot Find</td>
              <td class="text-end"><?= $missingQty ?></td>
              <td>No</td>
              <td>Deducted via audit (Out).</td>
            </tr>
          </tbody>
          <tfoot>
            <tr class="table-light">
              <th>Available to Use</th>
              <th class="text-end"><?= $goodCalc ?></th>
              <th colspan="2"></th>
            </tr>
            <tr class="table-light">
              <th>Unavailable but On-Hand (Repair)</th>
              <th class="text-end"><?= $needsRepairQty ?></th>
              <th colspan="2"></th>
            </tr>
            <tr class="table-light">
              <th>Removed (Loss + Missing)</th>
              <th class="text-end"><?= $lossQty + $missingQty ?></th>
              <th colspan="2"></th>
            </tr>
          </tfoot>
        </table>
        <div class="small text-muted">
          Update states via <strong>Audit</strong>; stock movements are created automatically.
        </div>
      </div>
    </div>

    <div class="mt-3 d-flex gap-2">
      <button class="btn btn-primary"><?= $isEdit ? 'Update' : 'Save' ?></button>
      <a class="btn btn-outline-secondary" href="<?= site_url('inventory/classroom') ?>">Cancel</a>
    </div>
  </form>

  <?php if ($isEdit && !empty($item['updated_at'])): ?>
    <div class="text-muted mt-3">
      <small>Updated Date: <?= esc(local_datetime($item['updated_at'], 'm-d-Y H:i')) ?></small>
    </div>
  <?php endif; ?>
</div>

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