# Client Controller Documentation

**File**: `/controllers/clientController.php`  
**Purpose**: Complete customer lifecycle management including creation, editing, deletion, and Excel import functionality  
**Last Updated**: December 20, 2024  
**Total Functions**: 12  
**Lines of Code**: ~1,822

---

## 📋 Overview

The Client Controller is the primary customer management module that handles all customer-related operations in the ERP system. It provides comprehensive functionality for customer creation, modification, deletion, and bulk import operations. The controller integrates with:
- Customer debt management
- Daily entry accounting system  
- Store and product associations
- Government and area classifications
- Customer type categorization
- Online store integration
- Excel import/export capabilities
- Supplier linkage for special operations

### Primary Functions
- [x] Customer creation with full profile details
- [x] Customer editing and updates
- [x] Customer deletion (soft delete)
- [x] Excel bulk import functionality
- [x] Customer listing and search
- [x] Debt balance initialization
- [x] Accounting integration (daily entries)
- [x] Geographic classification (government/area)
- [x] Customer type categorization
- [x] Special customer features (RFID, discounts, credit limits)
- [x] Online store synchronization
- [x] Supplier linking operations

### Related Controllers
- [clientdebt.php](clientdebt.md) - Customer debt tracking
- [clientReportsController.php](clientReportsController.md) - Customer reports
- [clientPayedDeptController.php](clientPayedDeptController.md) - Payment processing
- [sellbillController.php](sellbillController.md) - Sales operations
- [dailyentry.php](#) - Accounting entries

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer master data | clientid, clientname, clientaddress, clientphone, clientmobile, clientdebt, clientareaid, delegateid, typeClientid, conditions |
| **clientdebtchange** | Customer debt transaction log | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype, clientdebtchangedate, tablename |
| **clientdetails** | Extended customer information | clientdetailsid, noOfPersonsTamween, noOfPersonsDa3m, cardNum, cardPassword, specialDiscount |

### Accounting Tables  
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **dailyentry** | Journal entries | dailyentryid, dailyentryserial, dailyentrydate, dailyentrytotalamount, dailyentrydescription |
| **dailyentrycreditor** | Credit side entries | dailyentrycreditorid, dailyentryid, accountstreeid, dailyentrycreditoramount |
| **dailyentrydebtor** | Debit side entries | dailyentrydebtoryid, dailyentryid, accountstreeid, dailyentrydebtorramount |
| **accountstree** | Chart of accounts | accountstreeid, accountstreecode, accountstreename, accountstreetype |

### Classification Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **clientarea** | Customer areas/regions | id, name, description |
| **government** | Government/state data | governmentid, governmentname |
| **goverarea** | Government sub-areas | goverareaid, governmentid, goverareaname |
| **typeclient** | Customer types | typeclientid, typeclientname, typeclientdiscount |

### Configuration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **store** | Store locations | storeid, storename, storecode |
| **user** | System users/delegates | userid, username, employeename, usergroupid |
| **associatedtags** | Customer tags | associatedtagid, associatedtagname, conditions |
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |
| **programsettings** | System settings | programsettingsid, settingkey, settingvalue |

### Online Store Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **eclientsetting** | E-commerce customer settings | eclientsettingid, emailnotifications, smsnotifications, callingcustomer |
| **esaudiclientsetting** | Saudi-specific e-commerce settings | esaudiclientsettingid, identityNumber, companyNumber, vatNumber |
| **onlinestoremainsetting** | Main online store configuration | onlinestoremainsettingid, isactive, domain |
| **tamweenclientdetail** | Social support program details | tamweenclientdetailid, clientid, cardNum, cardPassword |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Customer Form
**Location**: Line 190-237  
**Purpose**: Display customer creation form with all required dropdown data

**Process Flow**:
1. Check user authentication
2. Load reference data:
   - All government locations
   - All store locations
   - Customer types
   - Customer areas
   - User delegates
   - Associated tags
3. Calculate next customer ID
4. Display add form template

**Template Variables**:
- `$allGovernment` - Government dropdown options
- `$stores` - Store assignment options
- `$typeClient` - Customer type options  
- `$allDelegate` - Delegate assignment options
- `$allclientarea` - Area classification options
- `$allTags` - Available customer tags
- `$nextId` - Auto-generated next customer ID

---

### 2. **add()** - Create New Customer
**Location**: Line 632-941  
**Purpose**: Process customer creation with full validation and accounting integration

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

**Input Processing**:
```php
$clientname = $_POST["txtName"];
$clientaddress = $_POST["txtAddress"];
$clientphone = $_POST["txtPhone"];
$clientmobile = $_POST["txtMobile"];
$clientdebt = (float) $_POST["txtDebt"];
$clientareaid = (int) $_POST["clientareaid"];
$clientcode = $_POST["clientcode"];
$debtLimit = $_POST["debtLimit"];
```

**Validation Checks**:
1. **Name Uniqueness**: Prevents duplicate customer names
2. **Required Fields**: Validates essential customer information
3. **Debt Limit**: Ensures proper credit limit settings
4. **Type Classification**: Validates customer type assignments

**Process Flow**:
1. Extract and validate POST data
2. Check for existing customer with same name
3. Create new client record
4. Process extended customer details
5. Handle online store settings (if enabled)
6. Create initial debt balance entry (if non-zero)
7. Generate accounting entries for debt
8. Process store assignments
9. Handle customer type assignments
10. Process special features (RFID, discounts)

**Accounting Integration**:
```php
// Create debt balance entry
if ($clientdebt != 0) {
    $clientDeptChange->clientid = $newClientid;
    $clientDeptChange->clientdebtchangeamount = $clientdebt;
    $clientDeptChange->clientdebtchangetype = 0; // Debt increase
    $clientDeptChange->tablename = 'clientController.php';
    $clientDeptChangeDAO->save($clientDeptChange);
}
```

**Return Values**:
- `Positive Integer` - Success (new client ID)
- `-1` - Error: Duplicate client name
- `-2` - Error: Missing required fields

---

### 3. **addFromExcel()** - Bulk Import from Excel
**Location**: Line 942-1187  
**Purpose**: Import multiple customers from Excel spreadsheet with validation

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

**Supported File Formats**:
- Excel 2007+ (.xlsx)
- Excel 97-2003 (.xls)  
- CSV files

**Excel Column Mapping**:
| Column | Field | Validation |
|--------|-------|------------|
| A | Customer Name | Required, unique check |
| B | Phone | Optional |
| C | Mobile | Optional |
| D | Address | Optional |
| E | Customer Area ID | Must exist in clientarea table |
| F | Initial Debt | Numeric, default 0 |
| G | Customer Code | Optional, unique |

**Process Flow**:
1. Validate uploaded file format
2. Load Excel data using PHPExcel
3. For each row:
   - Extract customer data
   - Validate required fields
   - Check name uniqueness
   - Create customer record
   - Handle debt initialization
   - Generate accounting entries
4. Track success/failure counts
5. Generate import summary

**Error Handling**:
```php
try {
    $objPHPExcel = PHPExcel_IOFactory::load($uploadPath);
    $worksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $worksheet->getHighestRow();
    
    for ($row = 2; $row <= $highestRow; ++$row) {
        // Process each customer row
    }
} catch (Exception $e) {
    // Handle file processing errors
}
```

---

### 4. **show()** - Customer Listing
**Location**: Line 1188-1240  
**Purpose**: Display paginated list of customers with search capabilities

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

**Features**:
- Pagination support
- Search by name, phone, address
- Sort by various columns
- Customer type filtering
- Area-based filtering
- Active/inactive status filtering

---

### 5. **edit()** - Customer Modification
**Location**: Line 1401+  
**Purpose**: Load customer data for editing and process updates

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

**Process Flow**:
1. Load existing customer data
2. Load related information (areas, types, etc.)
3. Pre-populate edit form
4. Process update submission
5. Handle related record updates
6. Update accounting entries if debt changed

---

### 6. **tempdelete()** - Soft Delete Customer  
**Location**: Line 1357-1378  
**Purpose**: Deactivate customer without removing historical data

**Function Signature**:
```php
function tempdelete($clientid)
```

**Process**:
```php
$client = $clientDAO->load($clientid);
$client->conditions = 1; // Mark as deleted
$clientDAO->update($client);
```

---

### 7. **returndelete()** - Reactivate Customer
**Location**: Line 1379-1400  
**Purpose**: Restore previously soft-deleted customer

**Function Signature**:
```php
function returndelete($clientid)
```

**Process**:
```php
$client = $clientDAO->load($clientid);
$client->conditions = 0; // Mark as active
$clientDAO->update($client);
```

---

## 🔄 Workflows

### Workflow 1: Customer Creation
```
┌─────────────────────────────────────────────────────────────┐
│                START: New Customer Creation                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Form Dependencies                                  │
│     - Government locations                                   │
│     - Store locations                                        │
│     - Customer types                                         │
│     - Customer areas                                         │
│     - Available delegates                                    │
│     - System tags                                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Customer Form                                   │
│     - Pre-populate dropdowns                                │
│     - Generate next customer ID                             │
│     - Show validation requirements                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Form Submission                                 │
│     - Validate required fields                              │
│     - Check name uniqueness                                 │
│     - Validate business rules                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Create Customer Record                                  │
│     - Insert main client record                             │
│     - Create extended details                               │
│     - Set up online store profile (if enabled)             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Initialize Financial Records                            │
│     IF initial debt > 0:                                    │
│       │                                                     │
│       ├─→ Create debt change record                        │
│       │                                                     │
│       ├─→ Generate daily entry                             │
│       │   ├─ Debit: Customer account                       │
│       │   └─ Credit: Opening balance account               │
│       │                                                     │
│       └─→ Update customer debt balance                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Finalize Creation                                       │
│     - Return success status                                 │
│     - Redirect to success page                              │
│     - Or return customer ID for API calls                   │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Customer creation form |
| `do=add` | `add()` | Process new customer creation |
| `do=addSimpleReturn` | Special AJAX | Simplified customer creation for supplier linking |
| `do=addFromExcel` | `addFromExcel()` | Bulk import from Excel file |
| `do=show` | `show()` | Customer listing with pagination |
| `do=showByType` | `showByType()` | Filter customers by type |
| `do=search` | `search()` | Search customers by criteria |
| `do=edit` | `edit()` | Customer editing form |
| `do=executeOperation` | `executeOperation()` | Process customer updates |
| `do=tempdelete` | `tempdelete()` | Soft delete customer |
| `do=returndelete` | `returndelete()` | Reactivate customer |

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientdebt.php](clientdebt.md) - Customer debt tracking
- [clientReportsController.php](clientReportsController.md) - Customer reporting

---

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