<?php
/**
 * إدارة العيادات
 */

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

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

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

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

// معالجة التعديل
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('clinics.update')) {
        http_response_code(403);
        echo 'غير مسموح بتعديل العيادات';
        return;
    }
    $editId = (int)($_POST['id'] ?? 0);
    if ($editId > 0) {
        try {
            $stmt = $db->prepare('SELECT * FROM clinics WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$editId, $tenantId]);
            $editClinic = $stmt->fetch();
        } catch (Throwable $e) {
            $editClinic = false;
        }
        
        if ($editClinic) {
            $name = trim($_POST['name'] ?? '');
            $clinicCode = trim($_POST['clinic_code'] ?? '');
            $specialty = trim($_POST['specialty'] ?? '');
            $licenseNumber = trim($_POST['license_number'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $mobile = trim($_POST['mobile'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $website = trim($_POST['website'] ?? '');
            $address = trim($_POST['address'] ?? '');
            $city = trim($_POST['city'] ?? '');
            $latitude = trim($_POST['latitude'] ?? '');
            $longitude = trim($_POST['longitude'] ?? '');
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            $branchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
            
            if ($name !== '') {
                try {
                    $stmt = $db->prepare(
                        'UPDATE clinics SET 
                         name = :name, clinic_code = :code, specialty = :spec, license_number = :license,
                         phone = :phone, mobile = :mobile, email = :email, website = :website,
                         address = :addr, city = :city, latitude = :lat, longitude = :lng,
                         is_active = :active, branch_id = :branch_id
                         WHERE id = :id AND tenant_id = :tid'
                    );
                    $stmt->execute([
                        'name' => $name,
                        'code' => $clinicCode ?: null,
                        'spec' => $specialty ?: null,
                        'license' => $licenseNumber ?: null,
                        'phone' => $phone ?: null,
                        'mobile' => $mobile ?: null,
                        'email' => $email ?: null,
                        'website' => $website ?: null,
                        'addr' => $address ?: null,
                        'city' => $city ?: null,
                        'lat' => $latitude ?: null,
                        'lng' => $longitude ?: null,
                        'active' => $isActive,
                        'branch_id' => $branchId,
                        'id' => $editId,
                        'tid' => $tenantId
                    ]);
                    
                    if (isset($auditLog)) {
                        $auditLog->log(
                            'clinic_updated',
                            'clinic',
                            $editId,
                            json_encode([
                                'name' => $name,
                                'specialty' => $specialty
                            ], JSON_UNESCAPED_UNICODE),
                            null,
                            $_SESSION['user_id'] ?? null
                        );
                    }
                    $_SESSION['clinics_msg'] = 'تم تحديث بيانات العيادة بنجاح';
                } catch (Throwable $e) {
                    $_SESSION['clinics_error'] = 'خطأ في تحديث العيادة: ' . $e->getMessage();
                }
            }
        }
    }
    header('Location: index.php?page=clinics&action=view&id=' . $editId);
    exit;
}

// معالجة الإضافة
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('clinics.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة العيادات';
        return;
    }
    
    $name = trim($_POST['name'] ?? '');
    $clinicCode = trim($_POST['clinic_code'] ?? '');
    $specialty = trim($_POST['specialty'] ?? '');
    $licenseNumber = trim($_POST['license_number'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $mobile = trim($_POST['mobile'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $branchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
    
    if ($name !== '') {
        if (empty($clinicCode)) {
            $clinicCode = 'CLINIC-' . time();
        }
        
        try {
            $stmt = $db->prepare(
                'INSERT INTO clinics (clinic_code, name, specialty, license_number, phone, mobile, email, address, city, tenant_id, branch_id)
                 VALUES (:code, :name, :spec, :license, :phone, :mobile, :email, :addr, :city, :tid, :branch_id)'
            );
            $stmt->execute([
                'code' => $clinicCode,
                'name' => $name,
                'spec' => $specialty ?: null,
                'license' => $licenseNumber ?: null,
                'phone' => $phone ?: null,
                'mobile' => $mobile ?: null,
                'email' => $email ?: null,
                'addr' => $address ?: null,
                'city' => $city ?: null,
                'tid' => $tenantId,
                'branch_id' => $branchId
            ]);
            
            $newId = (int)$db->lastInsertId();
            
            if (isset($auditLog)) {
                $auditLog->log(
                    'clinic_created',
                    'clinic',
                    $newId,
                    null,
                    json_encode([
                        'clinic_code' => $clinicCode,
                        'name' => $name,
                        'specialty' => $specialty
                    ], JSON_UNESCAPED_UNICODE),
                    $_SESSION['user_id'] ?? null
                );
            }
            $_SESSION['clinics_msg'] = 'تم إضافة العيادة بنجاح';
            header('Location: index.php?page=clinics&action=view&id=' . $newId);
            exit;
        } catch (Throwable $e) {
            $_SESSION['clinics_error'] = 'خطأ في إضافة العيادة: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=clinics&action=create');
    exit;
}

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

// جلب قائمة الفروع
$branches = [];
try {
    $stmt = $db->query('SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name');
    $branches = $stmt->fetchAll();
} catch (Throwable $e) {}

// عرض القائمة
if ($action === 'index') {
    $search = trim($_GET['search'] ?? '');
    $where = ['tenant_id = ?'];
    $params = [$tenantId];
    
    if ($search !== '') {
        $where[] = '(name LIKE ? OR clinic_code LIKE ? OR specialty LIKE ?)';
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT c.*, b.name as branch_name 
             FROM clinics c 
             LEFT JOIN branches b ON c.branch_id = b.id
             WHERE ' . implode(' AND ', $where) . ' 
             ORDER BY c.created_at DESC'
        );
        $stmt->execute($params);
        $clinics = $stmt->fetchAll();
    } catch (Throwable $e) {
        $clinics = [];
    }
    
    ?>
    <div class="page-header">
        <h1>إدارة العيادات</h1>
        <?php if ($auth->can('clinics.create')): ?>
            <a href="index.php?page=clinics&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="clinics">
            <input type="text" name="search" placeholder="بحث (اسم، كود، تخصص)..." value="<?= htmlspecialchars($search) ?>" style="width: 300px;">
            <button type="submit" class="btn">بحث</button>
            <?php if ($search): ?>
                <a href="index.php?page=clinics" 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>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($clinics)): ?>
                <tr>
                    <td colspan="8" style="text-align: center; padding: 20px;">لا توجد عيادات</td>
                </tr>
            <?php else: ?>
                <?php foreach ($clinics as $clinic): ?>
                    <tr>
                        <td><?= htmlspecialchars($clinic['clinic_code'] ?? '') ?></td>
                        <td>
                            <a href="index.php?page=clinics&action=view&id=<?= $clinic['id'] ?>">
                                <?= htmlspecialchars($clinic['name']) ?>
                            </a>
                        </td>
                        <td><?= htmlspecialchars($clinic['specialty'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($clinic['phone'] ?? $clinic['mobile'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($clinic['city'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($clinic['branch_name'] ?? '-') ?></td>
                        <td>
                            <span class="badge <?= $clinic['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                                <?= $clinic['is_active'] ? 'نشط' : 'معطل' ?>
                            </span>
                        </td>
                        <td>
                            <a href="index.php?page=clinics&action=view&id=<?= $clinic['id'] ?>" class="btn btn-sm">عرض</a>
                            <?php if ($auth->can('clinics.update')): ?>
                                <a href="index.php?page=clinics&action=edit&id=<?= $clinic['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=clinics');
        exit;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT c.*, b.name as branch_name 
             FROM clinics c 
             LEFT JOIN branches b ON c.branch_id = b.id
             WHERE c.id = ? AND c.tenant_id = ?'
        );
        $stmt->execute([$id, $tenantId]);
        $clinic = $stmt->fetch();
    } catch (Throwable $e) {
        $clinic = false;
    }
    
    if (!$clinic) {
        echo '<div class="alert alert-danger">العيادة غير موجودة</div>';
        echo '<a href="index.php?page=clinics" class="btn">العودة</a>';
        return;
    }
    
    // جلب أوقات الدوام
    $workingHours = [];
    try {
        $stmt = $db->prepare('SELECT * FROM clinic_working_hours WHERE clinic_id = ? ORDER BY day_of_week');
        $stmt->execute([$id]);
        $workingHours = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب الأطباء
    $doctors = [];
    try {
        $stmt = $db->prepare('SELECT * FROM clinic_doctors WHERE clinic_id = ? ORDER BY full_name');
        $stmt->execute([$id]);
        $doctors = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    $days = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
    
    if ($action === 'edit') {
        ?>
        <div class="page-header">
            <h1>تعديل العيادة: <?= htmlspecialchars($clinic['name']) ?></h1>
            <a href="index.php?page=clinics&action=view&id=<?= $id ?>" class="btn">عودة</a>
        </div>
        
        <form method="post" action="index.php?page=clinics&action=edit" class="form-card">
            <input type="hidden" name="id" value="<?= $id ?>">
            
            <h3>البيانات الأساسية</h3>
            <div class="form-group">
                <label>اسم العيادة *</label>
                <input type="text" name="name" value="<?= htmlspecialchars($clinic['name']) ?>" required>
            </div>
            
            <div class="form-group">
                <label>كود العيادة</label>
                <input type="text" name="clinic_code" value="<?= htmlspecialchars($clinic['clinic_code'] ?? '') ?>">
            </div>
            
            <div class="form-group">
                <label>التخصص</label>
                <input type="text" name="specialty" value="<?= htmlspecialchars($clinic['specialty'] ?? '') ?>" placeholder="مثل: طب عام، أسنان، جلدية">
            </div>
            
            <div class="form-group">
                <label>رقم الترخيص</label>
                <input type="text" name="license_number" value="<?= htmlspecialchars($clinic['license_number'] ?? '') ?>">
            </div>
            
            <h3>معلومات الاتصال</h3>
            <div class="form-row">
                <div class="form-group">
                    <label>الهاتف</label>
                    <input type="text" name="phone" value="<?= htmlspecialchars($clinic['phone'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>الجوال</label>
                    <input type="text" name="mobile" value="<?= htmlspecialchars($clinic['mobile'] ?? '') ?>">
                </div>
            </div>
            
            <div class="form-group">
                <label>البريد الإلكتروني</label>
                <input type="email" name="email" value="<?= htmlspecialchars($clinic['email'] ?? '') ?>">
            </div>
            
            <div class="form-group">
                <label>الموقع الإلكتروني</label>
                <input type="url" name="website" value="<?= htmlspecialchars($clinic['website'] ?? '') ?>">
            </div>
            
            <h3>العنوان</h3>
            <div class="form-group">
                <label>العنوان</label>
                <textarea name="address" rows="2"><?= htmlspecialchars($clinic['address'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group">
                <label>المدينة</label>
                <input type="text" name="city" value="<?= htmlspecialchars($clinic['city'] ?? '') ?>">
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>خط العرض (Latitude)</label>
                    <input type="text" name="latitude" value="<?= htmlspecialchars($clinic['latitude'] ?? '') ?>" placeholder="لربط Google Maps">
                </div>
                <div class="form-group">
                    <label>خط الطول (Longitude)</label>
                    <input type="text" name="longitude" value="<?= htmlspecialchars($clinic['longitude'] ?? '') ?>" placeholder="لربط Google Maps">
                </div>
            </div>
            
            <h3>إعدادات</h3>
            <div class="form-group">
                <label>الفرع</label>
                <select name="branch_id">
                    <option value="">-- اختر الفرع --</option>
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?= $branch['id'] ?>" <?= $clinic['branch_id'] == $branch['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($branch['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" name="is_active" <?= $clinic['is_active'] ? 'checked' : '' ?>>
                    العيادة نشطة
                </label>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                <a href="index.php?page=clinics&action=view&id=<?= $id ?>" class="btn">إلغاء</a>
            </div>
        </form>
        <?php
    } else {
        ?>
        <div class="page-header">
            <h1><?= htmlspecialchars($clinic['name']) ?></h1>
            <div>
                <?php if ($auth->can('clinics.update')): ?>
                    <a href="index.php?page=clinics&action=edit&id=<?= $id ?>" class="btn">تعديل</a>
                <?php endif; ?>
                <a href="index.php?page=clinics" class="btn">العودة</a>
            </div>
        </div>
        
        <div class="info-card">
            <h3>البيانات الأساسية</h3>
            <table class="info-table">
                <tr><th>الكود:</th><td><?= htmlspecialchars($clinic['clinic_code'] ?? '-') ?></td></tr>
                <tr><th>التخصص:</th><td><?= htmlspecialchars($clinic['specialty'] ?? '-') ?></td></tr>
                <tr><th>رقم الترخيص:</th><td><?= htmlspecialchars($clinic['license_number'] ?? '-') ?></td></tr>
                <tr><th>الفرع:</th><td><?= htmlspecialchars($clinic['branch_name'] ?? '-') ?></td></tr>
                <tr><th>الحالة:</th>
                    <td><span class="badge <?= $clinic['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                        <?= $clinic['is_active'] ? 'نشط' : 'معطل' ?>
                    </span></td>
                </tr>
            </table>
        </div>
        
        <div class="info-card">
            <h3>معلومات الاتصال</h3>
            <table class="info-table">
                <tr><th>الهاتف:</th><td><?= htmlspecialchars($clinic['phone'] ?? '-') ?></td></tr>
                <tr><th>الجوال:</th><td><?= htmlspecialchars($clinic['mobile'] ?? '-') ?></td></tr>
                <tr><th>البريد:</th><td><?= htmlspecialchars($clinic['email'] ?? '-') ?></td></tr>
                <tr><th>الموقع:</th><td><?= htmlspecialchars($clinic['website'] ?? '-') ?></td></tr>
                <tr><th>العنوان:</th><td><?= htmlspecialchars($clinic['address'] ?? '-') ?></td></tr>
                <tr><th>المدينة:</th><td><?= htmlspecialchars($clinic['city'] ?? '-') ?></td></tr>
            </table>
        </div>
        
        <?php if (!empty($clinic['latitude']) && !empty($clinic['longitude'])): ?>
            <div class="info-card">
                <h3>الموقع على الخريطة</h3>
                <div style="height: 300px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border-radius: 8px;">
                    <p>خريطة Google Maps - يمكن إضافة API key لاحقاً</p>
                    <p>Lat: <?= htmlspecialchars($clinic['latitude']) ?>, Lng: <?= htmlspecialchars($clinic['longitude']) ?></p>
                </div>
            </div>
        <?php endif; ?>
        
        <div class="info-card">
            <h3>الأطباء (<?= count($doctors) ?>)</h3>
            <?php if (empty($doctors)): ?>
                <p>لا يوجد أطباء في هذه العيادة</p>
            <?php else: ?>
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>الاسم</th>
                            <th>الاختصاص</th>
                            <th>رقم النقابة</th>
                            <th>الهاتف</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($doctors as $doctor): ?>
                            <tr>
                                <td><?= htmlspecialchars($doctor['full_name']) ?></td>
                                <td><?= htmlspecialchars($doctor['specialty'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($doctor['syndicate_number'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($doctor['phone'] ?? '-') ?></td>
                                <td>
                                    <a href="index.php?page=clinic_doctors&action=view&id=<?= $doctor['id'] ?>" class="btn btn-sm">عرض</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }
}

// إضافة عيادة جديدة
elseif ($action === 'create') {
    ?>
    <div class="page-header">
        <h1>إضافة عيادة جديدة</h1>
        <a href="index.php?page=clinics" class="btn">العودة</a>
    </div>
    
    <form method="post" action="index.php?page=clinics&action=create" class="form-card">
        <h3>البيانات الأساسية</h3>
        <div class="form-group">
            <label>اسم العيادة *</label>
            <input type="text" name="name" required>
        </div>
        
        <div class="form-group">
            <label>كود العيادة (سيتم إنشاؤه تلقائياً إذا تركت فارغاً)</label>
            <input type="text" name="clinic_code">
        </div>
        
        <div class="form-group">
            <label>التخصص</label>
            <input type="text" name="specialty" placeholder="مثل: طب عام، أسنان، جلدية">
        </div>
        
        <div class="form-group">
            <label>رقم الترخيص</label>
            <input type="text" name="license_number">
        </div>
        
        <h3>معلومات الاتصال</h3>
        <div class="form-row">
            <div class="form-group">
                <label>الهاتف</label>
                <input type="text" name="phone">
            </div>
            <div class="form-group">
                <label>الجوال</label>
                <input type="text" name="mobile">
            </div>
        </div>
        
        <div class="form-group">
            <label>البريد الإلكتروني</label>
            <input type="email" name="email">
        </div>
        
        <h3>العنوان</h3>
        <div class="form-group">
            <label>العنوان</label>
            <textarea name="address" rows="2"></textarea>
        </div>
        
        <div class="form-group">
            <label>المدينة</label>
            <input type="text" name="city">
        </div>
        
        <div class="form-group">
            <label>الفرع</label>
            <select name="branch_id">
                <option value="">-- اختر الفرع --</option>
                <?php foreach ($branches as $branch): ?>
                    <option value="<?= $branch['id'] ?>"><?= htmlspecialchars($branch['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">إضافة العيادة</button>
            <a href="index.php?page=clinics" class="btn">إلغاء</a>
        </div>
    </form>
    <?php
}
