# 🏥 Clinic Management System - Professional Prompts Pack

> **Stack:** Laravel 11 + Blade + jQuery AJAX + Tabler.io UI
> **Architecture:** Multi-Database (Database-per-Tenant)
> **Language:** Arabic (RTL) + English support
> **Author:** نظام إدارة العيادات الاحترافي

---

## 📋 جدول المحتويات

1. [Prompt 1: Project Setup & Multi-Database Architecture](#prompt-1)
2. [Prompt 2: Authentication & Multi-Tenancy Middleware](#prompt-2)
3. [Prompt 3: Database Schema & Migrations](#prompt-3)
4. [Prompt 4: Tabler.io Layout & RTL Setup](#prompt-4)
5. [Prompt 5: Doctor Dashboard with Live Stats](#prompt-5)
6. [Prompt 6: Patients Management (CRUD + AJAX)](#prompt-6)
7. [Prompt 7: Appointments System with Calendar](#prompt-7)
8. [Prompt 8: Medical Records & Prescriptions](#prompt-8)
9. [Prompt 9: Billing, Invoices & Reports](#prompt-9)
10. [Prompt 10: Notifications, Settings & Deployment](#prompt-10)

---

## 🎯 ملاحظات مهمة قبل البدء

### معلومات السيستم:
- **النظام:** Multi-Database — كل عيادة لها قاعدة بيانات مستقلة تماماً (بيانات منفصلة 100%)
- **القاعدة المركزية (Landlord DB):** تحتوي على بيانات العيادات، الاشتراكات، السوبر أدمن
- **قاعدة العيادة (Tenant DB):** تحتوي على المرضى، المواعيد، الفواتير، الموظفين، إلخ
- **الـ UI:** Tabler.io (نظيف، حديث، RTL-friendly)
- **التفاعلات:** jQuery AJAX لكل العمليات (بدون reload للصفحة)

### المشاكل اللي السيستم بيحلها:
✅ تداخل بيانات العيادات (محلولة بـ database isolation)
✅ بطء أنظمة العيادات التقليدية (AJAX + caching)
✅ صعوبة الـ UI (Tabler.io modern interface)
✅ عدم وجود تحليلات (Dashboard بإحصائيات حية)
✅ فقدان السجلات الطبية (Medical history مركزي للمريض)
✅ مشاكل المواعيد المتضاربة (Smart slot validation)
✅ صعوبة إدارة الفواتير (نظام محاسبي متكامل)

---

<a name="prompt-1"></a>
## 🚀 Prompt 1: Project Setup & Multi-Database Architecture

```
You are a senior Laravel architect. I'm building a multi-clinic management SaaS system in Laravel 11 with a strict database-per-tenant architecture (each clinic has its own MySQL database).

Set up the foundation:

1. Create a fresh Laravel 11 project named "clinic-system" with the following packages:
   - laravel/sanctum (API auth)
   - spatie/laravel-permission (roles & permissions)
   - yajra/laravel-datatables (server-side AJAX tables)
   - barryvdh/laravel-debugbar (dev only)
   - intervention/image (medical images)
   - maatwebsite/excel (reports export)
   - barryvdh/laravel-dompdf (invoices/prescriptions PDF)

2. Configure TWO database connections in config/database.php:
   - "landlord" → central DB (clinics registry, subscriptions, super admin)
   - "tenant" → dynamic, switched at runtime per logged-in clinic

3. Create the central "landlord" database with these tables:
   - clinics (id, name, slug, db_name, db_username, db_password, owner_email, phone, logo, status [active/suspended/trial], plan_id, trial_ends_at, created_at)
   - subscription_plans (id, name, price, max_doctors, max_patients, features_json, duration_days)
   - clinic_subscriptions (id, clinic_id, plan_id, started_at, expires_at, status)
   - super_admins (id, name, email, password)

4. Build a TenantManager service class (app/Services/TenantManager.php) that:
   - Resolves the current clinic from subdomain (e.g., dental.mysystem.com) OR from session
   - Dynamically reconfigures the "tenant" DB connection at runtime using clinic credentials
   - Caches the active clinic in the request lifecycle
   - Provides: TenantManager::current(), TenantManager::switchTo($clinic), TenantManager::createDatabase($clinic)

5. Create an artisan command "tenant:create {name} {email}" that:
   - Creates a new clinic record in landlord
   - Generates a unique DB name (clinic_<slug>_<random>)
   - Creates the actual MySQL database
   - Runs tenant migrations on the new DB
   - Seeds default roles, permissions, and an admin user

6. Create an artisan command "tenant:migrate {clinic?}" that runs migrations for one or all tenant databases.

7. Folder structure:
   - database/migrations/landlord/ → for central DB
   - database/migrations/tenant/   → for each clinic DB
   - app/Models/Landlord/          → central models
   - app/Models/Tenant/            → clinic models

Deliver: full file tree, all config files, the TenantManager class with full code, both artisan commands, and a step-by-step setup guide. Use clean, production-grade code with PHPDoc comments. No placeholder code.
```

---

<a name="prompt-2"></a>
## 🔐 Prompt 2: Authentication & Multi-Tenancy Middleware

```
Continue building the clinic system. Now implement the complete authentication & tenant resolution layer.

Requirements:

1. Build an "IdentifyTenant" middleware (app/Http/Middleware/IdentifyTenant.php) that:
   - Reads the subdomain from the request (e.g., "dental" from dental.mysystem.test)
   - Looks up the clinic in the landlord DB
   - If found and active → switches the DB connection via TenantManager
   - If not found → redirects to a "clinic not found" page
   - If suspended/expired → redirects to subscription page
   - Skips for the central domain (mysystem.test) which serves the landing & super admin

2. Build THREE separate auth guards:
   - "super_admin" → for system owner (uses landlord DB, super_admins table)
   - "clinic_owner" → owner of a clinic (tenant DB, users table, role: owner)
   - "web" → default for staff (doctors, receptionists, nurses) on tenant DB

3. Authentication features per clinic (tenant DB):
   - Login with email + password (AJAX, returns JSON with redirect URL)
   - Forgot password (AJAX, sends reset email via Laravel notifications)
   - Reset password page
   - "Remember me" support
   - Login attempt throttling (5 attempts per minute)
   - Activity logging (last_login_at, last_login_ip)
   - 2FA optional (Google Authenticator) — make it pluggable

4. Roles & Permissions (Spatie) — seed these roles per tenant:
   - owner       → full access
   - doctor      → patients, appointments, medical records, prescriptions
   - receptionist → patients, appointments, invoices (no medical records)
   - nurse       → patients (read-only), appointments
   - accountant  → invoices, reports only

5. Create a unified login page (resources/views/auth/login.blade.php) using Tabler.io style:
   - Centered card with clinic logo (loaded dynamically from current tenant)
   - Arabic RTL layout
   - AJAX form submission with proper error display
   - Loading spinner during request
   - Display the clinic name in the header

6. Build a "RoleMiddleware" that protects routes by permission, returns JSON 403 for AJAX requests, redirect for normal requests.

7. Routes structure (routes/tenant.php):
   - /login, /logout, /forgot-password, /reset-password
   - /dashboard (after login)
   - All tenant routes wrapped in middleware: ['web', 'tenant', 'auth']

Deliver: every middleware, every controller, every Blade view, the routes file, the seeders, AJAX JS code, and form validation rules. Production-grade only.
```

---

<a name="prompt-3"></a>
## 🗄️ Prompt 3: Database Schema & Migrations (Tenant DB)

```
Design and create ALL the migrations for the tenant (clinic) database. Schema must be normalized, indexed, and ready for scale.

Create these migrations in database/migrations/tenant/:

1. **users** — (id, name, email unique, phone, password, role, specialization (for doctors), avatar, status, last_login_at, last_login_ip, two_factor_secret, deleted_at, timestamps)

2. **patients** — (id, file_number unique [auto-generated like P-2026-0001], first_name, last_name, gender, date_of_birth, national_id unique nullable, phone, alternative_phone, email nullable, address, city, blood_type enum, marital_status enum, occupation, allergies text, chronic_diseases text, current_medications text, emergency_contact_name, emergency_contact_phone, insurance_provider nullable, insurance_number nullable, notes text, photo, created_by [user_id], deleted_at, timestamps)
   - Indexes on: phone, national_id, file_number

3. **appointments** — (id, patient_id FK, doctor_id FK, appointment_date, start_time, end_time, type enum [first_visit, follow_up, consultation, procedure], status enum [scheduled, confirmed, checked_in, in_progress, completed, cancelled, no_show], reason text, notes, cancelled_reason nullable, created_by, timestamps)
   - Composite index on (doctor_id, appointment_date, start_time)
   - Constraint: no two appointments for same doctor at the same start_time

4. **medical_records** — (id, patient_id, doctor_id, appointment_id nullable, visit_date, chief_complaint, history_of_present_illness, examination_findings, diagnosis, treatment_plan, follow_up_instructions, vital_signs_json [BP, HR, temp, weight, height, BMI], timestamps)

5. **prescriptions** — (id, medical_record_id, patient_id, doctor_id, prescription_number unique, issued_at, notes, timestamps)

6. **prescription_items** — (id, prescription_id, medication_name, dosage, frequency, duration, instructions, timestamps)

7. **medications** (catalog) — (id, name, generic_name, strength, form enum [tablet, capsule, syrup, injection, cream], default_dosage, notes, timestamps)

8. **services** — (id, name, code unique, category, price decimal, duration_minutes, description, is_active, timestamps)
   — examples: consultation, X-ray, blood test, dental cleaning

9. **invoices** — (id, invoice_number unique [INV-2026-0001], patient_id, appointment_id nullable, issue_date, due_date, subtotal, discount_amount, discount_type enum [fixed, percent], tax_amount, total, paid_amount, balance, status enum [draft, sent, partial, paid, overdue, cancelled], notes, created_by, timestamps)

10. **invoice_items** — (id, invoice_id, service_id nullable, description, quantity, unit_price, discount, total)

11. **payments** — (id, invoice_id, amount, payment_method enum [cash, card, transfer, insurance], reference_number nullable, paid_at, received_by, notes, timestamps)

12. **lab_tests** — (id, patient_id, doctor_id, test_name, test_date, results text, file_path nullable [PDF upload], status, timestamps)

13. **medical_attachments** — (id, patient_id, medical_record_id nullable, file_name, file_path, mime_type, size, description, uploaded_by, timestamps)

14. **clinic_settings** — (id, key unique, value, type, group, description, timestamps)
    — for: clinic name, working hours, currency, timezone, invoice prefix, etc.

15. **activity_logs** — (id, user_id, action, model, model_id, old_values json, new_values json, ip_address, user_agent, timestamps)

16. **notifications** — Laravel default

17. **password_reset_tokens, sessions, failed_jobs, jobs** — Laravel defaults

Requirements:
- Use proper foreign keys with onDelete behavior
- Add soft deletes where appropriate (patients, users, appointments)
- Use enums explicitly
- Add indexes on every FK and frequently-queried column
- Add a comprehensive seeder for: medications (50 common Egyptian medications), services (20 common services), default clinic settings

Deliver: every migration file with full schema, every Eloquent model with relationships, casts, fillable, hidden, scopes, and accessors. Include the seeders too.
```

---

<a name="prompt-4"></a>
## 🎨 Prompt 4: Tabler.io Layout & RTL Setup

```
Build the complete UI shell using Tabler.io v1.0+ with full Arabic RTL support.

Requirements:

1. Install & integrate Tabler.io:
   - Use the official CDN OR npm package (@tabler/core)
   - Include the RTL CSS variant
   - Include Tabler Icons
   - Set up Vite to compile RTL assets

2. Build the master layout (resources/views/layouts/app.blade.php) with:
   - <html dir="rtl" lang="ar"> with proper meta tags
   - Cairo or IBM Plex Sans Arabic font from Google Fonts
   - Top navbar with: clinic logo + name, search, notifications dropdown (AJAX-loaded), user dropdown (profile, settings, logout), dark mode toggle (persisted in localStorage)
   - Right-side collapsible sidebar with sections:
     * Dashboard (الرئيسية)
     * Patients (المرضى)
     * Appointments (المواعيد)
     * Medical Records (السجلات الطبية)
     * Prescriptions (الوصفات الطبية)
     * Lab Tests (التحاليل والفحوصات)
     * Billing (الفواتير) → submenu: Invoices, Payments, Services
     * Reports (التقارير)
     * Staff (الموظفين)
     * Settings (الإعدادات)
   - Footer with clinic name + powered by + version
   - Active menu item highlighting based on route name
   - Permission-based menu visibility (using @can directives)

3. Build reusable Blade components in resources/views/components/:
   - <x-card title="..." :actions="..."> — Tabler card
   - <x-stat-card icon color title value trend> — for dashboard stats
   - <x-data-table id columns ajax-url> — wraps DataTables
   - <x-modal id title size> — Bootstrap modal wrapper
   - <x-form-input name label type required> 
   - <x-form-select name label :options>
   - <x-form-textarea name label rows>
   - <x-alert type message dismissible>
   - <x-empty-state icon title description action>
   - <x-page-header title :breadcrumbs :actions>

4. Create a global SweetAlert2 wrapper (public/js/notify.js):
   - Notify.success(msg), Notify.error(msg), Notify.warning(msg)
   - Notify.confirm(msg, callback) — for delete confirmations
   - Notify.loading() / Notify.close()
   - Toast variants positioned top-left in RTL

5. Global AJAX setup (public/js/app.js):
   - jQuery $.ajaxSetup with CSRF token from <meta>
   - Global error handler: 401 → redirect login, 403 → toast, 422 → display field errors, 500 → generic error
   - Loading overlay helper showLoader() / hideLoader()
   - Form helper: $.fn.ajaxSubmit() that handles validation errors auto

6. Color theme:
   - Primary: medical teal (#0ea5a4 or #066f6c)
   - Secondary: soft blue (#3b82f6)
   - Use Tabler's built-in CSS variables to override

7. Make sure ALL forms, tables, modals, dropdowns are RTL-correct (icons mirror, padding flips, etc.)

Deliver: layout file, all components, package.json, vite.config.js, the full SCSS/CSS overrides, the JS files, and a sample dashboard page wired up to the layout to prove it works.
```

---

<a name="prompt-5"></a>
## 📊 Prompt 5: Doctor Dashboard with Live Stats

```
Build a beautiful, professional dashboard that solves real clinic problems. The dashboard differs based on logged-in user role.

For DOCTOR role, dashboard must show:

1. **Top KPI Cards (4 cards):**
   - Today's appointments (count + comparison to yesterday %)
   - Patients seen today
   - Pending lab results
   - Today's revenue (from completed appointments)
   Each card with: icon, number, trend arrow, sparkline mini-chart

2. **Today's Schedule Timeline (left, big card):**
   - Vertical timeline of all today's appointments
   - Each appointment shows: time, patient name + photo, type, status badge, quick actions (Check in / Start visit / View record)
   - Color-coded by status
   - Real-time updates via AJAX polling every 30 seconds

3. **Quick Actions Card:**
   - Big buttons: "موعد جديد" (New Appointment), "مريض جديد" (New Patient), "وصفة سريعة" (Quick Prescription), "بحث عن مريض"
   - Each opens a modal — no page reload

4. **Charts Section (using ApexCharts):**
   - Line chart: Appointments per day (last 30 days)
   - Donut chart: Appointment status distribution this month
   - Bar chart: Top 5 diagnoses this month
   - Heatmap: Busy hours (day of week × hour of day) over the last 90 days

5. **Recent Patients (right card):**
   - List of last 10 patients seen with avatar, name, last visit date, click → goes to medical record

6. **Notifications Feed:**
   - Lab results available
   - Upcoming appointment reminders
   - Birthday alerts for patients (nice human touch)
   - Stock alerts (medications running low — if applicable)

For OWNER/ADMIN role, ADD:
- Revenue chart (this month vs last month)
- Top performing doctors
- Clinic occupancy rate
- Outstanding invoices total

For RECEPTIONIST role:
- Today's appointments full list
- Walk-in patients queue
- Quick check-in interface
- Pending payments

Implementation:
- All data loaded via AJAX endpoints (/api/dashboard/stats, /api/dashboard/today-schedule, etc.)
- Cache stats for 60 seconds in Redis (or file cache)
- Skeleton loaders while data loads
- Empty states when no data
- Responsive grid (4 cols → 2 cols → 1 col)

Deliver: DashboardController with all methods, the routes, the Blade views, the ApexCharts JS configs, the AJAX endpoints with JSON responses, and the cache logic. Use real Eloquent queries with proper eager loading — NO N+1.
```

---

<a name="prompt-6"></a>
## 👥 Prompt 6: Patients Management (CRUD + AJAX)

```
Build the complete Patients module — the most important module in the system.

Pages & Features:

1. **Patients Index Page** (/patients):
   - Server-side DataTable (Yajra) with columns: file number, photo, full name, phone, gender, age (computed), last visit, status, actions
   - Search box at top searches across name, phone, file number, national ID (debounced 300ms)
   - Filters dropdown: gender, age range, blood type, has insurance, has chronic diseases, registered between dates
   - "Add Patient" button → opens modal (no page navigation)
   - Row actions: View, Edit, New Appointment, View History, Delete (with confirmation)
   - Bulk actions: Export selected to Excel/PDF, Send SMS reminder
   - Per-page selector (10/25/50/100)
   - All filters preserved in URL query string

2. **Add/Edit Patient Modal** (large modal, multi-tab):
   - Tab 1: المعلومات الأساسية — name (split first/last), gender, DOB (with auto-calculate age), national ID, phone, alternative phone, email, marital status, occupation, address, city
   - Tab 2: المعلومات الطبية — blood type, allergies (multi-select with custom add), chronic diseases (multi-select), current medications, family history
   - Tab 3: التأمين والطوارئ — insurance provider, insurance number, expiry date, emergency contact name + phone + relation
   - Tab 4: صورة وملاحظات — photo upload (with preview, drag & drop), notes
   - Form validates on the server (FormRequest), errors shown inline per field
   - On save: AJAX POST → if success, close modal, reload table, show success toast
   - File number auto-generated server-side: P-{YEAR}-{seq}

3. **Patient Profile Page** (/patients/{id}):
   - Hero header: photo, name, file number, age, gender, blood type badge, "edit" button
   - Quick stats: total visits, last visit, total invoices, balance due
   - Tabs:
     * نظرة عامة — basic info + medical summary
     * المواعيد — full appointment history table
     * السجل الطبي — timeline of medical records (each card expandable)
     * الوصفات الطبية — list of prescriptions, can re-print
     * التحاليل والفحوصات — list with file downloads
     * الفواتير — invoice history with payment status
     * المرفقات — uploaded documents (X-rays, reports)
     * النشاط — audit log of changes
   - Sticky right panel: emergency contact, allergies (red badges — important!), current medications, chronic conditions
   - "Print Patient Card" button (PDF with QR code linking to profile)

4. **Smart features:**
   - Duplicate detection on save: warns if a patient with same phone/national ID exists
   - Phone number validation (Egyptian format: 010/011/012/015 + 8 digits)
   - National ID validation (14 digits, age & gender extraction from it)
   - Auto-uppercase national ID, auto-format phone
   - Search-as-you-type globally (top navbar) — quick patient lookup with file number/name/phone

5. Backend:
   - PatientController with: index, store, show, update, destroy, restore, export, search (for autocomplete)
   - StorePatientRequest, UpdatePatientRequest with all rules
   - PatientService for business logic (duplicate check, file number generation)
   - PatientResource (API resource) for JSON responses
   - Activity log on every create/update/delete
   - Soft deletes + a "trash" view to restore

Deliver: full controller, FormRequests, service, resource, all Blade views, all the AJAX JS for the modals + datatable, the validation rules for Egyptian phone/ID, and the print PDF view. No skeletons, full code.
```

---

<a name="prompt-7"></a>
## 📅 Prompt 7: Appointments System with Calendar

```
Build the appointments module — second-most-critical feature. Must prevent double-booking and offer a beautiful calendar experience.

Pages:

1. **Calendar View** (/appointments) — DEFAULT view:
   - Use FullCalendar v6 (RTL enabled, Arabic locale)
   - Views: Day / Week / Month / Agenda — switchable
   - Each appointment is a colored block (color per status)
   - Click empty slot → opens "New Appointment" modal pre-filled with that time
   - Click existing appointment → opens "Appointment Details" popover with quick actions
   - Drag & drop to reschedule (AJAX update, with confirmation)
   - Resize to extend duration
   - Filter sidebar: by doctor, by status, by appointment type
   - Doctor color legend
   - Today button + date picker for jumping
   - Working hours respected (greyed out outside hours)

2. **List View** (/appointments?view=list):
   - Server-side DataTable: date, time, patient, doctor, type, status, duration, actions
   - Filters: date range, doctor, patient (autocomplete), status, type
   - Bulk: send SMS reminders to selected

3. **New Appointment Modal:**
   - Patient autocomplete (live search by name/phone/file#) — if not found, "+ Add new patient" inline
   - Doctor select (filtered by specialization if needed)
   - Date picker
   - Available time slots loaded via AJAX based on doctor's schedule (only show free slots)
   - Duration (defaults from service, can override)
   - Type (first visit / follow-up / consultation / procedure)
   - Reason / Chief complaint
   - Notes
   - "Send SMS confirmation" checkbox
   - Validation: no overlap with same doctor's existing appointments

4. **Appointment Details Modal:**
   - Patient info card (photo, name, phone, age)
   - Appointment info
   - Status timeline (Scheduled → Confirmed → Checked-in → In progress → Completed)
   - Action buttons depending on status:
     * Scheduled → Confirm / Cancel / Reschedule
     * Confirmed → Check in / Cancel
     * Checked-in → Start visit (goes to medical record creation)
     * Completed → View medical record / Create invoice
   - Cancel requires reason (textarea)

5. **Smart conflict prevention:**
   - DB constraint: unique(doctor_id, appointment_date, start_time)
   - Service-level check: overlap detection (any time range collision)
   - User-friendly error: "الدكتور لديه موعد آخر في هذا الوقت"

6. **Working hours management** (per doctor):
   - DoctorSchedule model: doctor_id, day_of_week, start_time, end_time, slot_duration, break_start, break_end
   - Settings page for owner to configure each doctor's weekly schedule
   - Holidays/exceptions table for specific dates

7. **Reminders system:**
   - Scheduled job runs every hour
   - Sends SMS/Email 24h before appointment (configurable in settings)
   - Sends WhatsApp via API if configured (placeholder integration)

8. **Patient queue (for receptionist):**
   - Live view of today's checked-in patients waiting
   - Drag to reorder priority
   - "Now serving" indicator
   - Average wait time stat

Backend:
- AppointmentController, AppointmentService (slot calculation, conflict check)
- Available slots API: GET /api/appointments/available-slots?doctor_id=X&date=Y → returns array of free time slots
- Status transition logic (state machine pattern)
- Activity log per status change

Deliver: FullCalendar integration, all modals, the slot algorithm, the cron job, the AJAX endpoints, all controllers and services, and the working hours admin page. Production code only.
```

---

<a name="prompt-8"></a>
## 💊 Prompt 8: Medical Records & Prescriptions

```
Build the clinical core: medical records (visits) and prescriptions. This is what doctors live in daily — make it FAST and ergonomic.

Features:

1. **New Visit / Medical Record Page** (/patients/{id}/visits/create):
   - Single-page workflow optimized for speed
   - Sections (collapsible accordion, all visible by default):
     a) **Vital Signs** — BP (systolic/diastolic), HR, Temperature, Weight, Height (auto-calculate BMI), O2 saturation, Respiratory rate
     b) **Chief Complaint** (textarea, required)
     c) **History of Present Illness** (rich text editor — TinyMCE or Quill)
     d) **Examination** (rich text)
     e) **Diagnosis** — multi-select with autocomplete from ICD-10 catalog (seed 200 common codes), can add free-text too
     f) **Treatment Plan** (rich text)
     g) **Prescription** (inline section — see #2)
     h) **Lab Tests Requested** — multi-select from lab tests catalog, can add custom
     i) **Follow-up** — date picker for next appointment, instructions textarea
     j) **Attachments** — drag & drop file upload (X-rays, scans)
   - Auto-save draft every 30 seconds (AJAX, silent)
   - "Save & Print Prescription" button
   - "Save & Create Invoice" button
   - Sticky right sidebar: patient summary, allergies (RED warning), current medications, last 3 visits diagnoses

2. **Inline Prescription Builder:**
   - "Add medication" button → row appears
   - Each row: medication autocomplete (from medications table, AJAX search), strength (auto-fills from medication), dosage (e.g., "1 tablet"), frequency dropdown (مرة يومياً / مرتين / 3 مرات / 4 مرات / حسب الحاجة), duration (e.g., "7 days"), special instructions
   - Quick-add common combinations (saved as templates per doctor)
   - "Duplicate row" / "Remove row" buttons
   - Keyboard shortcuts (Tab to navigate, Enter to add row)
   - Validation: at least one item, all fields required

3. **Print Prescription** (PDF):
   - Professional A5 layout
   - Clinic header: logo, name, address, phone, license number
   - Doctor info: name, specialization, signature image
   - Patient info: name, age, file number, date
   - Prescription items in a clean table
   - Footer: prescription number, QR code (verifies authenticity), "Rx" symbol
   - Use Laravel-DomPDF
   - Arabic RTL layout

4. **Medical Records List per Patient:**
   - Timeline view (vertical, newest first)
   - Each card: date, doctor, diagnosis (badge), summary preview, expand button
   - Filter by date range, by doctor, by diagnosis
   - Search inside records (full-text on diagnosis + complaint)

5. **Standalone Prescription Module** (/prescriptions):
   - List of all prescriptions (filterable by patient, doctor, date)
   - "Quick prescription" — without a full visit (for follow-ups, refills)
   - Re-issue feature (clone old prescription → new date)
   - Print history

6. **Templates:**
   - Per-doctor templates: common diagnoses, common prescriptions, common examinations
   - Save current visit as template
   - Apply template button (replaces current form content)

7. **ICD-10 catalog:**
   - Seed 200+ common Egyptian/Arabic diagnosis codes (with Arabic + English names)
   - Searchable autocomplete
   - Patient's chronic diagnoses get suggested first

Backend:
- MedicalRecordController, PrescriptionController
- StoreVisitRequest with comprehensive validation
- VisitService — orchestrates creating record + prescription + lab tests in a transaction
- DraftAutoSaveController for auto-save endpoint
- DiagnosisController with autocomplete endpoint
- MedicationController with autocomplete endpoint

Deliver: every controller, request, service, the Blade views (especially the visit creation page — it must be a masterpiece of UX), the PDF blade, the seeders for ICD-10 + common medications. Real working code.
```

---

<a name="prompt-9"></a>
## 💰 Prompt 9: Billing, Invoices & Reports

```
Build the financial backbone of the clinic: invoices, payments, and management reports.

Features:

1. **Services Catalog** (/services):
   - DataTable with: code, name, category, price, duration, status, actions
   - Add/edit modal — name, code (auto-suggested), category, price, duration, description
   - Categories: consultations, procedures, lab tests, imaging, pharmacy, other
   - Activate/deactivate toggle
   - Bulk price update (e.g., +10% for all dental)

2. **Invoices List** (/invoices):
   - DataTable: invoice #, date, patient, total, paid, balance, status, actions
   - Filters: date range, status, patient, created by
   - Status badges color-coded
   - Export to Excel/PDF
   - Stats cards on top: total revenue this month, total outstanding, paid invoices count, overdue count

3. **Create/Edit Invoice** (/invoices/create):
   - Patient autocomplete (or pre-filled if coming from appointment)
   - Linked appointment (optional)
   - Issue date, due date
   - Items section:
     * Add row → service autocomplete OR custom description
     * Quantity, unit price (auto from service, editable), discount (amount or %), line total
     * Add/remove rows
   - Totals panel (sticky right):
     * Subtotal
     * Discount (overall, amount or %)
     * Tax (configurable % from settings)
     * Grand total
     * Paid amount (live updates)
     * Balance
   - Notes field
   - "Save as Draft" / "Save & Send" / "Save & Record Payment"

4. **Invoice View** (/invoices/{id}):
   - Beautiful printable invoice (Tabler styled)
   - Clinic header (logo, name, contact, tax ID)
   - Patient info
   - Items table
   - Totals
   - Payment history section
   - Action buttons: Print, Download PDF, Email to patient, Record Payment, Mark as paid, Cancel
   - Status banner at top

5. **Record Payment Modal:**
   - Amount (defaults to balance, can be partial)
   - Payment method (cash, card, transfer, insurance)
   - Reference number (for cards/transfers)
   - Date
   - Received by (current user)
   - Notes
   - On save: updates invoice paid_amount, balance, status
   - Generates payment receipt (printable)

6. **Insurance handling:**
   - Mark invoice as "insurance" → captures policy info
   - Insurance status: pending, submitted, approved, paid, rejected
   - Track insurance company outstanding amounts
   - Insurance report

7. **Reports Module** (/reports):
   - **Daily Revenue Report**: per day, breakdown by payment method, by service, by doctor
   - **Patient Statement**: all invoices/payments for a patient over a period (printable)
   - **Doctor Performance**: appointments count, patients count, revenue generated, by period
   - **Service Performance**: which services generate most revenue
   - **Aged Receivables**: outstanding invoices grouped by age (0-30, 31-60, 61-90, 90+ days)
   - **Tax Report**: total tax collected per period
   - **Patients Demographics**: gender, age groups, geography
   - **Appointments Analytics**: by status, by type, no-show rate, cancellation rate
   - Each report:
     * Filter form (date range, etc.)
     * Charts (where applicable)
     * Detailed table
     * Export to Excel + PDF
     * Print-friendly view

8. **Cashier shift** (optional but valuable):
   - Open shift / close shift
   - At close: shows total cash collected, expected vs actual, variance
   - Receipt printout for shift summary

Backend:
- InvoiceController, PaymentController, ServiceController, ReportController
- InvoiceService — handles totals calculation, status transitions, number generation
- ReportService — each report as a method, returns DTOs
- PDF generation (Laravel-DomPDF) for invoices, receipts, reports
- Excel export (Maatwebsite/Excel) for tabular reports
- Caching for heavy reports (5-15 minutes)
- Permissions: only accountant + owner see financial data

Deliver: every controller, service, FormRequest, all the Blade views (invoice templates must be print-perfect), PDF templates, Excel exporters, and report queries. Use proper aggregations, no in-memory hacks.
```

---

<a name="prompt-10"></a>
## 🔔 Prompt 10: Notifications, Settings & Deployment

```
Final phase: notifications system, system settings, super admin panel, and production deployment.

Part A — **Notifications System:**

1. Build a notification center:
   - Bell icon in navbar with unread badge
   - Dropdown shows last 10 notifications (AJAX-loaded)
   - "Mark all as read" / "View all" links
   - Full page (/notifications) with all notifications, filterable
   - Each notification: icon (by type), title, body, time ago, link to relevant resource

2. Notification types & triggers:
   - New appointment booked → doctor & receptionist
   - Appointment cancelled → doctor & receptionist
   - Patient checked in → doctor
   - Lab result ready → doctor & patient (if email)
   - Invoice overdue → accountant & owner
   - Low medication stock → owner
   - Birthday → receptionist (to call patient)
   - New patient registered → owner

3. Channels (Laravel Notifications):
   - Database (always)
   - Mail (configurable per user)
   - SMS via a Service interface (so any provider can plug in: Twilio, Vonage, local Egyptian SMS gateway)
   - WhatsApp via Cloud API (placeholder)
   - Real-time via Laravel Echo + Pusher (optional, behind a config flag)

4. User notification preferences page: each notification type × each channel = checkbox

Part B — **Settings Module** (/settings, owner-only):

1. **Clinic Profile**:
   - Name (Arabic & English), logo, favicon, tax ID, license number, email, phone, WhatsApp, address, city, country
   - Working hours (per day of week) — applied across the system

2. **Localization**:
   - Default language (Arabic / English), timezone, currency, date format, number format

3. **Invoice Settings**:
   - Invoice prefix, starting number, terms & conditions text, footer note, tax rate, tax label

4. **Appointment Settings**:
   - Default slot duration, advance booking limit (days), reminder timing (hours before), allow online booking (boolean)

5. **SMS Settings**:
   - Provider, API credentials (encrypted), sender name, templates per notification type

6. **Backup**:
   - Automated daily backup of tenant DB
   - Manual "Backup Now" button
   - List of backups with download/restore
   - Backup retention policy

7. **Audit Log Viewer**:
   - Who did what, when
   - Filter by user, action, model, date
   - Read-only

Part C — **Super Admin Panel** (central domain):

1. Landing page (marketing) with pricing plans
2. Super admin login (separate guard)
3. Super admin dashboard:
   - Total clinics, active subscriptions, MRR, total users across system
   - Charts: clinics growth, revenue trend
4. Clinics management:
   - List all clinics, status, plan, expiry, last activity
   - Suspend/activate
   - Login as clinic owner (impersonation, audited)
   - Create new clinic (provisions DB automatically)
5. Subscriptions management
6. Plans CRUD
7. System logs

Part D — **Deployment & DevOps:**

1. Provide a Dockerfile + docker-compose.yml (PHP-FPM 8.3, Nginx, MySQL 8, Redis, Mailhog for dev)
2. .env.example with all required variables documented
3. Production deployment guide (markdown):
   - Server requirements
   - Nginx config (with subdomain wildcard *.mysystem.com)
   - SSL via Let's Encrypt
   - Queue worker setup (supervisor)
   - Schedule cron entry
   - Redis for cache + sessions + queue
   - File storage (S3 / local with proper permissions)
   - Daily backup cron
4. Health check endpoint: GET /health → checks DB, Redis, queue, storage
5. Performance:
   - All N+1 queries audited
   - Indexes verified
   - Cache strategy documented
   - Asset versioning + minification
   - OPcache config recommendations
6. Security checklist:
   - HTTPS enforced
   - Secure cookies, SameSite
   - Rate limiting on login + API
   - CSRF on all forms
   - XSS protection (escape all outputs)
   - SQL injection (parameterized queries — Eloquent does this)
   - File upload validation (mime, size, scan)
   - Permissions checked on every controller action
   - Tenant isolation verified (no cross-tenant data leaks)
   - Sensitive data encrypted at rest (insurance numbers, etc.)

7. Testing:
   - Feature tests for: auth, patient CRUD, appointment creation (with conflict), invoice creation + payment, tenant isolation
   - Use SQLite in-memory for fast tests
   - Aim for 70%+ coverage on services & controllers

Deliver: every file (Dockerfile, compose, nginx conf, supervisor conf, deployment.md, health check, all settings views, super admin panel views & controllers, notification classes, the SMS service interface + a sample driver). Final deliverable: a system ready to launch on a real server.
```

---

## 🎁 نصائح إضافية لتشغيل البرومبتات

### الترتيب الصحيح:
نفّذ البرومبتات بالترتيب من 1 إلى 10. كل برومبت يبني على اللي قبله.

### قبل كل برومبت:
قول للـ AI: **"استخدم نفس الكود اللي بنيته في البرومبت السابق وكمّل عليه."**

### بعد كل برومبت:
1. اعمل `php artisan migrate` لو فيه migrations جديدة
2. اعمل `npm run build` لو فيه assets
3. جرّب الفيتشر يدوياً
4. لو في error، ابعت الـ error للـ AI ومعاه الكود وقوله صلحه

### Stack مقترح للسيرفر:
- **PHP:** 8.3
- **Laravel:** 11
- **MySQL:** 8.0
- **Redis:** 7+ (للـ cache والـ queue)
- **Nginx:** مع wildcard subdomain
- **Supervisor:** لتشغيل الـ queue workers
- **Node.js:** 20+ للـ Vite

### الـ Folder Structure النهائي:
```
clinic-system/
├── app/
│   ├── Console/Commands/      → tenant:create, tenant:migrate
│   ├── Http/Controllers/
│   │   ├── Landlord/          → super admin
│   │   └── Tenant/            → clinic controllers
│   ├── Http/Middleware/       → IdentifyTenant, RoleMiddleware
│   ├── Models/
│   │   ├── Landlord/
│   │   └── Tenant/
│   ├── Services/              → TenantManager, InvoiceService, etc.
│   └── Notifications/
├── database/
│   └── migrations/
│       ├── landlord/
│       └── tenant/
├── resources/
│   ├── views/
│   │   ├── components/        → Blade components
│   │   ├── layouts/
│   │   └── (modules...)
│   └── js/
└── routes/
    ├── web.php                → landlord (central)
    ├── tenant.php             → tenant routes
    └── api.php
```

### حلول للمشاكل اللي السيستم بيواجهها:
| المشكلة | الحل |
|---------|------|
| تداخل بيانات العيادات | Database per tenant (عزل تام) |
| بطء التحميل | AJAX + Redis cache + skeleton loaders |
| double booking | DB unique constraint + service validation |
| فقدان السجلات | Soft deletes + activity logs + backups |
| صعوبة الـ UI | Tabler.io + RTL + استجابة كاملة |
| إدارة الصلاحيات | Spatie permissions + role middleware |
| تتبع المخالصات | نظام محاسبي متكامل + تقارير |
| المستخدم نسي يحفظ | Auto-save كل 30 ثانية |

---

## 📞 آخر نصيحة

لو في برومبت طلع ناقص أو الـ AI سكت في النص، قوله:
> **"كمّل من حيث وقفت بدون تكرار."**

ولو عايز تختصر، اعمل برومبت واحد كبير يجمع 2-3 برومبتات معاه — بس ده هيقلل الجودة شوية.

**نصيحة ذهبية:** اعمل Git commit بعد كل برومبت ناجح، علشان لو حاجة بظت ترجع.

---

**تم بحمد الله** 🙏
**نسخة:** 1.0
**التاريخ:** مايو 2026
