<?php /** @var array $rows */ ?>
<div class="topbar">
  <div>
    <h2>المقاولون</h2>
    <div class="small">إدارة المقاولين وربطهم بالعقود والصيانة.</div>
  </div>
  <div>
    <?php if (auth_can('manage_contractors')): ?>
      <a class="btn primary" href="<?= e(url('/index.php?page=contractors&action=create')) ?>">إضافة مقاول</a>
    <?php endif; ?>
  </div>
</div>

<form class="card" method="get" action="<?= e(url('/index.php')) ?>">
  <input type="hidden" name="page" value="contractors">
  <div class="grid" style="grid-template-columns: 1fr 180px 120px">
    <div>
      <label class="small">بحث</label>
      <input class="input" name="q" value="<?= e($_GET['q'] ?? '') ?>" placeholder="اسم/رمز/هاتف/بريد">
    </div>
    <div>
      <label class="small">نشط فقط</label>
      <select class="input" name="active">
        <option value="">الكل</option>
        <option value="1" <?= (($_GET['active'] ?? '')==='1')?'selected':'' ?>>نعم</option>
      </select>
    </div>
    <div style="display:flex;align-items:end;gap:8px">
      <button class="btn">بحث</button>
      <a class="btn" href="<?= e(url('/index.php?page=contractors')) ?>">إعادة ضبط</a>
    </div>
  </div>
</form>

<div class="card">
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th>الرمز</th>
        <th>الاسم</th>
        <th>الهاتف</th>
        <th>البريد</th>
        <th>الحالة</th>
        <th>العقود</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="8" class="small">لا توجد بيانات.</td></tr>
      <?php endif; ?>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= e((string)$r['id']) ?></td>
          <td><span class="tag"><?= e($r['code']) ?></span></td>
          <td><?= e($r['name']) ?></td>
          <td><?= e($r['phone'] ?? '-') ?></td>
          <td><?= e($r['email'] ?? '-') ?></td>
          <td><?= intval($r['is_active'])===1 ? '<span class="tag ok">نشط</span>' : '<span class="tag danger">موقوف</span>' ?></td>
          <td><?= e((string)($r['contracts_count'] ?? 0)) ?></td>
          <td style="white-space:nowrap">
            <?php if (auth_can('manage_contractors')): ?>
              <a class="btn" href="<?= e(url('/index.php?page=contractors&action=edit&id='.(int)$r['id'])) ?>">تعديل</a>
              <a class="btn danger" href="<?= e(url('/index.php?page=contractors&action=delete&id='.(int)$r['id'])) ?>">حذف</a>
            <?php endif; ?>
            <?php if (auth_can('view_contracts')): ?>
              <a class="btn" href="<?= e(url('/index.php?page=contracts&contractor_id='.(int)$r['id'])) ?>">عقود</a>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
