# Faida Director Controller Documentation

**File**: `/controllers/FaidaDireController.php`  
**Purpose**: Manages approval/rejection workflow for interest/profit transactions (Faida) by directors  
**Last Updated**: December 20, 2024  
**Total Functions**: 6  
**Lines of Code**: ~426

---

## 📋 Overview

The Faida Director Controller handles the approval and rejection process for profit/interest transactions (Faida) in the system. It provides a workflow where directors can review, approve, or reject profit applications submitted by users, with automatic debt adjustment upon approval.

### Primary Functions
- [x] Display pending profit applications for director review
- [x] Approve profit applications and update customer debt
- [x] Reject profit applications with comments
- [x] Automatic customer debt change tracking
- [x] Bill settings and configuration loading
- [x] YouTube tutorial link integration

### Related Controllers
- [FaidaController.php](FaidaController.md) - Main profit transaction management
- [clientController.php](#) - Customer management
- [clientPayedDeptController.php](#) - Payment processing

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **faidadirector** | Director approval/rejection records | id, faidaId, comment, conditions |
| **faida** | Profit/interest transactions | id, clientId, total_amount, conditions, user_id |
| **client** | Customer master data | clientid, clientname, clientdebt |
| **clientdebtchange** | Customer debt change log | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype |

### Configuration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue |
| **billname** | Bill type definitions | billnameid, billname |
| **billsettings** | Bill configuration | billsettingsid, billnameid, property |
| **unit** | Measurement units | unitid, unitname |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, username, employeename |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |
| **store** | Store locations | storeid, storename |

---

## 🔑 Key Functions

### 1. **show() / Default Action** - Director Review Interface
**Location**: Line 172  
**Purpose**: Display all pending profit applications for director review

**Function Signature**:
```php
// Triggered when: do=show or empty $do
```

**Process Flow**:
1. Load system configuration and VAT settings
2. Load bill name and settings for type 3
3. Load unit data for dropdowns
4. Call `show()` function to get pending applications
5. Load YouTube tutorial links
6. Display via `showDir.html` template

**Features**:
- Loads pending Faida applications with client details
- Shows user who created each application
- Provides approval/rejection interface

---

### 2. **approval** - Approve Profit Application
**Location**: Line 203  
**Purpose**: Approve a profit application and update customer debt

**Function Signature**:
```php
$faida_id = filter_input(INPUT_POST, 'faida_id');
$comment = filter_input(INPUT_POST, 'comment');
```

**Process Flow**:
1. Check if director record already exists for this Faida
2. If exists, update existing record; otherwise create new one
3. Set conditions = 0 (approved)
4. Update Faida record status to approved (conditions = 1)
5. Load customer data and increase debt by total_amount
6. Insert client debt change record
7. Redirect to success page

**Debt Update Process**:
```php
$total = $rowData->clientdebt + $faida->total_amount;
$myClient->clientdebt = $total;
$myClientRecord->update($myClient);
```

**Debt Change Tracking**:
```php
$clientDeptChange->clientdebtchangeamount = $faida->total_amount;
$clientDeptChange->clientdebtchangetype = 0; // Debt increase
$clientDeptChange->processname = "إضافة فايده لعميل ";
$clientDeptChange->tablename = "FaidaController.php";
```

---

### 3. **refusal** - Reject Profit Application
**Location**: Line 309  
**Purpose**: Reject a profit application with director comments

**Function Signature**:
```php
$faida_id = filter_input(INPUT_POST, 'faida_id');
$comment = filter_input(INPUT_POST, 'comment');
```

**Process Flow**:
1. Create director record with conditions = 1 (rejected)
2. Update Faida record status to rejected (conditions = 2)
3. Record rejection comment
4. No debt changes are made
5. Redirect to success page

**Key Difference from Approval**:
- Sets Faida conditions = 2 (rejected) instead of 1 (approved)
- Does not update customer debt
- Does not create debt change records

---

### 4. **show()** - Load Pending Applications
**Location**: Line 383  
**Purpose**: Retrieve all pending Faida applications with user and client details

**Function Signature**:
```php
function show()
```

**Process Flow**:
1. Query all Faida records by conditions using `queryAllByConditions()`
2. For each record:
   - Load username from user table
   - Load client name from client table
   - Attach data to Faida object
3. Return enriched array

**Data Enrichment**:
```php
$user = $userDAO->load($item->user_id);
$item->username = $user->username;

$clientData = $myClientEx->loadExt($client_id);
$item->clientname = $single->clientname;
```

---

### 5. **loadBillProperty()** - Load Bill Configuration
**Location**: Line 404  
**Purpose**: Load bill settings for a specific bill type

**Function Signature**:
```php
function loadBillProperty($billnameid)
```

**Returns**: Bill settings array for the specified bill name ID

---

### 6. **loadUnit()** - Load Measurement Units
**Location**: Line 419  
**Purpose**: Load all active measurement units for dropdowns

**Function Signature**:
```php
function loadUnit()
```

**Returns**: Array of active unit records

---

## 🔄 Workflows

### Workflow 1: Profit Application Approval Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Director Reviews Application            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Director Selects Application                            │
│     - View application details                              │
│     - See customer information                              │
│     - Review requested amount                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Director Decision                                       │
│     ┌─────────────┬─────────────────┬─────────────────────┐ │
│     │   APPROVE   │     REJECT      │      CANCEL        │ │
│     │             │                 │                     │ │
│     └─────────────┼─────────────────┼─────────────────────┘ │
└─────────────────────┬─────────────────┬─────────────────────┘
                     │                 │
            ┌────────▼──────────┐     │
            │   APPROVAL PATH   │     │
            └────────┬──────────┘     │
                     │                 │
                     ▼                 ▼
┌─────────────────────────────────────────────────────────────┐
│  3a. Process Approval                                       │
│     - Create/Update director record (conditions=0)          │
│     - Update Faida status (conditions=1)                    │
│     - Increase customer debt                                │
│     - Create debt change record                             │
│     - Log process details                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3b. Process Rejection                                      │
│     - Create director record (conditions=1)                 │
│     - Update Faida status (conditions=2)                    │
│     - Record rejection comment                              │
│     - No debt changes made                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Completion                                              │
│     - Redirect to success page                              │
│     - Remove from pending list                              │
│     - Notify relevant parties                               │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Default action | Display pending applications |
| `do=approval` | `approval` | Approve application |
| `do=refusal` | `refusal` | Reject application |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Required Parameters by Action

**Approval** (`do=approval`):
- `faida_id` - Application ID to approve
- `comment` - Director's approval comment

**Rejection** (`do=refusal`):
- `faida_id` - Application ID to reject  
- `comment` - Director's rejection reason

---

## 🧮 Calculation Methods

### Customer Debt Increase (Approval)
```php
// Get current customer debt
$rowData = $myClientRecord->load($faida->clientId);
$total = $rowData->clientdebt + $faida->total_amount;

// Update customer record
$myClient->clientdebt = $total;
$myClientRecord->update($myClient);
```

### Debt Change Tracking
```php
$clientDeptChange->clientdebtchangeafter = $faida->total_amount + $data->clientdebtchangeafter;
$clientDeptChange->clientdebtchangeamount = $faida->total_amount;
$clientDeptChange->clientdebtchangebefore = $data->clientdebtchangeafter;
$clientDeptChange->clientdebtchangetype = 0; // Debt increase
```

---

## 🔒 Security & Permissions

### Authentication Required
- All actions require authentication via `include_once("../public/authentication.php")`
- Session-based user identification: `$_SESSION['userid']`

### Input Validation
```php
$faida_id = filter_input(INPUT_POST, 'faida_id');
$comment = filter_input(INPUT_POST, 'comment');
```

### Transaction Integrity
- Uses try-catch blocks for error handling
- Proper database transaction management
- Rollback capability on errors

---

## 🐛 Common Issues & Troubleshooting

### 1. **Duplicate Approval Records**
**Issue**: Multiple director records for same Faida  
**Cause**: Multiple approval attempts

**Debug**:
```sql
SELECT * FROM faidadirector WHERE faidaId = [ID];
```

**Solution**: Check existing records before insertion

### 2. **Customer Debt Not Updated**
**Issue**: Approval processed but debt unchanged  
**Cause**: Client record update failed

**Debug**:
```sql
SELECT clientdebt FROM client WHERE clientid = [ID];
```

### 3. **Missing Debt Change Records**
**Issue**: Approval processed but no audit trail  
**Cause**: clientdebtchange insertion failed

**Debug**:
```sql
SELECT * FROM clientdebtchange 
WHERE tablename = 'FaidaController.php' 
AND clientid = [ID];
```

---

## 🧪 Testing Scenarios

### Test Case 1: Normal Approval Flow
```
1. Create test Faida application
2. Access director interface
3. Select application for approval
4. Add approval comment
5. Submit approval
6. Verify customer debt increased
7. Verify debt change record created
```

### Test Case 2: Rejection Flow
```
1. Create test Faida application
2. Access director interface  
3. Select application for rejection
4. Add rejection reason
5. Submit rejection
6. Verify Faida marked as rejected
7. Verify customer debt unchanged
```

### Test Case 3: Error Handling
```
1. Submit approval with invalid Faida ID
2. Verify error page displayed
3. Submit with missing comment
4. Test database connection failure
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `faidadirector(faidaId)`
   - `faida(conditions, clientId)`
   - `client(clientid)`
   - `clientdebtchange(clientid)`

2. **Query Optimization**:
   - Use prepared statements for user inputs
   - Minimize database calls in loops
   - Efficient JOIN operations

3. **Memory Management**:
   - Clean up large result sets
   - Avoid loading unnecessary data

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [FaidaController.md](FaidaController.md) - Main profit transaction controller
- [clientController.php](#) - Customer management
- [Database Schema Documentation](#) - Table relationships

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur