<?php /* brands/index.php */
$active   = array_filter($brands, fn($b)=>$b['status']==='active');
$inactive = array_filter($brands, fn($b)=>$b['status']!=='active');
$totalProducts = array_sum(array_column($brands,'product_count'));
$maxProd  = max(array_column($brands,'product_count') ?: [1]);
?>

<style>
.br-hero{background:linear-gradient(135deg,#1e3a5f,#1d4ed8 55%,#3b82f6);
  border-radius:12px;padding:18px 22px;color:#fff;margin-bottom:16px}
.brand-card{border-radius:12px;border:1.5px solid #e2e8f0;overflow:hidden;
  transition:all .15s;height:100%}
.brand-card:hover{box-shadow:0 4px 16px rgba(0,0,0,.1);border-color:#bfdbfe}
.brand-logo{width:48px;height:48px;border-radius:10px;background:linear-gradient(135deg,#1d4ed8,#3b82f6);
  display:flex;align-items:center;justify-content:center;
  color:#fff;font-size:1.2rem;font-weight:900;flex-shrink:0}
.brand-count{width:28px;height:28px;border-radius:50%;background:#eff6ff;
  color:#1d4ed8;display:flex;align-items:center;justify-content:center;
  font-size:.7rem;font-weight:700;flex-shrink:0}
.prod-bar{height:5px;border-radius:3px;background:#e2e8f0}
.prod-bar-fill{height:5px;border-radius:3px;background:linear-gradient(90deg,#1d4ed8,#60a5fa)}
.add-brand-card{border-radius:12px;border:2px dashed #bfdbfe;background:#eff6ff;
  display:flex;flex-direction:column;align-items:center;justify-content:center;
  min-height:140px;cursor:pointer;transition:all .15s}
.add-brand-card:hover{border-color:#3b82f6;background:#dbeafe}
</style>

<!-- Hero -->
<div class="br-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-bookmark-fill me-2"></i>Brands</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=count($active)?> active brands &nbsp;·&nbsp;
        <?=$totalProducts?> products across all brands
      </div>
    </div>
    <?php if(Auth::can('products.create')):?>
    <button class="btn btn-light btn-sm fw-semibold" style="color:#1d4ed8"
            data-bs-toggle="modal" data-bs-target="#addBrandModal">
      <i class="bi bi-plus-circle me-1"></i>Add Brand
    </button>
    <?php endif;?>
  </div>
</div>

<?= flashMessages() ?>

<!-- Summary -->
<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 #1d4ed8">
      <div class="fw-bold fs-4" style="color:#1d4ed8"><?=count($active)?></div>
      <div class="text-muted small">Active Brands</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"><?=$totalProducts?></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">
        <?=count(array_filter($brands,fn($b)=>$b['product_count']>0))?>
      </div>
      <div class="text-muted small">With Products</div>
    </div>
  </div>
</div>

<!-- Brand Cards -->
<?php if(!empty($active)):?>
<div class="d-flex justify-content-between align-items-center mb-2">
  <span class="small fw-semibold text-muted text-uppercase">
    <i class="bi bi-check-circle text-success me-1"></i>Active (<?=count($active)?>)
  </span>
</div>
<div class="row g-2 mb-4">
  <?php foreach($active as $brand):
    $initials = strtoupper(substr($brand['brand_name'],0,2));
    $barW = $maxProd > 0 ? round($brand['product_count']/$maxProd*100) : 0;
  ?>
  <div class="col-6 col-md-4 col-lg-3">
    <div class="brand-card">
      <!-- Header -->
      <div class="p-3 d-flex align-items-center gap-2"
           style="background:linear-gradient(135deg,#f8fafc,#eff6ff)">
        <div class="brand-logo"><?=e($initials)?></div>
        <div class="flex-grow-1 min-w-0">
          <div class="fw-bold text-truncate"><?=e($brand['brand_name'])?></div>
          <div style="font-size:.65rem;color:#1d4ed8;font-weight:600">
            <?=$brand['product_count']?> product<?=$brand['product_count']!=1?'s':''?>
          </div>
        </div>
        <div class="brand-count"><?=$brand['product_count']?></div>
      </div>

      <div class="p-2">
        <!-- Bar -->
        <div class="prod-bar mb-2">
          <div class="prod-bar-fill" style="width:<?=$barW?>%"></div>
        </div>

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

        <!-- Actions -->
        <div class="d-flex gap-1">
          <?php if(Auth::can('products.view') && $brand['product_count']>0):?>
          <a href="<?=APP_URL?>/products?brand=<?=$brand['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="editBrand(<?=$brand['id']?>,'<?=e(addslashes($brand['brand_name']))?>','<?=e(addslashes($brand['description']??''))?>')"
                  title="Edit">
            <i class="bi bi-pencil"></i>
          </button>
          <?php endif;?>
          <?php if(Auth::can('products.delete')):?>
          <form method="POST" action="<?=APP_URL?>/brands/delete/<?=$brand['id']?>"
                class="brand-delete-form"
                data-has-products="<?= $brand['product_count']>0 ? '1' : '0' ?>"
                data-count="<?= $brand['product_count'] ?>"
                data-name="<?= e($brand['brand_name']) ?>">
            <?=Auth::csrfField()?>
            <button type="button" class="btn btn-sm btn-outline-danger py-0 px-1 brand-delete-btn"
                    title="<?= $brand['product_count']>0 ? 'Deactivate' : 'Delete' ?>">
              <i class="bi <?= $brand['product_count']>0 ? 'bi-archive' : 'bi-trash3' ?>"></i>
            </button>
          </form>
          <?php endif;?>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach;?>

  <!-- Add Brand Card -->
  <?php if(Auth::can('products.create')):?>
  <div class="col-6 col-md-4 col-lg-3">
    <div class="add-brand-card"
         onclick="new bootstrap.Modal(document.getElementById('addBrandModal')).show()">
      <i class="bi bi-plus-circle fs-2 text-primary mb-1"></i>
      <div class="small fw-semibold text-primary">Add Brand</div>
    </div>
  </div>
  <?php endif;?>
</div>
<?php endif;?>

<!-- Inactive Brands -->
<?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 Brands (<?=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 $b):?>
          <tr class="opacity-60">
            <td class="ps-3 fw-semibold small"><?=e($b['brand_name'])?></td>
            <td class="text-muted small"><?=e($b['description']??'')?></td>
            <td class="text-center text-muted small"><?=$b['product_count']?> products</td>
            <td class="text-center pe-3">
              <?php if(Auth::can('products.edit')):?>
              <button class="btn btn-sm btn-outline-success py-0 px-2"
                      onclick="editBrand(<?=$b['id']?>,'<?=e(addslashes($b['brand_name']))?>','<?=e(addslashes($b['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="addBrandModal" 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 Brand</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?=APP_URL?>/brands/store">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">
              Brand Name <span class="text-danger">*</span>
            </label>
            <input type="text" name="brand_name" class="form-control fw-semibold"
                   placeholder="e.g. Nestlé, Araliya, Maliban…" required autofocus>
          </div>
          <div>
            <label class="form-label small fw-semibold">Description</label>
            <textarea name="description" class="form-control" rows="2"
                      placeholder="Optional…"></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 Brand
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editBrandModal" 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 Brand</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form id="editBrandForm" method="POST">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">
              Brand Name <span class="text-danger">*</span>
            </label>
            <input type="text" name="brand_name" id="editBrandName"
                   class="form-control fw-semibold" required>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Description</label>
            <textarea name="description" id="editBrandDesc"
                      class="form-control" rows="2"></textarea>
          </div>
          <div>
            <label class="form-label small fw-semibold">Status</label>
            <select name="status" id="editBrandStatus" 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 editBrand(id, name, desc) {
  document.getElementById('editBrandForm').action = '<?=APP_URL?>/brands/update/' + id;
  document.getElementById('editBrandName').value  = name;
  document.getElementById('editBrandDesc').value  = desc;
  new bootstrap.Modal(document.getElementById('editBrandModal')).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('.brand-delete-btn').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = btn.closest('.brand-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 brand 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>