<?php
/**
 * إدارة أطباء العيادات
 */

use App\Core\Auth;
use App\Core\Tenant;

$action = $_GET['action'] ?? 'index';
$tenantId = Tenant::id();

if (!($auth instanceof Auth) || !$auth->can('doctors.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى هذه الصفحة';
    return;
}

// معالجة الحذف
if ($action === 'delete' && isset($_GET['id'])) {
    if (!($auth instanceof Auth) || !$auth->can('doctors.delete')) {
        http_response_code(403);
        echo 'غير مسموح بحذف الأطباء';
        return;
    }
    $delId = (int)$_GET['id'];
    if ($delId > 0) {
        try {
            $stmt = $db->prepare('SELECT id, full_name FROM clinic_doctors WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$delId, $tenantId]);
            $doctor = $stmt->fetch();
        } catch (Throwable $e) {
            $doctor = false;
        }
        
        if ($doctor) {
            // التحقق من وجود مواعيد أو زيارات مرتبطة
            $appointmentCount = 0;
            $visitCount = 0;
            try {
                $stmt = $db->prepare('SELECT COUNT(*) FROM appointments WHERE doctor_id = ?');
                $stmt->execute([$delId]);
                $appointmentCount = (int)$stmt->fetchColumn();
                
                $stmt = $db->prepare('SELECT COUNT(*) FROM patient_visits WHERE doctor_id = ?');
                $stmt->execute([$delId]);
                $visitCount = (int)$stmt->fetchColumn();
            } catch (Throwable $e) {}
            
            if ($appointmentCount > 0 || $visitCount > 0) {
                $_SESSION['clinic_doctors_error'] = 'لا يمكن حذف الطبيب لأنه مرتبط بـ ' . 
                    ($appointmentCount > 0 ? "$appointmentCount موعد" : '') . 
                    ($visitCount > 0 ? ($appointmentCount > 0 ? ' و' : '') . "$visitCount زيارة" : '') . 
                    '. يمكنك تعطيله بدلاً من ذلك.';
                header('Location: index.php?page=clinic_doctors&action=view&id=' . $delId);
                exit;
            }
            
            try {
                $stmt = $db->prepare('DELETE FROM clinic_doctors WHERE id = ? AND tenant_id = ?');
                $stmt->execute([$delId, $tenantId]);
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'clinic_doctor_deleted',
                        'clinic_doctor',
                        $delId,
                        json_encode(['name' => $doctor['full_name']], JSON_UNESCAPED_UNICODE),
                        null,
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['clinic_doctors_msg'] = 'تم حذف الطبيب بنجاح';
            } catch (Throwable $e) {
                $_SESSION['clinic_doctors_error'] = 'خطأ في حذف الطبيب: ' . $e->getMessage();
            }
        }
    }
    header('Location: index.php?page=clinic_doctors');
    exit;
}

// معالجة التعديل
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('doctors.update')) {
        http_response_code(403);
        echo 'غير مسموح بتعديل الأطباء';
        return;
    }
    $editId = (int)($_POST['id'] ?? 0);
    if ($editId > 0) {
        try {
            $stmt = $db->prepare('SELECT * FROM clinic_doctors WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$editId, $tenantId]);
            $editDoctor = $stmt->fetch();
        } catch (Throwable $e) {
            $editDoctor = false;
        }
        
        if ($editDoctor) {
            $fullName = trim($_POST['full_name'] ?? '');
            $specialty = trim($_POST['specialty'] ?? '');
            $subSpecialty = trim($_POST['sub_specialty'] ?? '');
            $syndicateNumber = trim($_POST['syndicate_number'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $mobile = trim($_POST['mobile'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $dob = trim($_POST['date_of_birth'] ?? '');
            $gender = $_POST['gender'] ?? null;
            $consultationFee = (float)($_POST['consultation_fee'] ?? 0);
            $profitPercentage = (float)($_POST['profit_percentage'] ?? 0);
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            $isLoginEnabled = isset($_POST['is_login_enabled']) ? 1 : 0;
            $clinicId = (int)($_POST['clinic_id'] ?? 0);
            $username = trim($_POST['username'] ?? '');
            $newPassword = trim($_POST['new_password'] ?? '');
            
            if ($fullName !== '' && $clinicId > 0) {
                try {
                    // بناء الاستعلام
                    $updateFields = [
                        'full_name = :name', 'specialty = :spec', 'sub_specialty = :subspec',
                        'syndicate_number = :synd', 'phone = :phone', 'mobile = :mobile', 'email = :email',
                        'date_of_birth = :dob', 'gender = :gender',
                        'consultation_fee = :fee', 'profit_percentage = :profit', 
                        'is_active = :active', 'is_login_enabled = :login_enabled', 'clinic_id = :clinic'
                    ];
                    
                    $updateParams = [
                        'name' => $fullName,
                        'spec' => $specialty ?: null,
                        'subspec' => $subSpecialty ?: null,
                        'synd' => $syndicateNumber ?: null,
                        'phone' => $phone ?: null,
                        'mobile' => $mobile ?: null,
                        'email' => $email ?: null,
                        'dob' => $dob ?: null,
                        'gender' => $gender ?: null,
                        'fee' => $consultationFee,
                        'profit' => $profitPercentage,
                        'active' => $isActive,
                        'login_enabled' => $isLoginEnabled,
                        'clinic' => $clinicId,
                        'id' => $editId,
                        'tid' => $tenantId
                    ];
                    
                    // تحديث اسم المستخدم إذا تم إدخاله
                    if ($username !== '') {
                        $updateFields[] = 'username = :username';
                        $updateParams['username'] = $username;
                    }
                    
                    // تحديث كلمة المرور إذا تم إدخالها
                    if ($newPassword !== '') {
                        $updateFields[] = 'password_hash = :password';
                        $updateParams['password'] = password_hash($newPassword, PASSWORD_BCRYPT);
                    }
                    
                    $stmt = $db->prepare(
                        'UPDATE clinic_doctors SET ' . implode(', ', $updateFields) . '
                         WHERE id = :id AND tenant_id = :tid'
                    );
                    $stmt->execute($updateParams);
                    
                    if (isset($auditLog)) {
                        $auditLog->log(
                            'clinic_doctor_updated',
                            'clinic_doctor',
                            $editId,
                            json_encode(['name' => $fullName, 'specialty' => $specialty], JSON_UNESCAPED_UNICODE),
                            null,
                            $_SESSION['user_id'] ?? null
                        );
                    }
                    $_SESSION['clinic_doctors_msg'] = 'تم تحديث بيانات الطبيب بنجاح';
                } catch (Throwable $e) {
                    $_SESSION['clinic_doctors_error'] = 'خطأ في تحديث الطبيب: ' . $e->getMessage();
                }
            }
        }
    }
    header('Location: index.php?page=clinic_doctors&action=view&id=' . $editId);
    exit;
}

// معالجة الإضافة
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('doctors.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة الأطباء';
        return;
    }
    
    $fullName = trim($_POST['full_name'] ?? '');
    $doctorCode = trim($_POST['doctor_code'] ?? '');
    $specialty = trim($_POST['specialty'] ?? '');
    $syndicateNumber = trim($_POST['syndicate_number'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $clinicId = (int)($_POST['clinic_id'] ?? 0);
    $consultationFee = (float)($_POST['consultation_fee'] ?? 0);
    $profitPercentage = (float)($_POST['profit_percentage'] ?? 0);
    
    if ($fullName !== '' && $clinicId > 0) {
        if (empty($doctorCode)) {
            $doctorCode = 'DOC-' . time();
        }
        
        try {
            $stmt = $db->prepare(
                'INSERT INTO clinic_doctors (doctor_code, full_name, specialty, syndicate_number, phone, clinic_id, consultation_fee, profit_percentage, tenant_id)
                 VALUES (:code, :name, :spec, :synd, :phone, :clinic, :fee, :profit, :tid)'
            );
            $stmt->execute([
                'code' => $doctorCode,
                'name' => $fullName,
                'spec' => $specialty ?: null,
                'synd' => $syndicateNumber ?: null,
                'phone' => $phone ?: null,
                'clinic' => $clinicId,
                'fee' => $consultationFee,
                'profit' => $profitPercentage,
                'tid' => $tenantId
            ]);
            
            $newId = (int)$db->lastInsertId();
            
            if (isset($auditLog)) {
                $auditLog->log(
                    'clinic_doctor_created',
                    'clinic_doctor',
                    $newId,
                    null,
                    json_encode([
                        'doctor_code' => $doctorCode,
                        'full_name' => $fullName,
                        'specialty' => $specialty
                    ], JSON_UNESCAPED_UNICODE),
                    $_SESSION['user_id'] ?? null
                );
            }
            $_SESSION['clinic_doctors_msg'] = 'تم إضافة الطبيب بنجاح';
            header('Location: index.php?page=clinic_doctors&action=view&id=' . $newId);
            exit;
        } catch (Throwable $e) {
            $_SESSION['clinic_doctors_error'] = 'خطأ في إضافة الطبيب: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=clinic_doctors&action=create');
    exit;
}

// جلب البيانات
$msg = $_SESSION['clinic_doctors_msg'] ?? null;
$error = $_SESSION['clinic_doctors_error'] ?? null;
unset($_SESSION['clinic_doctors_msg'], $_SESSION['clinic_doctors_error']);

// جلب قائمة العيادات
$clinics = [];
try {
    $stmt = $db->prepare('SELECT id, name FROM clinics WHERE tenant_id = ? AND is_active = 1 ORDER BY name');
    $stmt->execute([$tenantId]);
    $clinics = $stmt->fetchAll();
} catch (Throwable $e) {}

// عرض القائمة
if ($action === 'index') {
    $search = trim($_GET['search'] ?? '');
    $clinicFilter = !empty($_GET['clinic_id']) ? (int)$_GET['clinic_id'] : 0;
    
    $where = ['cd.tenant_id = ?'];
    $params = [$tenantId];
    
    if ($search !== '') {
        $where[] = '(cd.full_name LIKE ? OR cd.doctor_code LIKE ? OR cd.specialty LIKE ?)';
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    if ($clinicFilter > 0) {
        $where[] = 'cd.clinic_id = ?';
        $params[] = $clinicFilter;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT cd.*, c.name as clinic_name 
             FROM clinic_doctors cd 
             LEFT JOIN clinics c ON cd.clinic_id = c.id
             WHERE ' . implode(' AND ', $where) . ' 
             ORDER BY cd.created_at DESC'
        );
        $stmt->execute($params);
        $doctors = $stmt->fetchAll();
    } catch (Throwable $e) {
        $doctors = [];
    }
    
    ?>
    <div class="page-header">
        <h1>إدارة أطباء العيادات</h1>
        <?php if ($auth->can('doctors.create')): ?>
            <a href="index.php?page=clinic_doctors&action=create" class="btn btn-primary">+ إضافة طبيب</a>
        <?php endif; ?>
    </div>
    
    <?php if ($msg): ?>
        <div class="alert alert-success"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <div class="search-box">
        <form method="get" action="index.php">
            <input type="hidden" name="page" value="clinic_doctors">
            <select name="clinic_id" style="width: 200px;">
                <option value="">كل العيادات</option>
                <?php foreach ($clinics as $clinic): ?>
                    <option value="<?= $clinic['id'] ?>" <?= $clinicFilter == $clinic['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($clinic['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <input type="text" name="search" placeholder="بحث (اسم، كود، تخصص)..." value="<?= htmlspecialchars($search) ?>" style="width: 300px;">
            <button type="submit" class="btn">بحث</button>
            <?php if ($search || $clinicFilter): ?>
                <a href="index.php?page=clinic_doctors" class="btn">إلغاء</a>
            <?php endif; ?>
        </form>
    </div>
    
    <table class="data-table">
        <thead>
            <tr>
                <th>الكود</th>
                <th>اسم الطبيب</th>
                <th>الاختصاص</th>
                <th>رقم النقابة</th>
                <th>العيادة</th>
                <th>رسوم الاستشارة</th>
                <th>نسبة الأرباح</th>
                <th>الحالة</th>
                <th>الإجراءات</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($doctors)): ?>
                <tr>
                    <td colspan="9" style="text-align: center; padding: 20px;">لا يوجد أطباء</td>
                </tr>
            <?php else: ?>
                <?php foreach ($doctors as $doctor): ?>
                    <tr>
                        <td><?= htmlspecialchars($doctor['doctor_code'] ?? '') ?></td>
                        <td>
                            <a href="index.php?page=clinic_doctors&action=view&id=<?= $doctor['id'] ?>">
                                <?= htmlspecialchars($doctor['full_name']) ?>
                            </a>
                        </td>
                        <td><?= htmlspecialchars($doctor['specialty'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($doctor['syndicate_number'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($doctor['clinic_name'] ?? '-') ?></td>
                        <td><?= number_format($doctor['consultation_fee'] ?? 0, 2) ?> د.ع</td>
                        <td><?= number_format($doctor['profit_percentage'] ?? 0, 2) ?>%</td>
                        <td>
                            <span class="badge <?= $doctor['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                                <?= $doctor['is_active'] ? 'نشط' : 'معطل' ?>
                            </span>
                        </td>
                        <td>
                            <a href="index.php?page=clinic_doctors&action=view&id=<?= $doctor['id'] ?>" class="btn btn-sm">عرض</a>
                            <?php if ($auth->can('doctors.update')): ?>
                                <a href="index.php?page=clinic_doctors&action=edit&id=<?= $doctor['id'] ?>" class="btn btn-sm">تعديل</a>
                            <?php endif; ?>
                            <?php if ($auth->can('doctors.schedule')): ?>
                                <a href="index.php?page=clinic_doctors&action=schedule&id=<?= $doctor['id'] ?>" class="btn btn-sm">الجدول</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
    <?php
}

// عرض/تعديل طبيب
elseif ($action === 'view' || $action === 'edit') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0) {
        header('Location: index.php?page=clinic_doctors');
        exit;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT cd.*, c.name as clinic_name 
             FROM clinic_doctors cd 
             LEFT JOIN clinics c ON cd.clinic_id = c.id
             WHERE cd.id = ? AND cd.tenant_id = ?'
        );
        $stmt->execute([$id, $tenantId]);
        $doctor = $stmt->fetch();
    } catch (Throwable $e) {
        $doctor = false;
    }
    
    if (!$doctor) {
        echo '<div class="alert alert-danger">الطبيب غير موجود</div>';
        echo '<a href="index.php?page=clinic_doctors" class="btn">العودة</a>';
        return;
    }
    
    // جلب جدول الطبيب
    $schedule = [];
    try {
        $stmt = $db->prepare('SELECT * FROM doctor_schedules WHERE doctor_id = ? ORDER BY day_of_week');
        $stmt->execute([$id]);
        $schedule = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    if ($action === 'edit') {
        ?>
        <div class="page-header">
            <h1>تعديل الطبيب: <?= htmlspecialchars($doctor['full_name']) ?></h1>
            <a href="index.php?page=clinic_doctors&action=view&id=<?= $id ?>" class="btn">عودة</a>
        </div>
        
        <form method="post" action="index.php?page=clinic_doctors&action=edit" class="form-card">
            <input type="hidden" name="id" value="<?= $id ?>">
            
            <h3>البيانات الأساسية</h3>
            <div class="form-group">
                <label>اسم الطبيب *</label>
                <input type="text" name="full_name" value="<?= htmlspecialchars($doctor['full_name']) ?>" required>
            </div>
            
            <div class="form-group">
                <label>الاختصاص *</label>
                <input type="text" name="specialty" value="<?= htmlspecialchars($doctor['specialty'] ?? '') ?>" required>
            </div>
            
            <div class="form-group">
                <label>التخصص الفرعي</label>
                <input type="text" name="sub_specialty" value="<?= htmlspecialchars($doctor['sub_specialty'] ?? '') ?>">
            </div>
            
            <div class="form-group">
                <label>رقم النقابة</label>
                <input type="text" name="syndicate_number" value="<?= htmlspecialchars($doctor['syndicate_number'] ?? '') ?>">
            </div>
            
            <div class="form-group">
                <label>العيادة *</label>
                <select name="clinic_id" required>
                    <option value="">-- اختر العيادة --</option>
                    <?php foreach ($clinics as $clinic): ?>
                        <option value="<?= $clinic['id'] ?>" <?= $doctor['clinic_id'] == $clinic['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($clinic['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <h3>معلومات الاتصال</h3>
            <div class="form-row">
                <div class="form-group">
                    <label>الهاتف</label>
                    <input type="text" name="phone" value="<?= htmlspecialchars($doctor['phone'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>الجوال</label>
                    <input type="text" name="mobile" value="<?= htmlspecialchars($doctor['mobile'] ?? '') ?>">
                </div>
            </div>
            
            <div class="form-group">
                <label>البريد الإلكتروني</label>
                <input type="email" name="email" value="<?= htmlspecialchars($doctor['email'] ?? '') ?>">
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>تاريخ الميلاد</label>
                    <input type="date" name="date_of_birth" value="<?= htmlspecialchars($doctor['date_of_birth'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>الجنس</label>
                    <select name="gender">
                        <option value="">-- اختر --</option>
                        <option value="M" <?= $doctor['gender'] == 'M' ? 'selected' : '' ?>>ذكر</option>
                        <option value="F" <?= $doctor['gender'] == 'F' ? 'selected' : '' ?>>أنثى</option>
                    </select>
                </div>
            </div>
            
            <h3>المالية</h3>
            <div class="form-row">
                <div class="form-group">
                    <label>رسوم الاستشارة (د.ع)</label>
                    <input type="number" name="consultation_fee" step="0.01" value="<?= $doctor['consultation_fee'] ?? 0 ?>">
                </div>
                <div class="form-group">
                    <label>نسبة الأرباح (%)</label>
                    <input type="number" name="profit_percentage" step="0.01" value="<?= $doctor['profit_percentage'] ?? 0 ?>">
                </div>
            </div>
            
            <h3>تسجيل الدخول</h3>
            <div class="form-group">
                <label>اسم المستخدم</label>
                <input type="text" name="username" value="<?= htmlspecialchars($doctor['username'] ?? '') ?>" placeholder="اسم المستخدم لتسجيل الدخول">
                <small style="color: #666;">اسم المستخدم الذي سيستخدمه الطبيب لتسجيل الدخول</small>
            </div>
            
            <div class="form-group">
                <label>كلمة المرور الجديدة</label>
                <input type="password" name="new_password" placeholder="اتركه فارغاً إذا لم ترد تغييره">
                <small style="color: #666;">اتركه فارغاً إذا لم ترد تغيير كلمة المرور</small>
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" name="is_login_enabled" <?= $doctor['is_login_enabled'] ?? 0 ? 'checked' : '' ?>>
                    تفعيل تسجيل الدخول للطبيب
                </label>
                <small style="color: #666; display: block; margin-top: 5px;">
                    عند التفعيل، يمكن للطبيب تسجيل الدخول من صفحة تسجيل دخول الأطباء
                </small>
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" name="is_active" <?= $doctor['is_active'] ? 'checked' : '' ?>>
                    الطبيب نشط
                </label>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                <a href="index.php?page=clinic_doctors&action=view&id=<?= $id ?>" class="btn">إلغاء</a>
            </div>
        </form>
        <?php
    } else {
        ?>
        <div class="page-header">
            <h1><?= htmlspecialchars($doctor['full_name']) ?></h1>
            <div>
                <?php if ($auth->can('doctors.update')): ?>
                    <a href="index.php?page=clinic_doctors&action=edit&id=<?= $id ?>" class="btn">تعديل</a>
                <?php endif; ?>
                <?php if ($auth->can('doctors.schedule')): ?>
                    <a href="index.php?page=clinic_doctors&action=schedule&id=<?= $id ?>" class="btn">إدارة الجدول</a>
                <?php endif; ?>
                <a href="index.php?page=clinic_doctors" class="btn">العودة</a>
            </div>
        </div>
        
        <div class="info-card">
            <h3>البيانات الأساسية</h3>
            <table class="info-table">
                <tr><th>الكود:</th><td><?= htmlspecialchars($doctor['doctor_code'] ?? '-') ?></td></tr>
                <tr><th>الاختصاص:</th><td><?= htmlspecialchars($doctor['specialty'] ?? '-') ?></td></tr>
                <tr><th>التخصص الفرعي:</th><td><?= htmlspecialchars($doctor['sub_specialty'] ?? '-') ?></td></tr>
                <tr><th>رقم النقابة:</th><td><?= htmlspecialchars($doctor['syndicate_number'] ?? '-') ?></td></tr>
                <tr><th>العيادة:</th><td><?= htmlspecialchars($doctor['clinic_name'] ?? '-') ?></td></tr>
                <tr><th>رسوم الاستشارة:</th><td><?= number_format($doctor['consultation_fee'] ?? 0, 2) ?> د.ع</td></tr>
                <tr><th>نسبة الأرباح:</th><td><?= number_format($doctor['profit_percentage'] ?? 0, 2) ?>%</td></tr>
                <tr><th>الحالة:</th>
                    <td><span class="badge <?= $doctor['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                        <?= $doctor['is_active'] ? 'نشط' : 'معطل' ?>
                    </span></td>
                </tr>
            </table>
        </div>
        
        <div class="info-card">
            <h3>معلومات الاتصال</h3>
            <table class="info-table">
                <tr><th>الهاتف:</th><td><?= htmlspecialchars($doctor['phone'] ?? '-') ?></td></tr>
                <tr><th>الجوال:</th><td><?= htmlspecialchars($doctor['mobile'] ?? '-') ?></td></tr>
                <tr><th>البريد:</th><td><?= htmlspecialchars($doctor['email'] ?? '-') ?></td></tr>
            </table>
        </div>
        
        <?php if (!empty($schedule)): ?>
            <div class="info-card">
                <h3>جدول الدوام</h3>
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>اليوم</th>
                            <th>متاح</th>
                            <th>من</th>
                            <th>إلى</th>
                            <th>استراحة</th>
                            <th>مدة الموعد</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $days = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
                        foreach ($schedule as $s): 
                        ?>
                            <tr>
                                <td><?= $days[$s['day_of_week']] ?? '-' ?></td>
                                <td><span class="badge <?= $s['is_available'] ? 'badge-success' : 'badge-danger' ?>">
                                    <?= $s['is_available'] ? 'نعم' : 'لا' ?>
                                </span></td>
                                <td><?= $s['start_time'] ?? '-' ?></td>
                                <td><?= $s['end_time'] ?? '-' ?></td>
                                <td>
                                    <?php if ($s['break_start'] && $s['break_end']): ?>
                                        <?= $s['break_start'] ?> - <?= $s['break_end'] ?>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td><?= $s['appointment_duration'] ?? 30 ?> دقيقة</td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
        <?php
    }
}

// إضافة طبيب جديد
elseif ($action === 'create') {
    ?>
    <div class="page-header">
        <h1>إضافة طبيب جديد</h1>
        <a href="index.php?page=clinic_doctors" class="btn">العودة</a>
    </div>
    
    <form method="post" action="index.php?page=clinic_doctors&action=create" class="form-card">
        <h3>البيانات الأساسية</h3>
        <div class="form-group">
            <label>اسم الطبيب *</label>
            <input type="text" name="full_name" required>
        </div>
        
        <div class="form-group">
            <label>الاختصاص *</label>
            <input type="text" name="specialty" required>
        </div>
        
        <div class="form-group">
            <label>رقم النقابة</label>
            <input type="text" name="syndicate_number">
        </div>
        
        <div class="form-group">
            <label>العيادة *</label>
            <select name="clinic_id" required>
                <option value="">-- اختر العيادة --</option>
                <?php foreach ($clinics as $clinic): ?>
                    <option value="<?= $clinic['id'] ?>"><?= htmlspecialchars($clinic['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <h3>معلومات الاتصال</h3>
        <div class="form-group">
            <label>الهاتف</label>
            <input type="text" name="phone">
        </div>
        
        <h3>المالية</h3>
        <div class="form-row">
            <div class="form-group">
                <label>رسوم الاستشارة (د.ع)</label>
                <input type="number" name="consultation_fee" step="0.01" value="0">
            </div>
            <div class="form-group">
                <label>نسبة الأرباح (%)</label>
                <input type="number" name="profit_percentage" step="0.01" value="0">
            </div>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">إضافة الطبيب</button>
            <a href="index.php?page=clinic_doctors" class="btn">إلغاء</a>
        </div>
    </form>
    <?php
}
