<?php
declare(strict_types=1);
require_once __DIR__ . '/queue_bootstrap.php';
qh_boot();
qh_admin_handle_request();

$stats = qh_admin_stats();
$clinics = qh_fetch_clinics();
$search = trim((string) ($_GET['q'] ?? ''));
$editId = (int) ($_GET['edit'] ?? 0);
$editClinic = $editId > 0 ? qh_fetch_clinic($editId) : null;

if ($editId > 0 && $editClinic === null) {
    qh_set_flash('warning', qh_t('The requested clinic record was not found.', 'لم يتم العثور على سجل العيادة المطلوب.'));
    qh_redirect('admin_clinics.php');
}

$toLower = static function (string $value): string {
    return function_exists('mb_strtolower') ? mb_strtolower($value, 'UTF-8') : strtolower($value);
};

if ($search !== '') {
    $needle = $toLower($search);
    $clinics = array_values(array_filter($clinics, static function (array $clinic) use ($needle, $toLower): bool {
        $haystack = implode(' ', [
            (string) ($clinic['code'] ?? ''),
            (string) ($clinic['name_en'] ?? ''),
            (string) ($clinic['name_ar'] ?? ''),
            (int) ($clinic['requires_vitals'] ?? 0) === 1 ? 'vitals first' : 'direct doctor',
        ]);
        return str_contains($toLower($haystack), $needle);
    }));
}

qh_page_start(
    'admin',
    qh_t('Clinic management', 'إدارة العيادات'),
    qh_t('Professional clinic directory with search, edit, and delete actions.', 'دليل احترافي للعيادات مع البحث وخيارات التعديل والحذف.')
);
?>
<div class="container-fluid container-xxl px-3 px-lg-4">
  <div class="admin-layout">
    <aside class="admin-sidebar-column">
      <?php qh_render_admin_sidebar('admin_clinics.php', $stats); ?>
    </aside>

    <div class="admin-content-stack">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h1 class="h3 mb-0 text-gray-800 fw-bold"><?= qh_h(qh_t('Clinic Directory', 'دليل العيادات')) ?></h1>
          <p class="text-muted mb-0 mt-1"><?= qh_h(qh_t('Manage clinics and routing rules.', 'إدارة العيادات وقواعد التوجيه.')) ?></p>
        </div>
        <?php if ($editClinic !== null): ?>
          <a class="btn btn-primary shadow-sm" href="<?= qh_h(qh_url('admin_clinics.php')) ?>"><i class="bi bi-plus-lg me-1"></i><?= qh_h(qh_t('Add New', 'إضافة جديد')) ?></a>
        <?php endif; ?>
      </div>

      <div class="card shadow-sm border-0 mb-4 bg-white">
        <div class="card-body p-3">
          <form method="get" class="d-flex gap-2 align-items-center flex-wrap" role="search">
            <input type="hidden" name="lang" value="<?= qh_h(qh_locale()) ?>">
            <div class="input-group">
              <span class="input-group-text bg-light border-end-0"><i class="bi bi-search text-muted"></i></span>
              <input id="clinicSearch" class="form-control border-start-0 ps-0 bg-light" type="search" name="q" value="<?= qh_h($search) ?>" placeholder="<?= qh_h(qh_t('Search by clinic name or code...', 'ابحث باسم العيادة أو الرمز...')) ?>">
              <button class="btn btn-primary px-4" type="submit"><?= qh_h(qh_t('Search', 'بحث')) ?></button>
            </div>
            <?php if ($search !== ''): ?>
              <a class="btn btn-outline-secondary bg-white" href="<?= qh_h(qh_url('admin_clinics.php')) ?>"><?= qh_h(qh_t('Clear', 'مسح')) ?></a>
            <?php endif; ?>
          </form>
        </div>
      </div>

      <div class="row g-4">
        <div class="col-xl-7 col-lg-6">
          <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
              <h5 class="mb-0 font-weight-bold text-dark"><?= qh_h(qh_t('Clinics', 'العيادات')) ?></h5>
              <span class="badge bg-light text-dark border px-2 py-1"><?= qh_h((string) count($clinics)) ?> <?= qh_h(qh_t('records', 'سجلات')) ?></span>
            </div>

            <div class="card-body p-0">
              <?php if ($clinics === []): ?>
                <div class="text-center py-5 text-muted">
                  <p class="mb-0"><?= qh_h(qh_t('No clinics found.', 'لم يتم العثور على عيادات.')) ?></p>
                </div>
              <?php else: ?>
                <div class="table-responsive">
                  <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                      <tr>
                        <th class="border-0 px-4 py-3"><?= qh_h(qh_t('Code', 'الرمز')) ?></th>
                        <th class="border-0 py-3"><?= qh_h(qh_t('Clinic', 'العيادة')) ?></th>
                        <th class="border-0 py-3"><?= qh_h(qh_t('Routing', 'المسار')) ?></th>
                        <th class="border-0 px-4 py-3 text-end"><?= qh_h(qh_t('Actions', 'الإجراءات')) ?></th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($clinics as $clinic): ?>
                        <?php $editUrl = qh_url('admin_clinics.php', ['edit' => (int) $clinic['id'], 'q' => $search]); ?>
                        <tr>
                          <td class="px-4 py-3"><span class="badge bg-light text-dark border"><?= qh_h((string) $clinic['code']) ?></span></td>
                          <td class="py-3">
                            <div class="fw-semibold text-dark"><?= qh_h(qh_name($clinic)) ?></div>
                            <div class="small text-muted"><?= qh_h(qh_is_ar() ? (string) ($clinic['name_en'] ?? '') : (string) ($clinic['name_ar'] ?? '')) ?></div>
                          </td>
                          <td class="py-3"><span class="badge bg-<?= (int) $clinic['requires_vitals'] === 1 ? 'warning text-dark' : 'info text-dark' ?> rounded-pill px-2 py-1"><?= qh_h((int) $clinic['requires_vitals'] === 1 ? qh_t('Vitals', 'علامات') : qh_t('Direct', 'مباشر')) ?></span></td>
                          <td class="text-end px-4 py-3">
                            <div class="d-inline-flex gap-2">
                              <a class="btn btn-sm btn-light border shadow-sm" href="<?= qh_h($editUrl) ?>"><i class="bi bi-pencil me-1"></i><?= qh_h(qh_t('Edit', 'تعديل')) ?></a>
                              <form method="post" class="m-0" onsubmit="return confirm('<?= qh_h(qh_t('Delete this clinic record?', 'هل تريد حذف سجل هذه العيادة؟')) ?>');">
                                <input type="hidden" name="action" value="delete_clinic">
                                <input type="hidden" name="clinic_id" value="<?= qh_h((string) $clinic['id']) ?>">
                                <input type="hidden" name="return_to" value="admin_clinics.php">
                                <button class="btn btn-sm btn-outline-danger shadow-sm bg-white" type="submit"><i class="bi bi-trash me-1"></i><?= qh_h(qh_t('Delete', 'حذف')) ?></button>
                              </form>
                            </div>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <div class="col-xl-5 col-lg-6">
          <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-bottom py-3">
              <h5 class="mb-0 font-weight-bold text-dark"><?= qh_h($editClinic ? qh_t('Edit Clinic', 'تعديل العيادة') : qh_t('New Clinic', 'عيادة جديدة')) ?></h5>
            </div>

            <div class="card-body">
              <form method="post" class="vstack gap-3">
                <input type="hidden" name="action" value="<?= qh_h($editClinic ? 'update_clinic' : 'add_clinic') ?>">
                <input type="hidden" name="return_to" value="admin_clinics.php">
                <?php if ($editClinic): ?>
                  <input type="hidden" name="clinic_id" value="<?= qh_h((string) $editClinic['id']) ?>">
                <?php endif; ?>

                <div class="row g-3">
                  <div class="col-sm-6">
                    <label class="form-label text-dark fw-semibold small" for="clinicCode"><?= qh_h(qh_t('Code', 'الرمز')) ?></label>
                    <input id="clinicCode" class="form-control bg-light" type="text" maxlength="10" name="code" value="<?= qh_h((string) ($editClinic['code'] ?? '')) ?>" required>
                  </div>
                  <div class="col-sm-6">
                    <label class="form-label text-dark fw-semibold small" for="clinicOrder"><?= qh_h(qh_t('Order', 'الترتيب')) ?></label>
                    <input id="clinicOrder" class="form-control bg-light" type="number" min="1" name="sort_order" value="<?= qh_h((string) ($editClinic['sort_order'] ?? 50)) ?>" required>
                  </div>
                </div>

                <div>
                  <label class="form-label text-dark fw-semibold small" for="clinicNameEn"><?= qh_h(qh_t('Name (English)', 'الاسم بالإنجليزية')) ?></label>
                  <input id="clinicNameEn" class="form-control bg-light" type="text" name="name_en" value="<?= qh_h((string) ($editClinic['name_en'] ?? '')) ?>" required>
                </div>

                <div>
                  <label class="form-label text-dark fw-semibold small" for="clinicNameAr"><?= qh_h(qh_t('Name (Arabic)', 'الاسم بالعربية')) ?></label>
                  <input id="clinicNameAr" class="form-control bg-light" type="text" name="name_ar" value="<?= qh_h((string) ($editClinic['name_ar'] ?? '')) ?>" required>
                </div>

                <div class="p-3 border rounded bg-light mt-2">
                  <div class="form-check form-switch mb-0">
                    <input class="form-check-input" type="checkbox" role="switch" id="clinicVitals" name="requires_vitals" <?= (int) ($editClinic['requires_vitals'] ?? 0) === 1 ? 'checked' : '' ?>>
                    <label class="form-check-label ms-2 text-dark" for="clinicVitals"><?= qh_h(qh_t('Require vitals before doctor', 'يتطلب علامات حيوية')) ?></label>
                  </div>
                </div>

                <div class="d-flex gap-2 pt-3 border-top mt-2">
                  <button class="btn btn-primary shadow-sm" type="submit"><?= qh_h($editClinic ? qh_t('Save Changes', 'حفظ التعديلات') : qh_t('Add Clinic', 'إضافة عيادة')) ?></button>
                  <?php if ($editClinic): ?>
                    <a class="btn btn-outline-secondary bg-white shadow-sm" href="<?= qh_h(qh_url('admin_clinics.php')) ?>"><?= qh_h(qh_t('Cancel', 'إلغاء')) ?></a>
                  <?php endif; ?>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php qh_page_end(); ?>