# RedBean Kashf (Medical Examination) Controller Documentation

**File**: `/controllers/rb_kashf.php`  
**Purpose**: Medical examination management system with comprehensive accounting integration, patient tracking, and cash register management  
**Last Updated**: December 20, 2024  
**Total Functions**: 12+  
**Lines of Code**: ~896

---

## 📋 Overview

The RedBean Kashf Controller manages medical examination operations for optical/medical clinics. It provides comprehensive functionality for:
- Patient examination registration and management
- Doctor assignment and tracking
- Medical examination fee processing with accounting integration
- Cash register integration with automatic balance updates
- Client debt tracking and payment history
- Examination editing and deletion with transaction reversal
- Print-friendly examination records
- Complete audit trail for all medical transactions

### Primary Functions
- [x] Medical examination registration with patient and doctor assignment
- [x] Automatic accounting journal entry creation for examination fees
- [x] Cash register integration with balance validation and updates
- [x] Client debt change tracking and history management
- [x] Examination editing with accounting transaction reversal
- [x] Doctor and patient management integration
- [x] Print formatting for examination records
- [x] Complete transaction audit trail and reversibility

### Related Controllers
- [clientController.php](#) - Patient/customer management
- [userController.php](#) - Doctor management (user type 4)
- [dailyentryfun.php](dailyentryfun.md) - Accounting journal entries
- [saveController.php](#) - Cash register management
- [clientdebtchangeController.php](#) - Client debt tracking

---

## 🗄️ Database Tables

### Core Medical Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **kashf** | Medical examinations | id, kashfvalue, kashftype, customerid, doctorid, kashfdate, paystatus |
| **client** | Patients/customers | clientid, clientname, clientphone, clientaddress |
| **user** | Doctors (type 4) | userid, username, usergroupid, usertype |
| **clientarea** | Patient area/region | clientareaid, areaname |

### Financial Integration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Cash registers | saveid, savename, savecurrentvalue, treeId |
| **savedaily** | Cash register transactions | saveid, savedailychangeamount, savedailychangetype, processname |
| **clientdebtchange** | Patient payment history | clientid, clientdebtchangeamount, clientdebtchangedate, processname |
| **dailyentry** | Accounting journal headers | id, totalcreditor, totaldebtor, entryComment |
| **dailyentrycreditor** | Credit entries | dailyentryid, accountstreeid, value, dComment |
| **dailyentrydebtor** | Debit entries | dailyentryid, accountstreeid, value, dComment |

---

## 🔑 Key Functions

### 1. **Default Action** - Examination Registration Form
**Location**: Line 101  
**Purpose**: Display examination registration form with required data

**Setup Process**:
```php
$today = date('Y-m-d');
$customer = $ClientDAO->queryAll();  // All patients
$Doctor = $doctorDAOEx->loadDocotr(4);  // Type 4 = doctors
$clientarea = $ClientareaDAO->queryAll();  // Patient areas

// Generate new examination ID
$kashfDetails = $kashfDAO->queryAll();
$last_obj = end($kashfDetails);
$new_id = $last_obj->id + 1;

$smarty->assign('new_id', $new_id);
```

### 2. **add** - Create Medical Examination
**Location**: Line 133  
**Purpose**: Process new medical examination with complete financial integration

**Function Logic**:
```php
function add() {
    // Extract form data
    $customerid = filter_input(INPUT_POST, 'client');
    $datetoday = filter_input(INPUT_POST, 'kashfdate');
    $docselect = filter_input(INPUT_POST, 'docselect');
    $kashf_value = (float) filter_input(INPUT_POST, 'kashf_value');
    $kasf_type = filter_input(INPUT_POST, 'kasf_type');
    $paytype = 2; // Fixed: payment completed
    
    // Validation checks
    if ($customerid == '-1') {
        // Show error: invalid customer
        return;
    }
    
    if ($docselect == '-1') {
        // Show error: invalid doctor
        return;
    }
    
    if ($datetoday < date('Y-m-d')) {
        // Show error: invalid date
        return;
    }
    
    // Create examination record
    $kashf->kashfvalue = $kashf_value;
    $kashf->kashftype = $kasf_type;
    $kashf->customerid = $customerid;
    $kashf->doctorid = $docselect;
    $kashf->kashfdate = $datetoday;
    $kashf->paystatus = $paytype;
    $kashf->entered = 0;
    $kashf->dailyentryid = 0;
    
    $kashId = $kashfDAO->insert($kashf);
}
```

**Client Debt Tracking Integration**:
```php
// Load last client debt change for continuity
$last_client_deptchaneg = $clientDeptChangeExt->selectLastClientDept($customerid);

if (!empty($customerid)) {
    // Create debt change record (no amount change for examination booking)
    $clientDeptChange->clientdebtchangeafter = $last_client_deptchaneg[0]->clientdebtchangeafter;
    $clientDeptChange->clientdebtchangeamount = 0;  // No debt change
    $clientDeptChange->clientdebtchangebefore = $last_client_deptchaneg[0]->clientdebtchangebefore;
    $clientDeptChange->clientdebtchangemodelid = $kashId;
    $clientDeptChange->processname = "إضافة كشف جديد";
    $clientDeptChange->tablename = "rb_kashf.php";
    
    $clientDeptChangeDAO->insert($clientDeptChange);
}
```

**Accounting Integration**:
```php
// Create journal entry for examination income
$dailyEntry->entryComment = 'تم حجز كشف بصريات';

// Debit: Cash Register (money received)
$dailyEntryDebtor->value = $kashf_value;
$saveid = $_SESSION['saveid'];
$dataSave = $mySaveRecord->load($saveid);
$idTreeSave = $dataSave->treeId;
$dailyEntryDebtor->accountstreeid = $idTreeSave;

// Credit: Medical Services Income Account (fixed account 273)
$dailyEntryCreditor->value = $kashf_value;
$dailyEntryCreditor->accountstreeid = 273;

// Execute journal entry
$returnDailyId = insertEntery($dailyEntry, [$dailyEntryDebtor], [$dailyEntryCreditor]);
$dailyId = $returnDailyId[1];

// Update examination with journal entry ID
$kashf->dailyentryid = $dailyId;
$kashfDAO->update($kashf);
```

**Cash Register Update**:
```php
// Update cash register balance
$saveDatat = $mySaveRecord->load($saveid);
$mySave->savecurrentvalue = ($saveDatat->savecurrentvalue + $kashf_value);
$mySaveRecord->update($mySave);

// Log cash register transaction
$mySavedaily->savedailychangeamount = $kashf_value;
$mySavedaily->savedailychangetype = 0;  // Increase
$mySavedaily->processname = 'تم حجز كشف بصريات';
$mySavedaily->savedailymodelid = $kashId;
$mySavedaily->savedailysaveafter = ($saveDatat->savecurrentvalue + $kashf_value);
$mySavedaily->savedailysavebefore = $saveDatat->savecurrentvalue;
$mySavedaily->tablename = 'rb_kashf.php';
$mySavedailyRecord->insert($mySavedaily);
```

---

### 3. **show** - Display Examinations List
**Location**: Line 347  
**Purpose**: Show all examinations with customer and doctor details

**Data Processing**:
```php
$showkashf = $kashfDAOEx->queryAllDESC();

foreach ($showkashf as $kdata) {
    $custid = $kdata->customerid;
    $docid = $kdata->doctorid;
    
    // Load customer information
    $custData = $ClientDAO->load($custid);
    $kdata->custname = $custData->clientname;
    
    // Load doctor information
    $docdata = $doctorDAOEx->loadDocotr2($docid, 4);
    $kdata->DocData = $docdata->username;
}
```

---

### 4. **update** - Examination Modification
**Location**: Line 434  
**Purpose**: Update examination with accounting transaction reversal and recreation

**Complex Update Logic**:
```php
function update() {
    $custselect = filter_input(INPUT_POST, 'custselect');
    $docselect = filter_input(INPUT_POST, 'docselect');
    $kashf_value = filter_input(INPUT_POST, 'kashf_value');
    $kashfid = filter_input(INPUT_POST, 'kashfid');
    $oldCustomer = filter_input(INPUT_POST, 'client');
    
    if ($oldCustomer == $custselect) {
        // Same customer - simple update
        $loadkashf2 = $kashfDAO->load($kashfid);
        $loadkashf2->kashfvalue = $kashf_value;
        $loadkashf2->kashftype = $kasf_type;
        $loadkashf2->doctorid = $docselect;
        
        // Reverse old accounting entry
        $dailyId1 = $loadkashf2->dailyentryid;
        reverseEntryWithItsID($dailyId1);
        
        // Create new accounting entry with updated values
        $dailyEntry->entryComment = 'تم تعديل الكشف ';
        $returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
        $dailyId2 = $returnDailyId[1];
        
        $loadkashf2->dailyentryid = $dailyId2;
        $kashfDAO->update($loadkashf2);
        
    } else {
        // Customer changed - more complex update
        // Full validation and re-creation process
    }
}
```

---

### 5. **delete** - Examination Deletion
**Location**: Line 870  
**Purpose**: Delete examination and reverse all associated transactions

**Deletion Process**:
```php
elseif ($do == 'delete') {
    // Delete examination record
    $kashfDAO->delete($id);
    
    // Reverse associated journal entry
    reverseEntryWithItsID($dilEntry);
    
    // Note: Cash register and debt changes are reversed via journal entry reversal
    header('location:?do=show');
}
```

---

## 🔄 Workflows

### Workflow 1: Complete Medical Examination Registration
```
┌─────────────────────────────────────────────────────────────┐
│            START: Medical Examination Registration         │
│   Patient visits clinic for eye examination               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Form Preparation & Display                             │
│     - Load all active patients from client table           │
│     - Load all doctors (user.usertype = 4)                │
│     - Load patient area/region data                        │
│     - Generate next examination ID for reference           │
│     - Set default date to today                            │
│     - Display registration form (kashf_add.html)           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Form Submission & Validation                           │
│     A. Extract Form Data:                                   │
│       - client = patient ID                                │
│       - docselect = doctor ID                              │
│       - kashf_value = examination fee                      │
│       - kasf_type = examination type/description           │
│       - kashfdate = examination date                       │
│                                                             │
│     B. Validation Checks:                                  │
│       IF customerid = '-1': Show "راجع اختيار العميل"       │
│       IF docselect = '-1': Show "راجع اختيار الطبيب"        │
│       IF kashfdate < today: Show "راجع اختيار التاريخ"       │
│       IF kasf_type empty: Show "ادخل نوع الكشف"            │
│       IF kashf_value <= 0: Show "راجع سعر الكشف"           │
│                                                             │
│     IF any validation fails: redisplay form with error     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Examination Record                              │
│     - Insert into kashf table:                             │
│       * kashfvalue = examination fee                       │
│       * kashftype = examination description                │
│       * customerid = selected patient                      │
│       * doctorid = selected doctor                         │
│       * kashfdate = examination date                       │
│       * paystatus = 2 (payment completed)                  │
│       * entered = 0 (not yet processed)                    │
│       * dailyentryid = 0 (will be updated after journal)   │
│     - Get new kashf ID for linking                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Client Debt Tracking Integration                       │
│     A. Load Previous Debt Status:                          │
│       - Get last clientdebtchange record for patient       │
│       - Maintain debt continuity chain                     │
│                                                             │
│     B. Create Debt Change Record:                          │
│       - clientdebtchangeamount = 0 (no debt change)        │
│       - clientdebtchangeafter = previous balance           │
│       - clientdebtchangebefore = previous balance          │
│       - processname = "إضافة كشف جديد"                      │
│       - tablename = "rb_kashf.php"                         │
│       - clientdebtchangemodelid = kashf ID                 │
│                                                             │
│     NOTE: Examination booking doesn't change debt,         │
│           but maintains audit trail                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Accounting Integration - Journal Entry Creation        │
│     A. Prepare Journal Entry Header:                       │
│       - entryComment = 'تم حجز كشف بصريات'                  │
│       - thedate = current date                             │
│       - userid = current user                              │
│                                                             │
│     B. Prepare Debit Entry (Cash Received):                │
│       - Load current cash register (save) from session     │
│       - Get cash register's linked chart of accounts ID    │
│       - Create debit entry:                                │
│         * accountstreeid = cash register account           │
│         * value = examination fee                          │
│         * dComment = cash received description             │
│                                                             │
│     C. Prepare Credit Entry (Medical Services Income):     │
│       - Use fixed account ID 273 for medical services      │
│       - Create credit entry:                               │
│         * accountstreeid = 273 (medical services income)   │
│         * value = examination fee                          │
│         * dComment = examination income description        │
│                                                             │
│     D. Execute Journal Entry:                              │
│       - Call insertEntery() from dailyentryfun.php        │
│       - Validate debits = credits                          │
│       - Update chart of accounts balances                 │
│       - Get new journal entry ID                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Cash Register Integration                              │
│     A. Update Cash Register Balance:                        │
│       - Load current cash register data                    │
│       - Calculate new balance: current + examination fee   │
│       - Update save.savecurrentvalue                       │
│                                                             │
│     B. Log Cash Register Transaction:                       │
│       - Insert into savedaily table:                       │
│         * savedailychangeamount = examination fee          │
│         * savedailychangetype = 0 (increase)               │
│         * processname = 'تم حجز كشف بصريات'                 │
│         * savedailymodelid = kashf ID                      │
│         * savedailysavebefore = old balance                │
│         * savedailysaveafter = new balance                 │
│         * tablename = 'rb_kashf.php'                       │
│         * clientid = patient ID                            │
│                                                             │
│     C. Maintain Complete Audit Trail:                      │
│       - Link cash transaction to examination               │
│       - Enable future transaction reversal                │
│       - Support financial reporting                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  7. Finalize Examination Record                            │
│     A. Update Examination with Journal Entry:              │
│       - Load created kashf record by ID                    │
│       - Set dailyentryid = journal entry ID                │
│       - Update kashf record                                │
│                                                             │
│     B. Complete Integration:                               │
│       - Examination now linked to accounting system        │
│       - Cash register balance updated                      │
│       - Client debt history maintained                     │
│       - Full audit trail established                       │
│                                                             │
│     C. Success Response:                                    │
│       - Redirect to examination list (?do=show)            │
│       - Display success message                            │
│       - Enable future editing/deletion                     │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Examination Update with Transaction Reversal
```
┌─────────────────────────────────────────────────────────────┐
│              START: Edit Existing Examination              │
│   User modifies examination fee, doctor, or details        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Examination for Editing                           │
│     - Load kashf record by ID                              │
│     - Load associated customer data                        │
│     - Load associated doctor data                          │
│     - Populate edit form with current values               │
│     - Display kashf_edit.html template                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Update Request                                  │
│     A. Extract Updated Data:                                │
│       - custselect = new/same customer ID                  │
│       - docselect = new/same doctor ID                     │
│       - kashf_value = new/same examination fee             │
│       - kasf_type = new/same examination type              │
│       - kashfid = examination ID being updated             │
│       - oldCustomer = original customer ID                 │
│                                                             │
│     B. Determine Update Complexity:                        │
│       IF oldCustomer = custselect:                         │
│         - Simple update (same customer)                    │
│       ELSE:                                                │
│         - Complex update (customer changed)               │
│         - Additional validation required                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Validation Phase                                       │
│     A. Standard Validations:                               │
│       - Customer selection valid                          │
│       - Doctor selection valid                            │
│       - Date not in the past                              │
│       - Examination type specified                        │
│       - Examination fee > 0                               │
│                                                             │
│     B. Customer Change Validations (if applicable):        │
│       - New customer exists and active                     │
│       - Debt implications considered                       │
│                                                             │
│     IF any validation fails: redisplay form with errors    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Reverse Original Accounting Transactions               │
│     A. Load Original Journal Entry:                        │
│       - Get dailyentryid from original kashf record        │
│       - Load complete journal entry details                │
│                                                             │
│     B. Execute Reversal:                                   │
│       - Call reverseEntryWithItsID(original_dailyentryid)  │
│       - This creates automatic reversing entry:            │
│         * Original debit (cash) → new credit (cash)        │
│         * Original credit (income) → new debit (income)    │
│         * Restores account balances to pre-examination     │
│       - Mark original entry as reversed                    │
│                                                             │
│     C. Cash Register Impact:                               │
│       - Reversal automatically adjusts cash balance        │
│       - Removes original examination fee from register     │
│       - Maintains audit trail of reversal                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Create New Accounting Transactions                     │
│     A. Prepare New Journal Entry:                          │
│       - entryComment = 'تم تعديل الكشف'                     │
│       - Use updated examination fee amount                 │
│       - Same accounts as original (cash + medical income)  │
│                                                             │
│     B. Execute New Journal Entry:                          │
│       - Create debit: cash register account                │
│       - Create credit: medical services income account     │
│       - Use NEW examination fee amount                     │
│       - Call insertEntery() to process                     │
│       - Get new journal entry ID                           │
│                                                             │
│     C. Update Cash Register:                               │
│       - Add NEW examination fee to cash balance            │
│       - Log new cash transaction                           │
│       - Link to updated examination ID                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Update Examination Record                              │
│     A. Update Kashf Table:                                 │
│       - kashfvalue = new examination fee                   │
│       - kashftype = new examination type                   │
│       - doctorid = new doctor ID                           │
│       - customerid = new customer ID (if changed)          │
│       - kashfdate = new date (if changed)                  │
│       - dailyentryid = new journal entry ID                │
│                                                             │
│     B. Maintain Data Integrity:                            │
│       - All related records properly linked                │
│       - Audit trail preserved                              │
│       - Financial transactions balanced                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  7. Handle Customer Debt Impact (if customer changed)      │
│     IF customer changed:                                    │
│       A. Remove from old customer debt history             │
│       B. Add to new customer debt history                  │
│       C. Update both customer debt chains                  │
│       D. Maintain debt balance continuity                  │
│                                                             │
│     IF same customer:                                      │
│       - No debt change impact                              │
│       - Only examination details updated                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  8. Completion & Response                                   │
│     - Redirect to examination list (?do=show)              │
│     - Display update success message                       │
│     - Enable further editing if needed                     │
│                                                             │
│  NET EFFECT:                                                │
│     - Original examination completely reversed             │
│     - New examination properly recorded                    │
│     - All financial impacts correctly applied              │
│     - Complete audit trail maintained                      │
│     - Cash register balance accurate                       │
└─────────────────────────────────────────────────────────────┘
```

---

## 💰 Financial Integration Details

### Chart of Accounts Integration
```php
// Cash Register Account (Dynamic - based on user's assigned register)
$saveid = $_SESSION['saveid'];
$dataSave = $mySaveRecord->load($saveid);
$cashAccountId = $dataSave->treeId;

// Medical Services Income Account (Fixed)
$medicalIncomeAccountId = 273;

// Journal Entry Structure:
// DR: Cash Register Account     $examination_fee
// CR: Medical Services Account  $examination_fee
```

### Client Debt vs Cash Payment Logic
```php
// Current Implementation: Immediate Cash Payment
$clientDeptChange->clientdebtchangeamount = 0;  // No debt created
$mySave->savecurrentvalue += $kashf_value;     // Cash added immediately

// Alternative: Credit/Debt System (for future implementation)
// $clientDeptChange->clientdebtchangeamount = $kashf_value;  // Create debt
// Cash received only when payment made separately
```

### Account Balance Effects
```
Before Examination:
- Cash Register Balance: $1,000
- Medical Income Account: $5,000

After $100 Examination:
- Cash Register Balance: $1,100  (+$100)
- Medical Income Account: $5,100  (+$100)

Journal Entry:
DR: Cash Register (Asset)     $100
CR: Medical Income (Revenue)  $100
```

---

## 🔒 Security & Data Validation

### Input Validation
```php
// Date validation
$datetoday = filter_input(INPUT_POST, 'kashfdate');
$now = new DateTime();
$date = $now->format('Y-m-d');
if ($kashfdate < $date) {
    // Show error: future dates only
}

// Amount validation  
$kashf_value = (float) filter_input(INPUT_POST, 'kashf_value');
if ($kashf_value <= 0) {
    // Show error: positive amounts only
}

// Entity validation
if ($customerid == '-1' || $docselect == '-1') {
    // Show error: valid selections required
}
```

### Transaction Integrity
- All operations wrapped in database transactions
- Journal entries automatically balance debit/credit
- Cash register updates linked to journal entries
- Reversal operations maintain audit trail

### Access Control
- Requires active user session
- Doctor selection limited to user type 4
- Cash register access controlled by user assignment

---

## 📊 Performance Considerations

### Database Optimization
1. **Critical Indexes**:
   ```sql
   CREATE INDEX idx_kashf_customer ON kashf(customerid, kashfdate);
   CREATE INDEX idx_kashf_doctor ON kashf(doctorid, kashfdate);
   CREATE INDEX idx_savedaily_kashf ON savedaily(savedailymodelid, tablename);
   CREATE INDEX idx_clientdebt_kashf ON clientdebtchange(clientdebtchangemodelid, tablename);
   ```

2. **Query Patterns**:
   - Frequent lookups by customer and doctor
   - Date range filtering for reporting
   - Cash register transaction tracking

### Memory Management
- Limited result sets for dropdown lists
- Efficient object loading for edit operations
- Minimal template variable assignment

---

## 🐛 Common Issues & Troubleshooting

### 1. **Journal Entry Imbalance**
**Issue**: Debits don't equal credits error  
**Cause**: Currency conversion or calculation error

**Debug**:
```php
echo "Debit Amount: " . $dailyEntryDebtor->value;
echo "Credit Amount: " . $dailyEntryCreditor->value;
echo "Examination Fee: " . $kashf_value;
```

### 2. **Cash Register Balance Issues**
**Issue**: Cash register shows incorrect balance  
**Cause**: Failed transaction or reversal issue

**Debug**:
```php
$saveData = $mySaveRecord->load($_SESSION['saveid']);
echo "Current Balance: " . $saveData->savecurrentvalue;

// Check recent transactions
$recentTransactions = R::getAll("SELECT * FROM savedaily 
    WHERE tablename = 'rb_kashf.php' 
    ORDER BY savedailydate DESC LIMIT 10");
```

### 3. **Customer/Doctor Not Loading**
**Issue**: Dropdowns show empty or wrong data  
**Cause**: Query filtering or deleted records

**Debug**:
```php
// Check doctor query
$doctors = $doctorDAOEx->loadDocotr(4);
echo "Doctor Count: " . count($doctors);

// Check customer query  
$customers = $ClientDAO->queryAll();
echo "Customer Count: " . count($customers);
```

### 4. **Update Errors**
**Issue**: Examination update fails or creates duplicates  
**Cause**: Transaction reversal failure

**Debug**:
```php
echo "Original Journal Entry ID: " . $originalKashf->dailyentryid;
echo "New Journal Entry ID: " . $newDailyEntryId;

// Check reversal status
$originalEntry = $dailyEntryDAO->load($originalKashf->dailyentryid);
echo "Reversal Status: " . $originalEntry->reverseofid;
```

---

## 📱 Print & Display Features

### Print Formatting
```php
if ($do == 'editprint') {
    // Load examination data for print format
    $editkasf = $kashfDAO->load($id);
    
    // Load related data
    $custData = $ClientDAO->load($editkasf->customerid);
    $docdata = $doctorDAOEx->loadDocotr2($editkasf->doctorid, 4);
    
    // Display print template
    $smarty->display('rb_kashf/kashf_editprint.html');
}
```

### Custom Display Variable
```php
// Special template variable for kashf functionality
$smarty->assign("customKashf", 1);

// Used in templates for:
// - Special CSS styling
// - Custom navigation elements  
// - Kashf-specific UI components
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Examination Creation
```
1. Access examination form
2. Select valid patient and doctor
3. Enter examination fee and type
4. Submit form
5. Verify examination created
6. Check cash register balance increased
7. Verify journal entry created
8. Check client debt change record
```

### Test Case 2: Examination Update
```
1. Edit existing examination
2. Change examination fee amount
3. Verify original transaction reversed
4. Verify new transaction created
5. Check cash register balance adjusted correctly
6. Verify journal entries balanced
```

### Test Case 3: Examination Deletion
```
1. Delete examination record
2. Verify examination marked as deleted
3. Check journal entry reversal
4. Verify cash register balance decreased
5. Check audit trail maintained
```

### Test Case 4: Validation Testing
```
1. Submit form with invalid customer (-1)
2. Verify error message displayed
3. Submit with past date
4. Verify date validation error
5. Submit with zero amount
6. Verify amount validation error
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [dailyentryfun.md](dailyentryfun.md) - Accounting journal functions
- [clientController.php](#) - Patient management
- [Medical Practice Management Guide](#) - Best practices for medical systems

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When medical examination workflow changes