<?php /* units/index.php */
$active   = array_filter($units, fn($u) => isset($u['status']) ? $u['status']==='active' : true);
$totalProducts = array_sum(array_column($units,'product_count'));

// Common units reference
$commonUnits = [
  ['Kilogram','kg','Weight'],['Gram','g','Weight'],['Litre','L','Volume'],
  ['Millilitre','ml','Volume'],['Piece','pcs','Count'],['Dozen','doz','Count'],
  ['Box','box','Package'],['Packet','pkt','Package'],['Bottle','btl','Package'],
  ['Bag','bag','Package'],['Meter','m','Length'],['Centimeter','cm','Length'],
];
$existingNames = array_map(fn($u)=>strtolower($u['unit_name']), $units);
?>

<style>
.un-hero{background:linear-gradient(135deg,#134e4a,#0f766e 55%,#14b8a6);
  border-radius:12px;padding:18px 22px;color:#fff;margin-bottom:16px}
.unit-table th{font-size:.72rem;padding:8px 12px}
.unit-table td{font-size:.8rem;padding:8px 12px;vertical-align:middle}
.unit-table tr:hover td{background:#f0fdfa}
.short-badge{display:inline-block;padding:3px 10px;border-radius:8px;
  font-size:.78rem;font-weight:800;background:#f0fdfa;
  color:#0d9488;border:1.5px solid #99f6e4;font-family:monospace;letter-spacing:.05em}
.quick-unit{border:1.5px dashed #a7f3d0;border-radius:8px;padding:7px 12px;
  cursor:pointer;transition:all .12s;font-size:.75rem;font-weight:600;
  color:#0f766e;background:#f0fdfa;text-align:center;display:block}
.quick-unit:hover{background:#ccfbf1;border-color:#0d9488;border-style:solid}
.quick-unit .short{font-size:.65rem;color:#14b8a6;display:block;margin-top:2px;font-family:monospace}
</style>

<!-- Hero -->
<div class="un-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1"><i class="bi bi-rulers me-2"></i>Units of Measurement</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=count($units)?> units defined &nbsp;·&nbsp;
        <?=$totalProducts?> products using units
      </div>
    </div>
    <?php if(Auth::can('products.create')):?>
    <button class="btn btn-light btn-sm fw-semibold" style="color:#0f766e"
            data-bs-toggle="modal" data-bs-target="#addUnitModal">
      <i class="bi bi-plus-circle me-1"></i>Add Unit
    </button>
    <?php endif;?>
  </div>
</div>

<?= flashMessages() ?>

<div class="row g-3">

  <!-- Left: Units table -->
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
        <span><i class="bi bi-rulers me-1"></i>Defined Units</span>
        <span class="badge bg-secondary"><?=count($units)?></span>
      </div>
      <div class="table-responsive">
        <table class="table table-sm table-hover mb-0 unit-table">
          <thead class="table-secondary">
            <tr>
              <th class="ps-3">#</th>
              <th>Unit Name</th>
              <th class="text-center">Short Code</th>
              <th class="text-center">Products</th>
              <th class="text-center">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if(empty($units)):?>
            <tr>
              <td colspan="5" class="text-center text-muted py-4">
                <i class="bi bi-rulers d-block fs-3 mb-2 opacity-25"></i>
                No units defined yet.
                <?php if(Auth::can('products.create')):?>
                <div class="mt-2">
                  <button class="btn btn-sm btn-outline-teal"
                          style="color:#0f766e;border-color:#0f766e"
                          data-bs-toggle="modal" data-bs-target="#addUnitModal">
                    Add first unit
                  </button>
                </div>
                <?php endif;?>
              </td>
            </tr>
            <?php endif;?>

            <?php foreach($units as $i=>$unit):?>
            <tr>
              <td class="ps-3 text-muted small"><?=$i+1?></td>

              <!-- Unit Name -->
              <td>
                <div class="fw-semibold"><?=e($unit['unit_name'])?></div>
              </td>

              <!-- Short Code -->
              <td class="text-center">
                <span class="short-badge"><?=e($unit['short_name'])?></span>
              </td>

              <!-- Products -->
              <td class="text-center">
                <?php if($unit['product_count']>0):?>
                <a href="<?=APP_URL?>/products?unit=<?=$unit['id']?>"
                   class="badge bg-primary text-decoration-none"
                   style="font-size:.68rem">
                  <?=$unit['product_count']?> product<?=$unit['product_count']!=1?'s':''?>
                </a>
                <?php else:?>
                <span class="text-muted small">—</span>
                <?php endif;?>
              </td>

              <!-- Actions -->
              <td class="text-center">
                <div class="d-flex gap-1 justify-content-center">
                  <?php if(Auth::can('products.edit')):?>
                  <button class="btn btn-sm btn-outline-secondary py-0 px-2"
                          onclick="editUnit(<?=$unit['id']?>,'<?=e(addslashes($unit['unit_name']))?>','<?=e(addslashes($unit['short_name']))?>')"
                          title="Edit">
                    <i class="bi bi-pencil"></i>
                  </button>
                  <?php endif;?>
                  <?php if(Auth::can('products.delete') && $unit['product_count']==0):?>
                  <form method="POST" action="<?=APP_URL?>/units/delete/<?=$unit['id']?>"
                        onsubmit="return confirm('Delete unit: <?=e($unit['unit_name'])?>?')">
                    <?=Auth::csrfField()?>
                    <button class="btn btn-sm btn-outline-danger py-0 px-1" title="Delete">
                      <i class="bi bi-trash3"></i>
                    </button>
                  </form>
                  <?php endif;?>
                </div>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
          <?php if(!empty($units)):?>
          <tfoot class="table-secondary" style="font-size:.72rem">
            <tr>
              <td colspan="3" class="ps-3 fw-bold">TOTAL (<?=count($units)?> units)</td>
              <td class="text-center fw-bold"><?=$totalProducts?></td>
              <td></td>
            </tr>
          </tfoot>
          <?php endif;?>
        </table>
      </div>
    </div>
  </div>

  <!-- Right: Quick add common units -->
  <div class="col-lg-5">
    <div class="card">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-lightning me-1 text-warning"></i>Quick Add Common Units
        <span class="text-muted fw-normal">(click to add)</span>
      </div>
      <div class="card-body">
        <?php
        $groups = ['Weight'=>[],'Volume'=>[],'Count'=>[],'Package'=>[],'Length'=>[]];
        foreach($commonUnits as $cu) {
            $groups[$cu[2]][] = $cu;
        }
        ?>
        <?php foreach($groups as $grpName=>$items):?>
        <div class="mb-3">
          <div class="text-muted small fw-bold mb-2"
               style="font-size:.65rem;text-transform:uppercase;letter-spacing:.06em">
            <?=$grpName?>
          </div>
          <div class="d-flex flex-wrap gap-2">
            <?php foreach($items as[$uname,$ushort,$ugrp]):
              $already = in_array(strtolower($uname), $existingNames, true);
            ?>
            <?php if($already):?>
            <span class="quick-unit"
                  style="opacity:.4;cursor:not-allowed;border-style:solid;
                         background:#f0fdf4;border-color:#86efac;color:#16a34a">
              <i class="bi bi-check2 me-1"></i><?=$uname?>
              <span class="short"><?=$ushort?> ✓</span>
            </span>
            <?php else:?>
            <form method="POST" action="<?=APP_URL?>/units/store" style="display:inline">
              <?=Auth::csrfField()?>
              <input type="hidden" name="unit_name"  value="<?=e($uname)?>">
              <input type="hidden" name="short_name" value="<?=e($ushort)?>">
              <button type="submit" class="quick-unit" style="border:none"
                      title="Add <?=$uname?> (<?=$ushort?>)">
                <?=$uname?>
                <span class="short"><?=$ushort?></span>
              </button>
            </form>
            <?php endif;?>
            <?php endforeach;?>
          </div>
        </div>
        <?php endforeach;?>
      </div>
    </div>
  </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addUnitModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:380px">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h6 class="modal-title fw-bold"><i class="bi bi-plus-circle me-2"></i>Add Unit</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?=APP_URL?>/units/store">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">
              Unit Name <span class="text-danger">*</span>
            </label>
            <input type="text" name="unit_name" class="form-control fw-semibold"
                   placeholder="e.g. Kilogram, Litre, Piece…"
                   required autofocus>
          </div>
          <div>
            <label class="form-label small fw-semibold">
              Short Code <span class="text-danger">*</span>
            </label>
            <input type="text" name="short_name" class="form-control"
                   placeholder="e.g. kg, L, pcs"
                   maxlength="10" required>
            <div class="form-text">Shown in POS and product labels</div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary fw-semibold">
            <i class="bi bi-check-circle me-1"></i>Add Unit
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editUnitModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:380px">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h6 class="modal-title fw-bold"><i class="bi bi-pencil me-2"></i>Edit Unit</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form id="editUnitForm" method="POST">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">Unit Name <span class="text-danger">*</span></label>
            <input type="text" name="unit_name" id="editUnitName"
                   class="form-control fw-semibold" required>
          </div>
          <div>
            <label class="form-label small fw-semibold">Short Code <span class="text-danger">*</span></label>
            <input type="text" name="short_name" id="editUnitShort"
                   class="form-control" maxlength="10" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary fw-semibold">
            <i class="bi bi-check-circle me-1"></i>Save Changes
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function editUnit(id, name, short) {
  document.getElementById('editUnitForm').action  = '<?=APP_URL?>/units/update/' + id;
  document.getElementById('editUnitName').value   = name;
  document.getElementById('editUnitShort').value  = short;
  new bootstrap.Modal(document.getElementById('editUnitModal')).show();
}
</script>