<?php
require_once __DIR__ . '/../../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..' . '/../');
$dotenv->safeLoad();
require_once __DIR__ . '/../i18n.php';

use App\Auth;
use App\Csrf;
use App\Database;

Auth::init();
Auth::requireRole(['admin','staff']);
$pdo = Database::getConnection();
$errors = [];
$info = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  if (!Csrf::verify($_POST['_csrf'] ?? '')) {
    $errors[] = 'Geçersiz CSRF';
  } else {
    try {
      if ($action === 'add_doctor') {
        $full_name = trim($_POST['full_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $specIds = array_filter(array_map('intval', $_POST['specializations'] ?? []));
        if (!$full_name) {
          $errors[] = 'Doktor adı gerekli';
        }
        if (empty($errors)) {
          $pdo->beginTransaction();
          $st = $pdo->prepare('INSERT INTO doctors (full_name, email, phone) VALUES (:full_name,:email,:phone)');
          $st->execute([
            ':full_name' => $full_name,
            ':email' => $email ?: null,
            ':phone' => $phone ?: null
          ]);
          $doctorId = (int)$pdo->lastInsertId();

          if ($specIds) {
            $link = $pdo->prepare('INSERT IGNORE INTO doctor_specializations (doctor_id, specialization_id) VALUES (:doctor_id, :specialization_id)');
            foreach ($specIds as $sid) {
              $link->execute([':doctor_id' => $doctorId, ':specialization_id' => $sid]);
            }
          }
          $pdo->commit();
          $info = 'Doktor başarıyla eklendi';
        }
      } elseif ($action === 'update_doctor') {
        $doctorId = (int)($_POST['doctor_id'] ?? 0);
        $full_name = trim($_POST['full_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $specIds = array_filter(array_map('intval', $_POST['specializations'] ?? []));
        $status = $_POST['status'] ?? 'active';
        if (!$doctorId) {
          $errors[] = 'Geçersiz doktor';
        }
        if (!$full_name) {
          $errors[] = 'Doktor adı gerekli';
        }
        if (empty($errors)) {
          $pdo->beginTransaction();
          $upd = $pdo->prepare('UPDATE doctors SET full_name = :full_name, email = :email, phone = :phone, status = :status WHERE id = :id');
          $upd->execute([
            ':id' => $doctorId,
            ':full_name' => $full_name,
            ':email' => $email ?: null,
            ':phone' => $phone ?: null,
            ':status' => $status
          ]);
          $del = $pdo->prepare('DELETE FROM doctor_specializations WHERE doctor_id = :id');
          $del->execute([':id' => $doctorId]);
          if ($specIds) {
            $link = $pdo->prepare('INSERT IGNORE INTO doctor_specializations (doctor_id, specialization_id) VALUES (:doctor_id, :specialization_id)');
            foreach ($specIds as $sid) {
              $link->execute([':doctor_id' => $doctorId, ':specialization_id' => $sid]);
            }
          }
          $pdo->commit();
          $info = 'Doktor bilgileri güncellendi';
        }
      } elseif ($action === 'add_specialization') {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        if (!$name) {
          $errors[] = 'Uzmanlık adı gerekli';
        } else {
          $st = $pdo->prepare('INSERT INTO specializations (name, description) VALUES (:name,:description)');
          $st->execute([':name' => $name, ':description' => $description ?: null]);
          $info = 'Uzmanlık alanı eklendi';
        }
      } elseif ($action === 'delete_specialization') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
          // Önce ilişkili kayıtları kontrol et
          $check = $pdo->prepare('SELECT COUNT(*) FROM doctor_specializations WHERE specialization_id = :id');
          $check->execute([':id' => $id]);
          if ($check->fetchColumn() > 0) {
            $errors[] = 'Bu uzmanlık doktorlara atanmış olduğu için silinemez';
          } else {
            $del = $pdo->prepare('DELETE FROM specializations WHERE id = :id');
            $del->execute([':id' => $id]);
            $info = 'Uzmanlık alanı silindi';
          }
        }
      } elseif ($action === 'update_doctor_status') {
        $doctorId = (int)($_POST['doctor_id'] ?? 0);
        $newStatus = $_POST['status'] ?? 'active';
        if (!$doctorId || !in_array($newStatus, ['active','inactive'], true)) {
          $errors[] = 'Geçersiz durum';
        } else {
          $upd = $pdo->prepare('UPDATE doctors SET status = :st WHERE id = :id');
          $upd->execute([':st' => $newStatus, ':id' => $doctorId]);
          $info = 'Doktor durumu güncellendi';
        }
      }
    } catch (\Throwable $e) {
      if ($pdo->inTransaction()) {
        $pdo->rollBack();
      }
      $errors[] = 'İşlem başarısız: ' . $e->getMessage();
    }
  }
}

$csrf = App\Csrf::token();
$specializations = $pdo->query('SELECT id, name, description FROM specializations ORDER BY name')->fetchAll();

// Filtreler
$q = trim($_GET['q'] ?? '');
$status = trim($_GET['status'] ?? '');

$where = [];
$params = [];
if ($q !== '') {
  $where[] = '(d.full_name LIKE :q OR d.email LIKE :q OR d.phone LIKE :q)';
  $params[':q'] = "%{$q}%";
}
if (in_array($status, ['active','inactive'], true)) {
  $where[] = 'd.status = :st';
  $params[':st'] = $status;
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$sql = "SELECT d.id, d.full_name, d.email, d.phone, d.status, d.created_at,
  GROUP_CONCAT(s.name ORDER BY s.name SEPARATOR ', ') AS specialties,
  GROUP_CONCAT(s.id ORDER BY s.id SEPARATOR ',') AS spec_ids
  FROM doctors d
  LEFT JOIN doctor_specializations ds ON ds.doctor_id = d.id
  LEFT JOIN specializations s ON s.id = ds.specialization_id
  $whereSql
  GROUP BY d.id
  ORDER BY d.full_name";
$st = $pdo->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll();

include __DIR__ . '/../header.php';
?>
<style>
/* ✅ BU SAYFADA: header.php içindeki Bootstrap container'ı full width yap */
.container,
.container-sm,
.container-md,
.container-lg,
.container-xl,
.container-xxl {
  max-width: 100% !important;
  width: 100% !important;
}

/* Bazı temalarda main/content alanı da max-width verebiliyor */
main,
#app,
#content,
.content,
.page,
.wrapper {
  max-width: 100% !important;
}

:root {
  --primary: #4f46e5;
  --primary-dark: #4338ca;
  --primary-light: #e0e7ff;
  --secondary: #7c3aed;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --info: #06b6d4;
  --light: #f8fafc;
  --dark: #0f172a;
  --gray-50: #f8fafc;
  --gray-100: #f1f5f9;
  --gray-200: #e2e8f0;
  --gray-300: #cbd5e1;
  --gray-400: #94a3b8;
  --gray-500: #64748b;
  --gray-600: #475569;
  --gray-700: #334155;
  --gray-800: #1e293b;
  --gray-900: #0f172a;
  --border-radius: 12px;
  --border-radius-lg: 16px;
  --border-radius-xl: 20px;
  --shadow-sm: 0 1px 3px rgba(0,0,0,0.08);
  --shadow: 0 4px 20px rgba(0,0,0,0.06);
  --shadow-lg: 0 12px 32px rgba(0,0,0,0.10);
  --shadow-xl: 0 20px 50px rgba(0,0,0,0.15);
  --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  color: var(--gray-800);
  line-height: 1.6;
  min-height: 100vh;
}

.page-container {
  max-width: 100% !important;
  width: 100% !important;
  margin: 0 !important;
  padding: 20px 24px;
}

@media (max-width: 768px) {
  .page-container {
    padding: 14px;
  }
}


/* Premium Button Styles */
.btn {
  padding: 14px 28px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  transition: var(--transition);
  text-decoration: none;
  position: relative;
  overflow: hidden;
  letter-spacing: 0.3px;
  text-transform: uppercase;
  font-family: 'Inter', sans-serif;
}

.btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: left 0.6s ease;
}

.btn:hover::before {
  left: 100%;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(79, 70, 229, 0.3);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(79, 70, 229, 0.4);
}

.btn-secondary {
  background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
  color: white;
  border: none;
  box-shadow: 0 4px 16px rgba(79, 70, 229, 0.25);
}

.btn-secondary:hover {
  background: linear-gradient(135deg, var(--primary-dark) 0%, #3730a3 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(79, 70, 229, 0.35);
}

.btn-success {
  background: linear-gradient(135deg, var(--success) 0%, #0da271 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(16, 185, 129, 0.3);
}

.btn-danger {
  background: linear-gradient(135deg, var(--danger) 0%, #dc2626 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(239, 68, 68, 0.3);
}

.btn-sm {
  padding: 10px 20px;
  font-size: 13px;
  border-radius: 10px;
}

/* Premium Alerts */
.alert {
  max-width: 100%;
  margin: 0 auto 24px;
  padding: 20px 24px;
  border-radius: var(--border-radius);
  display: flex;
  align-items: center;
  gap: 16px;
  animation: slideIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  border: none;
}

.alert::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4px;
}

.alert-success {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(16, 185, 129, 0.05) 100%);
  color: #047857;
  border: 1px solid rgba(16, 185, 129, 0.2);
}

.alert-success::before {
  background: linear-gradient(180deg, var(--success), #0da271);
}

.alert-danger {
  background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(239, 68, 68, 0.05) 100%);
  color: #b91c1c;
  border: 1px solid rgba(239, 68, 68, 0.2);
}

.alert-danger::before {
  background: linear-gradient(180deg, var(--danger), #dc2626);
}

.alert i {
  font-size: 20px;
}

/* Filter Section - Premium */
.filter-section {
  max-width: 100%;
  margin: 0 auto 32px;
  background: white;
  border-radius: var(--border-radius-lg);
  padding: 32px;
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--gray-200);
}

.filter-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--gray-200);
}

.filter-header h3 {
  font-size: 20px;
  font-weight: 700;
  color: var(--gray-900);
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-header h3 i {
  color: var(--primary);
  background: var(--primary-light);
  width: 36px;
  height: 36px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.filter-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 0;
}

.form-label {
  display: block;
  font-size: 13px;
  font-weight: 600;
  color: var(--gray-700);
  margin-bottom: 10px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.form-control {
  width: 100%;
  height: 48px;
  padding: 0 18px;
  border: 2px solid var(--gray-300);
  border-radius: 12px;
  font-size: 15px;
  color: var(--gray-800);
  background: white;
  transition: var(--transition);
  font-family: 'Inter', sans-serif;
}

.form-control:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
  transform: translateY(-1px);
}

.form-control::placeholder {
  color: var(--gray-500);
}

.form-control[multiple] {
  min-height: 120px;
  padding: 12px 18px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding-top: 24px;
  border-top: 1px solid var(--gray-200);
}

/* Main Content Container */
.main-content {
  max-width: 100%;
  margin: 0 auto;
  padding: 0 32px 32px;
}

/* Card Styles */
.card {
  background: white;
  border-radius: var(--border-radius-lg);
  padding: 32px;
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--gray-200);
  margin-bottom: 32px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 15px;
}

.card-title {
  font-size: 20px;
  font-weight: 700;
  color: var(--gray-900);
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0;
}

.card-title i {
  color: var(--primary);
  background: var(--primary-light);
  width: 36px;
  height: 36px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-body {
  padding: 0;
}

/* Table Styles */
.table-container {
  overflow-x: auto;
  border-radius: var(--border-radius);
  border: 1px solid var(--gray-200);
}

.table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  min-width: 1000px;
}

.table thead {
  background: linear-gradient(135deg, var(--gray-50) 0%, var(--gray-100) 100%);
}

.table th {
  padding: 20px 16px;
  font-weight: 700;
  color: var(--gray-700);
  text-align: left;
  font-size: 13px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  border-bottom: 2px solid var(--gray-200);
  white-space: nowrap;
  position: sticky;
  top: 0;
  background: inherit;
}

.table tbody tr {
  transition: var(--transition);
  border-bottom: 1px solid var(--gray-200);
}

.table tbody tr:hover {
  background: linear-gradient(90deg, rgba(79, 70, 229, 0.03) 0%, rgba(79, 70, 229, 0.01) 100%);
  transform: translateX(4px);
}

.table td {
  padding: 20px 16px;
  font-size: 14px;
  color: var(--gray-800);
  vertical-align: middle;
}

/* Premium Badges */
.badge {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: 0.3px;
  white-space: nowrap;
  border: none;
  backdrop-filter: blur(10px);
}

.badge-success {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.15) 0%, rgba(16, 185, 129, 0.1) 100%);
  color: #047857;
  border: 1px solid rgba(16, 185, 129, 0.2);
}

.badge-danger {
  background: linear-gradient(135deg, rgba(239, 68, 68, 0.15) 0%, rgba(239, 68, 68, 0.1) 100%);
  color: #b91c1c;
  border: 1px solid rgba(239, 68, 68, 0.2);
}

.badge-info {
  background: linear-gradient(135deg, rgba(6, 182, 212, 0.15) 0%, rgba(6, 182, 212, 0.1) 100%);
  color: #0e7490;
  border: 1px solid rgba(6, 182, 212, 0.2);
}

/* Action Buttons */
.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: nowrap;
}

/* Modal Styles */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(15, 23, 42, 0.7);
  backdrop-filter: blur(4px);
  display: none;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 20px;
  animation: fadeIn 0.3s ease;
}

.modal.open {
  display: flex;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.modal-content {
  background: white;
  border-radius: var(--border-radius-xl);
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-xl);
  animation: modalSlideIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-40px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  padding: 32px;
  border-bottom: 1px solid var(--gray-200);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: linear-gradient(135deg, var(--gray-50) 0%, white 100%);
}

.modal-title-wrapper {
  flex: 1;
}

.modal-title {
  font-size: 24px;
  font-weight: 800;
  color: var(--gray-900);
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.modal-title i {
  color: var(--primary);
  background: var(--primary-light);
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-subtitle {
  color: var(--gray-600);
  font-size: 14px;
  margin: 0;
}

.modal-close {
  background: var(--gray-100);
  border: none;
  font-size: 24px;
  color: var(--gray-500);
  cursor: pointer;
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: var(--transition);
}

.modal-close:hover {
  background: var(--gray-200);
  color: var(--gray-700);
  transform: rotate(90deg);
}

.modal-body {
  padding: 32px;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: 20px 32px;
  border-top: 1px solid var(--gray-200);
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  background: var(--gray-50);
}

/* Chip Styles */
.chip-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.chip {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: var(--gray-50);
  border: 2px solid var(--gray-200);
  border-radius: var(--border-radius);
  padding: 16px;
  transition: var(--transition);
}

.chip:hover {
  border-color: var(--primary);
  background: var(--primary-light);
  transform: translateY(-2px);
  box-shadow: var(--shadow);
}

.chip-content {
  flex: 1;
}

.chip-title {
  font-weight: 700;
  color: var(--gray-900);
  margin-bottom: 6px;
  font-size: 15px;
}

.chip-description {
  color: var(--gray-600);
  font-size: 13px;
  line-height: 1.5;
}

/* Animations */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: slideIn 0.6s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

/* Responsive Design */
@media (max-width: 768px) {
  .page-container {
    padding: 14px;
  }

  .card {
    padding: 20px;
  }

  .filter-section {
    padding: 20px;
  }

  .filter-grid {
    grid-template-columns: 1fr;
  }

  .chip-grid {
    grid-template-columns: 1fr;
  }

  .modal-content {
    max-height: 95vh;
    border-radius: var(--border-radius-lg);
  }

  .modal-header,
  .modal-body {
    padding: 24px;
  }

  .modal-footer {
    padding: 16px 24px;
  }

  .action-buttons {
    flex-direction: column;
    width: 100%;
  }

  .action-buttons .btn {
    width: 100%;
    justify-content: center;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
}

/* Custom Scrollbar */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--gray-100);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: var(--gray-400);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: var(--gray-500);
}
</style>

<div class="page-container">
  <!-- Alerts -->
  <div class="main-content">
    <?php if($info): ?>
    <div class="alert alert-success fade-in">
      <i class="bi bi-check-circle-fill"></i>
      <?= htmlspecialchars($info) ?>
    </div>
    <?php endif; ?>
    
    <?php if($errors): ?>
    <div class="alert alert-danger fade-in">
      <i class="bi bi-exclamation-circle-fill"></i>
      <div>
        <?php foreach($errors as $e): ?>
          <div><?= htmlspecialchars($e) ?></div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Filter Section -->
    <div class="filter-section fade-in">
      <div class="filter-header">
        <h3><i class="bi bi-funnel"></i> Doktor Filtreleme</h3>
      </div>
      
      <form method="get">
        <div class="filter-grid">
          <div class="form-group">
            <label class="form-label">Arama</label>
            <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" 
                   class="form-control" placeholder="Doktor adı, e-posta veya telefon ara...">
          </div>
          
          <div class="form-group">
            <label class="form-label">Durum</label>
            <select name="status" class="form-control">
              <option value="">Tüm Doktorlar</option>
              <option value="active" <?= $status==='active'?'selected':'' ?>>Aktif Doktorlar</option>
              <option value="inactive" <?= $status==='inactive'?'selected':'' ?>>Pasif Doktorlar</option>
            </select>
          </div>
        </div>
        
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-search"></i>
            FİLTRELE
          </button>
          <a href="/SistemModulu/doktor-tanimlari.php" class="btn btn-secondary">
            <i class="bi bi-x-lg"></i>
            FİLTRELERİ TEMİZLE
          </a>
        </div>
      </form>
    </div>

    <!-- Specializations Card -->
    <div class="card fade-in">
      <div class="card-header">
        <h3 class="card-title"><i class="bi bi-capsule"></i> Uzmanlık Alanları</h3>
      </div>
      <div class="card-body">
        <?php if(empty($specializations)): ?>
          <div class="empty-state">
            <div class="empty-state-icon">🏥</div>
            <h3 class="empty-state-title">Uzmanlık Alanı Bulunamadı</h3>
            <p class="empty-state-description">Henüz bir uzmanlık alanı eklenmemiş. "Yeni Uzmanlık" butonuna tıklayın.</p>
          </div>
        <?php else: ?>
          <div class="chip-grid">
            <?php foreach($specializations as $s): ?>
              <div class="chip">
                <div class="chip-content">
                  <div class="chip-title"><?= htmlspecialchars($s['name']) ?></div>
                  <?php if(!empty($s['description'])): ?>
                    <div class="chip-description"><?= htmlspecialchars($s['description']) ?></div>
                  <?php endif; ?>
                </div>
                <form method="post" onsubmit="return confirm('Bu uzmanlık alanını silmek istediğinize emin misiniz?')" style="display: inline;">
                  <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
                  <input type="hidden" name="action" value="delete_specialization">
                  <input type="hidden" name="id" value="<?= (int)$s['id'] ?>">
                  <button type="submit" class="btn btn-danger btn-sm" title="Sil">×</button>
                </form>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Doctors Card -->
    <div class="card fade-in">
      <div class="card-header">
        <h3 class="card-title"><i class="bi bi-person-check"></i> Doktor Listesi</h3>
        <div style="display: flex; align-items: center; gap: 20px;">
          <div style="color: var(--gray-600); font-size: 14px;">
            <strong><?= count($rows) ?></strong> doktor listeleniyor
          </div>
          <button class="btn btn-primary" type="button" onclick="openModal('doctorModal')">
            <i class="bi bi-plus-lg"></i>
            YENİ DOKTOR EKLE
          </button>
        </div>
      </div>
      <div class="card-body">
      <?php if(empty($rows)): ?>
        <div class="empty-state">
          <div class="empty-state-icon">👨‍⚕️</div>
          <h3 class="empty-state-title">Doktor Bulunamadı</h3>
          <p class="empty-state-description">
            <?php if($q || $status): ?>
              Arama kriterlerinize uygun doktor bulunamadı. Filtreleri temizleyip tekrar deneyin.
            <?php else: ?>
              Henüz bir doktor eklenmemiş. İlk doktoru eklemek için "Yeni Doktor" butonuna tıklayın.
            <?php endif; ?>
          </p>
        </div>
      <?php else: ?>
        <div class="table-container">
          <table class="table">
            <thead>
              <tr>
                <th>Doktor</th>
                <th>Uzmanlıklar</th>
                <th>İletişim</th>
                <th>Durum</th>
                <th>Kayıt Tarihi</th>
                <th>İşlemler</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($rows as $r): ?>
              <tr>
                <td>
                  <div style="font-weight: 600; color: #111827;"><?= htmlspecialchars($r['full_name']) ?></div>
                  <div style="font-size: 13px; color: #6b7280;">ID: <?= (int)$r['id'] ?></div>
                </td>
                <td>
                  <?php if($r['specialties']): ?>
                    <div style="display: flex; flex-wrap: wrap; gap: 6px;">
                      <?php 
                      $specialties = explode(', ', $r['specialties']);
                      foreach($specialties as $spec):
                      ?>
                        <span class="badge badge-info"><?= htmlspecialchars(trim($spec)) ?></span>
                      <?php endforeach; ?>
                    </div>
                  <?php else: ?>
                    <span style="color: #9ca3af; font-size: 13px;">Tanımlanmamış</span>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if($r['email']): ?>
                    <div style="margin-bottom: 4px;">
                      <a href="mailto:<?= htmlspecialchars($r['email']) ?>" style="color: var(--primary-color); text-decoration: none; font-size: 13px;">
                        <?= htmlspecialchars($r['email']) ?>
                      </a>
                    </div>
                  <?php endif; ?>
                  <?php if($r['phone']): ?>
                    <div style="font-size: 13px; color: #374151;">
                      <?= htmlspecialchars($r['phone']) ?>
                    </div>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if(($r['status'] ?? 'active') === 'active'): ?>
                    <div class="status-indicator">
                      <span class="status-dot status-active"></span>
                      <span class="badge badge-success">Aktif</span>
                    </div>
                  <?php else: ?>
                    <div class="status-indicator">
                      <span class="status-dot status-inactive"></span>
                      <span class="badge badge-danger">Pasif</span>
                    </div>
                  <?php endif; ?>
                </td>
                <td>
                  <div style="font-size: 13px; color: #374151;"><?= htmlspecialchars($r['created_at'] ?? '') ?></div>
                </td>
                <td>
                  <div class="action-buttons">
                    <button class="btn btn-secondary btn-sm" type="button"
                      data-id="<?= (int)$r['id'] ?>"
                      data-name="<?= htmlspecialchars($r['full_name']) ?>"
                      data-email="<?= htmlspecialchars($r['email'] ?? '') ?>"
                      data-phone="<?= htmlspecialchars($r['phone'] ?? '') ?>"
                      data-spec-ids="<?= htmlspecialchars($r['spec_ids'] ?? '') ?>"
                      data-status="<?= htmlspecialchars($r['status'] ?? 'active') ?>"
                      onclick="openDoctorEdit(this)">
                      <i class="bi bi-pencil"></i>
                      DÜZENLE
                    </button>
                    <form method="post" style="display: inline;">
                      <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
                      <input type="hidden" name="action" value="update_doctor_status">
                      <input type="hidden" name="doctor_id" value="<?= (int)$r['id'] ?>">
                      <input type="hidden" name="status" value="<?= ($r['status'] ?? 'active') === 'active' ? 'inactive' : 'active' ?>">
                      <button class="btn btn-sm <?= ($r['status'] ?? 'active') === 'active' ? 'btn-danger' : 'btn-success' ?>" 
                              type="submit"
                              onclick="return confirm('Doktor durumunu değiştirmek istediğinizden emin misiniz?')">
                        <i class="bi bi-toggle-<?= ($r['status'] ?? 'active') === 'active' ? 'off' : 'on' ?>"></i>
                        <?= ($r['status'] ?? 'active') === 'active' ? 'PASİFLEŞTİR' : 'AKTİFLEŞTİR' ?>
                      </button>
                    </form>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Add Doctor Modal -->
<div class="modal" id="doctorModal">
  <div class="modal-content">
    <div class="modal-header">
      <div>
        <h3 class="modal-title">Yeni Doktor Ekle</h3>
        <p class="modal-subtitle">Doktor bilgilerini ve uzmanlık alanlarını ekleyin</p>
      </div>
      <button class="btn btn-secondary btn-sm" type="button" onclick="closeModal('doctorModal')">×</button>
    </div>
    <form method="post">
      <div class="modal-body">
        <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
        <input type="hidden" name="action" value="add_doctor">
        
        <div class="grid grid-2">
          <div class="form-group">
            <label class="form-label">Ad Soyad *</label>
            <input type="text" class="form-control" name="full_name" required 
              placeholder="Dr. Ad Soyad">
          </div>
          
          <div class="form-group">
            <label class="form-label">E-posta</label>
            <input type="email" class="form-control" name="email" 
              placeholder="ornek@hastane.com">
          </div>
          
          <div class="form-group">
            <label class="form-label">Telefon</label>
            <input type="text" class="form-control" name="phone" 
              placeholder="05XX XXX XX XX">
          </div>
          
          <div class="form-group">
            <label class="form-label">Uzmanlık Alanları</label>
            <select class="form-control" name="specializations[]" multiple size="5">
              <?php foreach($specializations as $s): ?>
                <option value="<?= (int)$s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <small style="display: block; margin-top: 5px; color: #6b7280;">
              Birden fazla seçim için Ctrl (Windows) veya Cmd (Mac) tuşunu basılı tutarak tıklayın
            </small>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" type="button" onclick="closeModal('doctorModal')">Vazgeç</button>
        <button class="btn btn-primary" type="submit">Kaydet</button>
      </div>
    </form>
  </div>
</div>

<!-- Add Specialization Modal -->
<div class="modal" id="specModal">
  <div class="modal-content">
    <div class="modal-header">
      <div>
        <h3 class="modal-title">Yeni Uzmanlık Alanı</h3>
        <p class="modal-subtitle">Doktorlara atanabilecek yeni bir uzmanlık alanı ekleyin</p>
      </div>
      <button class="btn btn-secondary btn-sm" type="button" onclick="closeModal('specModal')">×</button>
    </div>
    <form method="post">
      <div class="modal-body">
        <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
        <input type="hidden" name="action" value="add_specialization">
        
        <div class="form-group">
          <label class="form-label">Uzmanlık Adı *</label>
          <input type="text" class="form-control" name="name" required 
            placeholder="Örn: Kardiyoloji, Nöroloji">
        </div>
        
        <div class="form-group">
          <label class="form-label">Açıklama</label>
          <textarea class="form-control" name="description" rows="3" 
            placeholder="Uzmanlık alanı hakkında kısa açıklama"></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" type="button" onclick="closeModal('specModal')">Vazgeç</button>
        <button class="btn btn-primary" type="submit">Ekle</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Doctor Modal -->
<div class="modal" id="doctorEditModal">
  <div class="modal-content">
    <div class="modal-header">
      <div>
        <h3 class="modal-title">Doktoru Düzenle</h3>
        <p class="modal-subtitle">Doktor bilgilerini ve uzmanlık alanlarını güncelleyin</p>
      </div>
      <button class="btn btn-secondary btn-sm" type="button" onclick="closeModal('doctorEditModal')">×</button>
    </div>
    <form method="post">
      <div class="modal-body">
        <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
        <input type="hidden" name="action" value="update_doctor">
        <input type="hidden" name="doctor_id" id="editDoctorId">
        
        <div class="grid grid-2">
          <div class="form-group">
            <label class="form-label">Ad Soyad *</label>
            <input type="text" class="form-control" name="full_name" id="editDoctorName" required>
          </div>
          
          <div class="form-group">
            <label class="form-label">E-posta</label>
            <input type="email" class="form-control" name="email" id="editDoctorEmail">
          </div>
          
          <div class="form-group">
            <label class="form-label">Telefon</label>
            <input type="text" class="form-control" name="phone" id="editDoctorPhone">
          </div>
          
          <div class="form-group">
            <label class="form-label">Durum</label>
            <select class="form-control" name="status" id="editDoctorStatus">
              <option value="active">Aktif</option>
              <option value="inactive">Pasif</option>
            </select>
          </div>
          
          <div class="form-group">
            <label class="form-label">Uzmanlık Alanları</label>
            <select class="form-control" name="specializations[]" id="editDoctorSpecs" multiple size="5">
              <?php foreach($specializations as $s): ?>
                <option value="<?= (int)$s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <small style="display: block; margin-top: 5px; color: #6b7280;">
              Birden fazla seçim için Ctrl (Windows) veya Cmd (Mac) tuşunu basılı tutarak tıklayın
            </small>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" type="button" onclick="closeModal('doctorEditModal')">Vazgeç</button>
        <button class="btn btn-primary" type="submit">Güncelle</button>
      </div>
    </form>
  </div>
</div>

<script>
// Modal Functions
function openModal(id) {
  const modal = document.getElementById(id);
  if (modal) {
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('open'), 10);
    document.body.style.overflow = 'hidden';
  }
}

function closeModal(id) {
  const modal = document.getElementById(id);
  if (modal) {
    modal.classList.remove('open');
    setTimeout(() => {
      modal.style.display = 'none';
      document.body.style.overflow = 'auto';
    }, 300);
  }
}

// Close modal when clicking outside
document.querySelectorAll('.modal').forEach(modal => {
  modal.addEventListener('click', function(e) {
    if (e.target === this) {
      closeModal(this.id);
    }
  });
});

// Close modal with Escape key
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') {
    document.querySelectorAll('.modal.open').forEach(modal => {
      closeModal(modal.id);
    });
  }
});

// Edit Doctor Function
function openDoctorEdit(btn) {
  const id = btn.getAttribute('data-id');
  const name = btn.getAttribute('data-name') || '';
  const email = btn.getAttribute('data-email') || '';
  const phone = btn.getAttribute('data-phone') || '';
  const status = btn.getAttribute('data-status') || 'active';
  const specIdsStr = btn.getAttribute('data-spec-ids') || '';
  const specIds = specIdsStr ? specIdsStr.split(',').map(s => s.trim()).filter(Boolean) : [];

  // Set form values
  document.getElementById('editDoctorId').value = id;
  document.getElementById('editDoctorName').value = name;
  document.getElementById('editDoctorEmail').value = email;
  document.getElementById('editDoctorPhone').value = phone;
  document.getElementById('editDoctorStatus').value = status;

  // Set specializations
  const specSelect = document.getElementById('editDoctorSpecs');
  if (specSelect) {
    Array.from(specSelect.options).forEach(option => {
      option.selected = specIds.includes(option.value);
    });
  }

  // Open modal
  openModal('doctorEditModal');
}

// Form Validation
document.addEventListener('DOMContentLoaded', function() {
  const forms = document.querySelectorAll('form');
  forms.forEach(form => {
    form.addEventListener('submit', function(e) {
      const requiredFields = this.querySelectorAll('[required]');
      let valid = true;
      
      requiredFields.forEach(field => {
        if (!field.value.trim()) {
          valid = false;
          field.style.borderColor = '#dc2626';
        } else {
          field.style.borderColor = '';
        }
      });
      
      if (!valid) {
        e.preventDefault();
        alert('Lütfen zorunlu alanları doldurunuz (* ile işaretli alanlar)');
      }
    });
  });
});

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
  const deleteButtons = document.querySelectorAll('form[onsubmit*="confirm"] button[type="submit"]');
  deleteButtons.forEach(btn => {
    btn.addEventListener('mouseover', function() {
      this.title = 'Silme işlemi geri alınamaz';
    });
  });
});
</script>
<?php include __DIR__ . '/../footer.php'; ?>