<?php /* categories/index.php */
$sym    = setting('currency_symbol','Rs.');
$active = array_filter($categories, fn($c)=>$c['status']==='active');
$inactive = array_filter($categories, fn($c)=>$c['status']!=='active');
?>

<style>
.cat-hero{background:linear-gradient(135deg,#312e81,#4f46e5 60%,#818cf8);
  border-radius:12px;padding:18px 22px;color:#fff;margin-bottom:16px}
.cat-card{border-radius:10px;border:1.5px solid #e2e8f0;overflow:hidden;
  transition:box-shadow .15s;height:100%}
.cat-card:hover{box-shadow:0 4px 16px rgba(0,0,0,.08);border-color:#c7d2fe}
.cat-card-header{padding:14px;background:#f5f3ff;border-bottom:1px solid #e2e8f0;
  display:flex;align-items:center;gap:10px}
.cat-icon{width:40px;height:40px;border-radius:10px;background:#4f46e5;
  display:flex;align-items:center;justify-content:center;
  font-size:1.1rem;color:#fff;flex-shrink:0}
.cat-badge{display:inline-flex;align-items:center;justify-content:center;
  width:26px;height:26px;border-radius:50%;
  font-size:.72rem;font-weight:700;flex-shrink:0}
.edit-form{display:none;padding:12px;background:#fafafa;border-top:1px solid #e2e8f0}
</style>

<!-- Hero -->
<div class="cat-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-tags me-2"></i>Categories</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=count($active)?> active categories &nbsp;·&nbsp;
        <?=array_sum(array_column(iterator_to_array((function() use($categories){
          foreach($categories as $c) yield $c;
        })()), 'product_count'))?> total products
      </div>
    </div>
    <?php if(Auth::can('products.create')):?>
    <button class="btn btn-light btn-sm fw-semibold" style="color:#4f46e5"
            data-bs-toggle="modal" data-bs-target="#addCatModal">
      <i class="bi bi-plus-circle me-1"></i>Add Category
    </button>
    <?php endif;?>
  </div>
</div>

<?= flashMessages() ?>

<!-- Summary pills -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="card p-3 text-center" style="border-top:3px solid #4f46e5">
      <div class="fw-bold fs-4" style="color:#4f46e5"><?=count($active)?></div>
      <div class="text-muted small">Active Categories</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card p-3 text-center" style="border-top:3px solid #dc2626">
      <div class="fw-bold fs-4 text-danger"><?=count($inactive)?></div>
      <div class="text-muted small">Inactive</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card p-3 text-center" style="border-top:3px solid #16a34a">
      <div class="fw-bold fs-4 text-success">
        <?=array_sum(array_column($categories,'product_count'))?>
      </div>
      <div class="text-muted small">Total Products</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card p-3 text-center" style="border-top:3px solid #d97706">
      <div class="fw-bold fs-4 text-warning">
        <?php
        $withProd = count(array_filter($categories, fn($c)=>$c['product_count']>0));
        echo $withProd;
        ?>
      </div>
      <div class="text-muted small">With Products</div>
    </div>
  </div>
</div>

<!-- Category Cards Grid -->
<?php if(!empty($active)):?>
<div class="fw-semibold small text-muted mb-2 text-uppercase tracking-wide">
  <i class="bi bi-check-circle text-success me-1"></i>Active Categories (<?=count($active)?>)
</div>
<div class="row g-2 mb-4">
  <?php foreach($active as $cat):
    $pct = $cat['product_count'];
    $maxProd = max(array_column($categories,'product_count') ?: [1]);
    $barW = $maxProd > 0 ? round($pct/$maxProd*100) : 0;
  ?>
  <div class="col-6 col-md-4 col-lg-3">
    <div class="cat-card">
      <div class="cat-card-header">
        <div class="cat-icon"><i class="bi bi-tag-fill"></i></div>
        <div class="flex-grow-1 min-w-0">
          <div class="fw-bold small text-truncate"><?=e($cat['category_name'])?></div>
          <div style="font-size:.65rem;color:#6d28d9">
            <?=$cat['product_count']?> product<?=$cat['product_count']!=1?'s':''?>
          </div>
        </div>
        <div class="cat-badge" style="background:#ede9fe;color:#4f46e5">
          <?=$cat['product_count']?>
        </div>
      </div>

      <div class="p-2">
        <!-- Product count bar -->
        <div style="height:5px;background:#f1f5f9;border-radius:3px;margin-bottom:8px">
          <div style="height:5px;border-radius:3px;width:<?=$barW?>%;background:#4f46e5;transition:width .4s"></div>
        </div>

        <?php if($cat['description']):?>
        <div class="text-muted mb-2" style="font-size:.7rem">
          <?=e(substr($cat['description'],0,60)).(strlen($cat['description'])>60?'…':'')?>
        </div>
        <?php endif;?>

        <!-- Actions -->
        <div class="d-flex gap-1">
          <?php if(Auth::can('products.view')):?>
          <a href="<?=APP_URL?>/products?category=<?=$cat['id']?>"
             class="btn btn-sm btn-outline-primary py-0 px-2 flex-fill text-center"
             style="font-size:.68rem">
            <i class="bi bi-box-seam me-1"></i>Products
          </a>
          <?php endif;?>
          <?php if(Auth::can('products.edit')):?>
          <button class="btn btn-sm btn-outline-secondary py-0 px-2"
                  onclick="editCategory(<?=$cat['id']?>,'<?=e(addslashes($cat['category_name']))?>','<?=e(addslashes($cat['description']??''))?>')"
                  title="Edit">
            <i class="bi bi-pencil"></i>
          </button>
          <?php endif;?>
          <?php if(Auth::can('products.delete')):?>
          <form method="POST" action="<?=APP_URL?>/categories/delete/<?=$cat['id']?>"
                class="category-delete-form"
                data-has-products="<?= $cat['product_count']>0 ? '1' : '0' ?>"
                data-count="<?= $cat['product_count'] ?>"
                data-name="<?= e($cat['category_name']) ?>">
            <?=Auth::csrfField()?>
            <button type="button" class="btn btn-sm btn-outline-danger py-0 px-1 category-delete-btn"
                    title="<?= $cat['product_count']>0 ? 'Deactivate' : 'Delete' ?>">
              <i class="bi <?= $cat['product_count']>0 ? 'bi-archive' : 'bi-trash3' ?>"></i>
            </button>
          </form>
          <?php endif;?>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach;?>

  <!-- Add new card -->
  <?php if(Auth::can('products.create')):?>
  <div class="col-6 col-md-4 col-lg-3">
    <div class="cat-card d-flex align-items-center justify-content-center"
         style="min-height:120px;border-style:dashed;border-color:#c7d2fe;
                background:#f5f3ff;cursor:pointer"
         onclick="new bootstrap.Modal(document.getElementById('addCatModal')).show()">
      <div class="text-center">
        <i class="bi bi-plus-circle fs-2" style="color:#4f46e5"></i>
        <div class="small fw-semibold mt-1" style="color:#4f46e5">Add Category</div>
      </div>
    </div>
  </div>
  <?php endif;?>
</div>
<?php endif;?>

<!-- Inactive categories (collapsible) -->
<?php if(!empty($inactive)):?>
<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center py-2"
       style="cursor:pointer" onclick="toggleInactive()">
    <span class="fw-semibold small text-muted">
      <i class="bi bi-archive me-1"></i>Inactive Categories (<?=count($inactive)?>)
    </span>
    <i class="bi bi-chevron-down" id="inactiveChevron" style="font-size:.75rem;transition:transform .2s"></i>
  </div>
  <div id="inactiveList" style="display:none">
    <div class="table-responsive">
      <table class="table table-sm mb-0">
        <tbody>
          <?php foreach($inactive as $cat):?>
          <tr class="opacity-60">
            <td class="ps-3 small fw-semibold"><?=e($cat['category_name'])?></td>
            <td class="text-muted small"><?=e($cat['description']??'')?></td>
            <td class="text-center text-muted small"><?=$cat['product_count']?> products</td>
            <td class="text-center">
              <?php if(Auth::can('products.edit')):?>
              <button class="btn btn-sm btn-outline-success py-0 px-2"
                      onclick="editCategory(<?=$cat['id']?>,'<?=e(addslashes($cat['category_name']))?>','<?=e(addslashes($cat['description']??''))?>')"
                      style="font-size:.7rem">
                <i class="bi bi-arrow-clockwise me-1"></i>Restore
              </button>
              <?php endif;?>
            </td>
          </tr>
          <?php endforeach;?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php endif;?>

<!-- Add Modal -->
<div class="modal fade" id="addCatModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:420px">
    <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 Category</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?=APP_URL?>/categories/store">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">
              Category Name <span class="text-danger">*</span>
            </label>
            <input type="text" name="category_name" class="form-control fw-semibold"
                   placeholder="e.g. Electronics, Rice, Beverages…" required autofocus>
          </div>
          <div>
            <label class="form-label small fw-semibold">Description</label>
            <textarea name="description" class="form-control" rows="2"
                      placeholder="Optional description…"></textarea>
          </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 Category
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editCatModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:420px">
    <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 Category</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form id="editCatForm" method="POST">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">
              Category Name <span class="text-danger">*</span>
            </label>
            <input type="text" name="category_name" id="editCatName"
                   class="form-control fw-semibold" required>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Description</label>
            <textarea name="description" id="editCatDesc"
                      class="form-control" rows="2"></textarea>
          </div>
          <div>
            <label class="form-label small fw-semibold">Status</label>
            <select name="status" id="editCatStatus" class="form-select">
              <option value="active">✓ Active</option>
              <option value="inactive">✗ Inactive</option>
            </select>
          </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 editCategory(id, name, desc) {
  document.getElementById('editCatForm').action = '<?=APP_URL?>/categories/update/' + id;
  document.getElementById('editCatName').value  = name;
  document.getElementById('editCatDesc').value  = desc;
  new bootstrap.Modal(document.getElementById('editCatModal')).show();
}
function toggleInactive() {
  const el  = document.getElementById('inactiveList');
  const chv = document.getElementById('inactiveChevron');
  const open = el.style.display === 'block';
  el.style.display = open ? 'none' : 'block';
  chv.style.transform = open ? '' : 'rotate(180deg)';
}

document.querySelectorAll('.category-delete-btn').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = btn.closest('.category-delete-form');
    var hasProducts = form.getAttribute('data-has-products') === '1';
    var count = form.getAttribute('data-count');
    var name = form.getAttribute('data-name');
    var msg = hasProducts
      ? 'This category has ' + count + ' product(s) assigned and will be DEACTIVATED (not deleted). Continue?'
      : 'Permanently delete "' + name + '"? This cannot be undone.';
    if (confirm(msg)) {
      form.submit();
    }
  });
});
</script>