<?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();
$doctors = qh_fetch_doctors();
$search = trim((string) ($_GET['q'] ?? ''));
$editId = (int) ($_GET['edit'] ?? 0);
$editDoctor = $editId > 0 ? qh_fetch_doctor($editId) : null;

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

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

if ($search !== '') {
    $needle = $toLower($search);
    $doctors = array_values(array_filter($doctors, static function (array $doctor) use ($needle, $toLower): bool {
        $haystack = implode(' ', [
            (string) ($doctor['name_en'] ?? ''),
            (string) ($doctor['name_ar'] ?? ''),
            (string) ($doctor['clinic_name_en'] ?? ''),
            (string) ($doctor['clinic_name_ar'] ?? ''),
            (string) ($doctor['room_number'] ?? ''),
        ]);
        return str_contains($toLower($haystack), $needle);
    }));
}

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

    <div class="admin-content-stack">
      <section class="page-header-panel admin-hero-panel mb-0">
        <div>
          <span class="section-kicker"><?= qh_h(qh_t('Doctor directory', 'دليل الأطباء')) ?></span>
          <div class="locale-chip mt-3"><?= qh_h(qh_current_language_badge()) ?></div>
          <h1 class="section-title-xl mt-2 mb-2"><?= qh_h(qh_t('Dedicated doctor management with clear actions.', 'إدارة مستقلة للأطباء مع إجراءات واضحة.')) ?></h1>
          <p class="section-copy mb-0"><?= qh_h(qh_t('Search doctors, edit assignments, and manage room records from a focused page.', 'ابحث عن الأطباء وعدّل التعيينات وأدر سجلات الغرف من صفحة مركزة.')) ?></p>
        </div>
      </section>

      <section class="panel-card admin-toolbar-card">
        <div class="admin-toolbar">
          <form method="get" class="admin-search-form" role="search">
            <input type="hidden" name="lang" value="<?= qh_h(qh_locale()) ?>">
            <label class="visually-hidden" for="doctorSearch"><?= qh_h(qh_t('Search doctors', 'البحث عن الأطباء')) ?></label>
            <input id="doctorSearch" class="form-control" type="search" name="q" value="<?= qh_h($search) ?>" placeholder="<?= qh_h(qh_t('Search by doctor, clinic, or room', 'ابحث باسم الطبيب أو العيادة أو الغرفة')) ?>">
            <button class="btn btn-dark" type="submit"><?= qh_h(qh_t('Search', 'بحث')) ?></button>
            <?php if ($search !== ''): ?>
              <a class="btn btn-outline-dark" href="<?= qh_h(qh_url('admin_doctors.php')) ?>"><?= qh_h(qh_t('Reset', 'إعادة ضبط')) ?></a>
            <?php endif; ?>
          </form>
          <?php if ($editDoctor !== null): ?>
            <a class="btn btn-outline-dark" href="<?= qh_h(qh_url('admin_doctors.php')) ?>"><?= qh_h(qh_t('Add new doctor', 'إضافة طبيب جديد')) ?></a>
          <?php endif; ?>
        </div>
      </section>

      <div class="admin-directory-layout">
        <section class="panel-card admin-table-card">
          <div class="admin-section-head">
            <div>
              <span class="section-kicker"><?= qh_h(qh_t('Doctor list', 'قائمة الأطباء')) ?></span>
              <h2 class="section-title mt-2 mb-1"><?= qh_h(qh_t('Doctors and room assignments', 'الأطباء وتعيينات الغرف')) ?></h2>
              <p class="section-copy mb-0"><?= qh_h($search !== ''
                ? qh_t('Filtered results based on your search.', 'نتائج مفلترة بناءً على البحث.')
                : qh_t('All configured doctor records.', 'جميع سجلات الأطباء المهيأة.')) ?></p>
            </div>
            <div class="admin-count-chip"><?= qh_h((string) count($doctors)) ?> <?= qh_h(qh_t('records', 'سجلات')) ?></div>
          </div>

          <?php if ($doctors === []): ?>
            <div class="empty-state compact mt-4"><strong><?= qh_h(qh_t('No doctor records match this view.', 'لا توجد سجلات أطباء مطابقة لهذا العرض.')) ?></strong><span><?= qh_h(qh_t('Try another search or create a new doctor profile.', 'جرّب بحثاً آخر أو أنشئ ملف طبيب جديد.')) ?></span></div>
          <?php else: ?>
            <div class="table-responsive mt-4">
              <table class="table align-middle admin-table">
                <thead>
                  <tr>
                    <th><?= qh_h(qh_t('Doctor', 'الطبيب')) ?></th>
                    <th><?= qh_h(qh_t('Clinic', 'العيادة')) ?></th>
                    <th><?= qh_h(qh_t('Room', 'الغرفة')) ?></th>
                    <th><?= qh_h(qh_t('Order', 'الترتيب')) ?></th>
                    <th><?= qh_h(qh_t('Actions', 'الإجراءات')) ?></th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($doctors as $doctor): ?>
                    <?php $editUrl = qh_url('admin_doctors.php', ['edit' => (int) $doctor['id'], 'q' => $search]); ?>
                    <tr>
                      <td>
                        <div class="fw-semibold"><?= qh_h(qh_name($doctor)) ?></div>
                        <div class="small text-secondary"><?= qh_h(qh_is_ar() ? (string) ($doctor['name_en'] ?? '') : (string) ($doctor['name_ar'] ?? '')) ?></div>
                      </td>
                      <td><?= qh_h(qh_name($doctor, 'clinic_name', qh_t('Unassigned', 'غير محدد'))) ?></td>
                      <td><span class="room-badge"><?= qh_h((string) $doctor['room_number']) ?></span></td>
                      <td><?= qh_h((string) $doctor['sort_order']) ?></td>
                      <td>
                        <div class="admin-table-actions">
                          <a class="btn btn-sm btn-outline-dark" href="<?= qh_h($editUrl) ?>"><?= qh_h(qh_t('Edit', 'تعديل')) ?></a>
                          <form method="post" onsubmit="return confirm('<?= qh_h(qh_t('Delete this doctor record?', 'هل تريد حذف سجل هذا الطبيب؟')) ?>');">
                            <input type="hidden" name="action" value="delete_doctor">
                            <input type="hidden" name="doctor_id" value="<?= qh_h((string) $doctor['id']) ?>">
                            <input type="hidden" name="return_to" value="admin_doctors.php">
                            <button class="btn btn-sm btn-outline-danger" type="submit"><?= qh_h(qh_t('Delete', 'حذف')) ?></button>
                          </form>
                        </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </section>

        <section class="panel-card admin-form-card">
          <div class="admin-section-head">
            <div>
              <span class="section-kicker"><?= qh_h($editDoctor ? qh_t('Edit doctor', 'تعديل الطبيب') : qh_t('New doctor', 'طبيب جديد')) ?></span>
              <h2 class="section-title mt-2 mb-1"><?= qh_h($editDoctor ? qh_t('Update doctor profile', 'تحديث ملف الطبيب') : qh_t('Create doctor profile', 'إنشاء ملف الطبيب')) ?></h2>
              <p class="section-copy mb-0"><?= qh_h(qh_t('Store both English and Arabic names while keeping the page language separate.', 'احفظ الاسمين الإنجليزي والعربي مع إبقاء لغة الصفحة منفصلة.')) ?></p>
            </div>
          </div>

          <?php if ($clinics === []): ?>
            <div class="empty-state compact mt-4"><strong><?= qh_h(qh_t('Clinics are required first.', 'يجب إعداد العيادات أولاً.')) ?></strong><span><?= qh_h(qh_t('Create at least one clinic before assigning doctors.', 'أنشئ عيادة واحدة على الأقل قبل تعيين الأطباء.')) ?></span></div>
            <a class="btn btn-dark mt-3" href="<?= qh_h(qh_url('admin_clinics.php')) ?>"><?= qh_h(qh_t('Open clinics page', 'فتح صفحة العيادات')) ?></a>
          <?php else: ?>
            <form method="post" class="vstack gap-3 mt-4">
              <input type="hidden" name="action" value="<?= qh_h($editDoctor ? 'update_doctor' : 'add_doctor') ?>">
              <input type="hidden" name="return_to" value="admin_doctors.php">
              <?php if ($editDoctor): ?>
                <input type="hidden" name="doctor_id" value="<?= qh_h((string) $editDoctor['id']) ?>">
              <?php endif; ?>

              <div>
                <label class="form-label" for="doctorNameEn"><?= qh_h(qh_t('Doctor name (English)', 'اسم الطبيب بالإنجليزية')) ?></label>
                <input id="doctorNameEn" class="form-control" type="text" name="name_en" value="<?= qh_h((string) ($editDoctor['name_en'] ?? '')) ?>" required>
              </div>

              <div>
                <label class="form-label" for="doctorNameAr"><?= qh_h(qh_t('Doctor name (Arabic)', 'اسم الطبيب بالعربية')) ?></label>
                <input id="doctorNameAr" class="form-control" type="text" name="name_ar" value="<?= qh_h((string) ($editDoctor['name_ar'] ?? '')) ?>" required>
              </div>

              <div>
                <label class="form-label" for="doctorClinic"><?= qh_h(qh_t('Clinic', 'العيادة')) ?></label>
                <select id="doctorClinic" class="form-select" name="clinic_id" required>
                  <?php foreach ($clinics as $clinic): ?>
                    <option value="<?= qh_h((string) $clinic['id']) ?>" <?= (int) ($editDoctor['clinic_id'] ?? 0) === (int) $clinic['id'] ? 'selected' : '' ?>><?= qh_h(qh_name($clinic)) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>

              <div class="row g-3">
                <div class="col-sm-6">
                  <label class="form-label" for="doctorRoom"><?= qh_h(qh_t('Room number', 'رقم الغرفة')) ?></label>
                  <input id="doctorRoom" class="form-control" type="text" name="room_number" value="<?= qh_h((string) ($editDoctor['room_number'] ?? '')) ?>" required>
                </div>
                <div class="col-sm-6">
                  <label class="form-label" for="doctorOrder"><?= qh_h(qh_t('Display order', 'ترتيب العرض')) ?></label>
                  <input id="doctorOrder" class="form-control" type="number" min="1" name="sort_order" value="<?= qh_h((string) ($editDoctor['sort_order'] ?? 50)) ?>" required>
                </div>
              </div>

              <div class="d-flex flex-wrap gap-2 pt-2">
                <button class="btn btn-dark" type="submit"><?= qh_h($editDoctor ? qh_t('Save changes', 'حفظ التعديلات') : qh_t('Add doctor', 'إضافة طبيب')) ?></button>
                <?php if ($editDoctor): ?>
                  <a class="btn btn-outline-dark" href="<?= qh_h(qh_url('admin_doctors.php')) ?>"><?= qh_h(qh_t('Cancel edit', 'إلغاء التعديل')) ?></a>
                <?php endif; ?>
              </div>
            </form>
          <?php endif; ?>
        </section>
      </div>
    </div>
  </div>
</div>
<?php qh_page_end(); ?>
