# Extended Doctor & Pharmacy Workplaces (Private & Hospital Clinics) Import/Export Plan

> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

**Goal:** Extend the Universal Excel Import & Export system for Doctors and Pharmacies so each doctor can have a Private Clinic, a Hospital Clinic, or both simultaneously, and pharmacies have enhanced hospital affiliation matching with an approved hospitals reference guide.

**Architecture:** 
1. Enhance `ArabicNormalizer` with `findHospital()` to provide intelligent, fuzzy, and prefix-tolerant hospital matching.
2. Extend the Doctor Excel template & export schema in `DataImportService` into structured sections: Basic Doctor Info, Private Clinic Details (Clinic Name, Governorate, Area, Address, Phone), and Hospital Clinic Details (Works in Hospital?, Hospital Name, Hospital Clinic/Department Name), while maintaining 100% backward compatibility for legacy format files.
3. Update `previewDoctors()` and `executeImport()` to parse both workplace types and create/update corresponding `DoctorWorkplace` rows (primary private clinic and secondary/primary hospital clinic).
4. Update `previewPharmacies()` and Pharmacy reference sheets to include the approved Hospitals directory and use `findHospital()`.
5. Update the preview interface in `resources/js/pages/Admin/Import/Index.vue` to display badges/labels indicating Private Clinic and/or Hospital Clinic.

**Tech Stack:** Laravel 11, Inertia.js, Vue 3, PhpSpreadsheet, TypeScript, Tailwind CSS, PHPUnit.

---

### Task 1: Smart Hospital Normalization in `ArabicNormalizer`

**Files:**
- Modify: `app/Support/ArabicNormalizer.php`
- Modify: `tests/Unit/ArabicNormalizerTest.php`

**Step 1: Write failing unit test for `findHospital`**
Add test assertions in `tests/Unit/ArabicNormalizerTest.php` testing:
- Exact match on Arabic and English name.
- Match with and without prefixes ("مشفى", "مستشفى", "مركز", "مجمع").
- Match case-insensitive English.
- Return `null` when hospital cannot be resolved.

**Step 2: Run test to verify it fails**
Run: `php artisan test tests/Unit/ArabicNormalizerTest.php`
Expected: FAIL (`findHospital` method not defined).

**Step 3: Implement `findHospital` in `ArabicNormalizer`**
Add `findHospital($hospitals, ?string $rawHospital, ?string $govId = null)`:
- Normalizes incoming string using `self::normalize()`.
- Strips prefixes: `/(مشفى|مستشفى|مركز|مجمع)\s+/u`.
- Matches exact normalized `name_ar` or `name_en`.
- Supports filtering by governorate if provided.
- Substring match for names with length >= 4.

**Step 4: Run test to verify it passes**
Run: `php artisan test tests/Unit/ArabicNormalizerTest.php`
Expected: PASS (All tests passing).

**Step 5: Commit**
`git commit -m "feat(normalizer): add smart hospital normalization and prefix tolerance"`

---

### Task 2: Extended Doctor Template & Export Schema in `DataImportService`

**Files:**
- Modify: `app/Services/DataImportService.php` (`buildDoctorsTemplate`, `buildDoctorsExport`)

**Step 1: Write test for extended doctor export columns**
In `tests/Feature/DataExportRoundTripTest.php`:
Assert that exporting doctors includes columns for:
- Private Clinic: `اسم العيادة الخاصة`, `محافظة العيادة الخاصة`, `منطقة / حي العيادة الخاصة`, `عنوان العيادة الخاصة`, `هاتف العيادة الخاصة`.
- Hospital Clinic: `يعمل في مشفى؟ (نعم/لا)`, `اسم المشفى التابع له`, `اسم عيادة أو قسم المشفى`.

**Step 2: Run test to verify it fails**
Run: `php artisan test tests/Feature/DataExportRoundTripTest.php`
Expected: FAIL (missing new column headers).

**Step 3: Update `buildDoctorsTemplate()` and `buildDoctorsExport()`**
- Schema Headers:
  - Column A: `اسم الطبيب *`
  - Column B: `الاختصاص الطبي *`
  - Column C: `تصنيف الطبيب *`
  - Column D: `رقم هاتف الطبيب / الجوال`
  - Column E: `درجة التعاون`
  - Column F: `اسم العيادة الخاصة`
  - Column G: `محافظة العيادة الخاصة`
  - Column H: `منطقة / حي العيادة الخاصة`
  - Column I: `عنوان العيادة الخاصة`
  - Column J: `هاتف العيادة الخاصة`
  - Column K: `يعمل في مشفى؟ (نعم/لا)`
  - Column L: `اسم المشفى التابع له`
  - Column M: `اسم عيادة أو قسم المشفى`
  - Column N: `ملاحظات إضافية`
- Set generous static column widths for all columns A through N.
- Add Dropdown validations for Classification (A+, A, B, C), Cooperation (مرتفعة، متوسطة، منخفضة), and Works in Hospital (نعم, لا).
- In the Reference Sheet (`الدليل المرجعي`), include three reference tables:
  1. Approved Specialties (عربي وإنجليزي).
  2. Approved Governorates & Areas.
  3. Approved Hospitals List (`المشافي المعتمدة`).
- In `buildDoctorsExport()`, query doctor workplaces:
  - Extract the `private_clinic` workplace for columns F-J.
  - Extract the `hospital_clinic` workplace for columns K-M.

**Step 4: Run test to verify it passes**
Run: `php artisan test tests/Feature/DataExportRoundTripTest.php`
Expected: PASS.

**Step 5: Commit**
`git commit -m "feat(export): extend doctor template and export schema to support private and hospital clinics"`

---

### Task 3: Dual Workplace Parsing & Execution in `DataImportService`

**Files:**
- Modify: `app/Services/DataImportService.php` (`previewDoctors`, `executeImport`)

**Step 1: Write test for importing doctor with both private and hospital clinic**
In `tests/Feature/TemplateDataImportTest.php`:
- Test doctor with only private clinic -> creates 1 `DoctorWorkplace` (`private_clinic`, `is_primary = true`).
- Test doctor with only hospital clinic -> creates 1 `DoctorWorkplace` (`hospital_clinic`, `is_primary = true`, `hospital_id` set).
- Test doctor with both private and hospital clinic -> creates 2 `DoctorWorkplace` records (private as `is_primary = true`, hospital as `is_primary = false`).
- Test legacy 9-column format -> correctly imports without error.

**Step 2: Run test to verify it fails**
Run: `php artisan test tests/Feature/TemplateDataImportTest.php`
Expected: FAIL.

**Step 3: Implement workplace parsing in `previewDoctors()` & `executeImport()`**
- In `previewDoctors()`:
  - Add dictionary entry: `'hospitals' => Hospital::with('area.governorate')->get()`.
  - Check for extended column names (`اسم العيادة الخاصة`, `اسم المشفى التابع له`, etc.) with fallback to legacy column names (`اسم العيادة / المركز`, `المحافظة`, `المنطقة / الحي`).
  - Parse Private Clinic: Resolve Governorate & Area via `ArabicNormalizer::findGovernorate` & `findArea`.
  - Parse Hospital Clinic: If `works_in_hospital === 'نعم'` or `hospital_name` is provided:
    - Match hospital via `ArabicNormalizer::findHospital($dict['hospitals'], $rawHospitalName)`.
    - If found: link `hospital_id` and inherit/validate area.
    - If not found and hospital name was specified: add warning/error "المشفى غير معروف".
  - Return detailed payload containing both `private_workplace` and `hospital_workplace` sub-arrays.
- In `executeImport()`:
  - Create the `Doctor` record.
  - If `private_workplace` data exists:
    - Create `DoctorWorkplace` with `workplace_type = 'private_clinic'`, `is_primary = true`.
  - If `hospital_workplace` data exists:
    - Create `DoctorWorkplace` with `workplace_type = 'hospital_clinic'`, `hospital_id = $hospId`, `is_primary = (empty($private_workplace))`.

**Step 4: Run test to verify it passes**
Run: `php artisan test tests/Feature/TemplateDataImportTest.php`
Expected: PASS.

**Step 5: Commit**
`git commit -m "feat(import): support importing doctors with private clinic, hospital clinic, or both"`

---

### Task 4: Enhance Pharmacy Hospital Affiliation & Reference Guide

**Files:**
- Modify: `app/Services/DataImportService.php` (`buildPharmaciesTemplate`, `buildPharmaciesExport`, `previewPharmacies`)

**Step 1: Write test for pharmacy hospital matching with ArabicNormalizer**
In `tests/Feature/TemplateDataImportTest.php`:
- Verify importing a hospital pharmacy matches hospital names like "مستشفى الحكمة" to "مشفى الحكمة".
- Verify pharmacy template contains approved hospitals in reference sheet.

**Step 2: Run test to verify it fails**
Run: `php artisan test tests/Feature/TemplateDataImportTest.php`
Expected: FAIL.

**Step 3: Update `DataImportService.php` for Pharmacies**
- In `buildPharmaciesTemplate()` and `buildPharmaciesExport()`:
  - Add Column C to the reference sheet: `قائمة المشافي والمراكز المعتمدة`.
  - Populate with all registered hospitals in the database.
- In `previewPharmacies()`:
  - Use `ArabicNormalizer::findHospital($dict['hospitals'], $rawHospName)` instead of strict array key lookup.
  - If `isHospitalPharmacy` is true and hospital is matched, store `hospital_id` and show hospital name badge in preview table.

**Step 4: Run test to verify it passes**
Run: `php artisan test tests/Feature/TemplateDataImportTest.php`
Expected: PASS.

**Step 5: Commit**
`git commit -m "feat(pharmacy): enrich pharmacy hospital matching and reference guide"`

---

### Task 5: Update Frontend Preview Table in Vue

**Files:**
- Modify: `resources/js/pages/Admin/Import/Index.vue`

**Step 1: Update Doctor & Pharmacy Preview Columns**
- In `tableHeaders`:
  - For Doctors: Display:
    - `الطبيب والاختصاص`
    - `التصنيف والتعاون`
    - `العيادة الخاصة` (اسم العيادة والموقع)
    - `عيادة المشفى` (اسم المشفى والقسم مع شارة ملونة Hospital Badge)
    - `الهواتف`
- In `preview` rows:
  - Render a clean badge `عيادة خاصة` and `عيادة مشفى` so the user clearly sees both workplaces resolved before confirming import.

**Step 2: Verify in browser / compile assets**
Run: `npm run build`
Expected: Build succeeds with 0 errors.

**Step 3: Commit**
`git commit -m "feat(ui): display dual workplace badges in import preview table"`

---

### Task 6: Comprehensive Regression Testing & cPanel Repackaging

**Files:**
- Modify: `package_cpanel.ps1`
- Test: All Unit & Feature tests

**Step 1: Run complete test suite**
Run: `php artisan test tests/Unit/ArabicNormalizerTest.php tests/Feature/DataExportRoundTripTest.php tests/Feature/TemplateDataImportTest.php`
Expected: All tests PASS.

**Step 2: Synchronize with Sibling Repo**
Sync changes to `c:\Users\hasan\Herd\creative-medvisits`.

**Step 3: Re-package cPanel update**
Run: `powershell -ExecutionPolicy Bypass -File .\package_cpanel.ps1`
Verify: `cpanel_update_import_export.zip` is updated.

**Step 4: Git Push**
Commit and push both `hilal-medical-visits` and `creative-medvisits` to `origin main`.
