# Bank Controller Documentation

**File**: `/controllers/bankController.php`  
**Purpose**: Manages bank master data and bank institution information  
**Last Updated**: December 19, 2024  
**Total Functions**: 8  
**Lines of Code**: 519

---

## 📋 Overview

The Bank Controller manages bank institution master data in the ERP system. It handles:
- Bank institution creation and management
- Bank information and details maintenance
- Bank status management (active/inactive)
- Bank deletion with safety checks
- Integration with bank account management
- Chart of accounts integration for bank accounts
- Multi-language support for bank operations
- API support for external integrations
- Bulk operations on multiple banks
- Bank listing and search functionality

### Primary Functions
- [x] Create new bank institutions
- [x] Manage bank information and details
- [x] Handle bank status (active/inactive/deleted)
- [x] Delete banks with relationship validation
- [x] Edit and update bank information
- [x] Bulk operations (hide/show/delete multiple banks)
- [x] Integration with chart of accounts
- [x] API support for CURL operations
- [x] Multi-language interface support
- [x] Bank listing with ordering

### Related Controllers
- [bankaccountController.php](#) - Bank account management
- [accountstree.php](accountstree.md) - Chart of accounts integration
- [saveController.php](saveController.md) - Cash management
- [dailyentry.php](dailyentry.md) - Bank transaction entries
- [expensesController.php](expensesController.md) - Bank expense payments

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **bank** | Bank institutions master | bankid, bankname, bankdate, conditions, userid, webApiId |

### Integration Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **bankaccount** | Bank accounts | bankaccount.bankid references bank.bankid |
| **accountstree** | Chart of accounts | Auto-created bank account elements |
| **accountmovement** | Bank account movements | Bank transaction history |

### Support Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **user** | User management | bank.userid references user.userid |
| **youtubelink** | Help videos | Training and help materials |

---

## 🔧 Key Functions

### 1. Main Display (Default Action)
**Purpose**: Display bank creation form  
**Line**: 96

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Authentication  │───▶│ Set Breadcrumb   │───▶│ Display Add     │
│ Check           │    │ Navigation       │    │ Form            │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**UI Elements**:
- Bank name input field
- Bank details text area
- API ID field for external integration

### 2. add()
**Purpose**: Create new bank institution  
**Line**: 311

**Parameters** (via $_POST):
- `bankname` - Bank institution name
- `bankdetails` - Additional bank details/description
- `webApiId` - External API integration ID

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Collect Form    │───▶│ Set Default      │───▶│ Insert Bank     │
│ Data            │    │ Values           │    │ Record          │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Default Values Set**:
```php
$myBank->bankdate = date("Y-m-d");        // Current date
$myBank->conditions = 0;                   // Active status
$myBank->userid = $_SESSION["userid"];     // Current user
```

### 3. show()
**Purpose**: Display bank listing  
**Line**: 333

**Features**:
- Ordered bank listing
- Status-based filtering
- Integration with YouTube help links

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Bank Data  │───▶│ Apply Ordering   │───▶│ Display Bank    │
│ with Status     │    │ and Filtering    │    │ Listing         │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### 4. delete($bankId)
**Purpose**: Permanently delete bank with safety validation  
**Line**: 343

**Safety Checks**:
1. Validates bank ID exists
2. Checks for related bank accounts
3. Only deletes if no dependent records

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Bank       │───▶│ Check Bank       │───▶│ Delete or       │
│ Record          │    │ Accounts         │    │ Return Error    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Delete Chart    │    │ Return Error     │    │ Success         │
│ Account Element │    │ Message          │    │ Response        │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Return Codes**:
- **0**: Success - Bank deleted
- **1**: Cannot delete - Has related bank accounts
- **2**: Error - Database or validation error

**Critical Safety Logic**:
```php
$bankaccountData = $myBankaccountRecord->queryByBankid($bankId);
if (count($bankaccountData) <= 0) {
    // Safe to delete
    $myBankRecord->delete($bankId);
    delTreeElement($rowDelData->bankname);  // Remove from chart of accounts
} else {
    // Cannot delete - has dependent bank accounts
    $bankdeleteValid = 1;
}
```

### 5. deletetemp($bankId)
**Purpose**: Soft delete (hide) bank institution  
**Line**: 377

**Process**:
- Sets `conditions = 1` (hidden status)
- Preserves all data and relationships
- Can be reversed with returndelete()

### 6. returndelete($bankId)
**Purpose**: Restore soft-deleted (hidden) bank institution  
**Line**: 405

**Process**:
- Sets `conditions = 0` (active status)
- Makes bank visible again in listings

### 7. edit()
**Purpose**: Load bank data for editing  
**Line**: 433

**Returns**: Bank record object for editing form

### 8. update()
**Purpose**: Update existing bank institution  
**Line**: 445

**Parameters** (via $_POST):
- `bankname` - Updated bank name
- `bankdetails` - Updated bank details
- `conditions` - Status (0=active, 1=hidden)
- `bankid` - Bank ID to update
- `bankdate` - Bank creation/update date

**Process**: Updates bank record with new information

### 9. executeOperation()
**Purpose**: Perform bulk operations on multiple banks  
**Line**: 470

**Supported Operations**:
- **Operation 1**: Bulk soft delete (hide multiple banks)
- **Operation 2**: Bulk restore (show multiple banks)
- **Operation 3**: Bulk permanent delete (with safety checks)

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Get Selected    │───▶│ Loop Through     │───▶│ Apply Operation │
│ Bank IDs        │    │ Each Bank        │    │ Based on Type   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Collect Results │    │ Handle Errors    │    │ Display Summary │
│ for Each Bank   │    │ for Each Bank    │    │ Message         │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

---

## 🔄 Business Logic Flow

### Bank Creation Workflow
```
User Input
    │
    ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Form Validation │───▶│ Set System       │───▶│ Database        │
│ (Client Side)   │    │ Defaults         │    │ Insert          │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                │                       │
                                ▼                       ▼
                    ┌──────────────────┐    ┌─────────────────┐
                    │ Chart Accounts   │    │ Success/Error   │
                    │ Integration      │    │ Response        │
                    └──────────────────┘    └─────────────────┘
```

### Bank Deletion Safety Logic
```
Delete Request
    │
    ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Bank       │───▶│ Check Bank       │───▶│ Count > 0?      │
│ Information     │    │ Accounts         │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                          │
                            Yes ┌─────────────────────────┼─────────────────┐ No
                                ▼                         ▼                 ▼
                    ┌──────────────────┐    ┌─────────────────┐ ┌─────────────────┐
                    │ Return Error:    │    │ Proceed with    │ │ Success: Bank   │
                    │ Cannot Delete    │    │ Deletion        │ │ Deleted         │
                    └──────────────────┘    └─────────────────┘ └─────────────────┘
```

### Status Management
Banks have three states:
- **Active** (conditions = 0): Visible and usable
- **Hidden** (conditions = 1): Hidden but data preserved
- **Deleted**: Permanently removed (only if no dependencies)

---

## ⚠️ Common Issues

### 1. Cannot Delete Bank with Accounts
**Issue**: Attempting to delete bank that has bank accounts  
**Error Message**: "لا يمكن حذف هذا البنك الا بعد حذف كل البيانات المرتبطه به"  
**Solution**: Delete all bank accounts first, then delete the bank

### 2. Chart of Accounts Sync Issues
**Issue**: Bank name changes not reflected in chart of accounts  
**Note**: Current implementation doesn't sync bank name updates to chart of accounts
**Recommendation**: Add chart of accounts update in update() function

### 3. API Integration Conflicts
**Issue**: webApiId conflicts for external integrations  
**Prevention**: Validate unique webApiId values

### 4. Bulk Operation Partial Failures
**Issue**: Some banks in bulk operation succeed, others fail  
**Handling**: System provides detailed results for each bank operation

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/authentication.php` - Security
- `../public/include_dao.php` - Database layer
- `dailyentryfun.php` - Journal entry utilities
- `initiateStaticSessionCommingWithCurl.php` - API session
- `../library/breadcrumb.php` - Navigation breadcrumbs

### Critical DAOs
- `BankDAO` - Bank master data operations
- `BankaccountDAO` - Bank account relationship checks
- `AccountstreeDAO` - Chart of accounts integration

### JavaScript Integration
- Form validation (customValidation flag)
- Bulk operations interface (customBank flag)
- Checkbox selection for bulk operations (customCheck flag)

---

## 🎯 Bank Institution Management

### Bank Master Data Structure
```
Bank Institution
├── Basic Information
│   ├── Bank Name (required)
│   ├── Bank Details (optional)
│   └── Creation Date (auto-set)
├── Status Management
│   ├── Active (conditions = 0)
│   ├── Hidden (conditions = 1)
│   └── Deleted (permanent removal)
├── Integration
│   ├── Web API ID (external systems)
│   └── Chart of Accounts Element
└── Relationships
    └── Bank Accounts (one-to-many)
```

### Standard Bank Types
Common bank institutions include:
- Commercial banks
- Central banks
- Investment banks
- Credit unions
- Online banks
- International banks

---

## 🎲 Best Practices

### 1. Bank Creation
- Use descriptive, standardized bank names
- Include relevant details for identification
- Set appropriate API IDs for external integration

### 2. Status Management
- Use soft delete (hide) for temporary deactivation
- Only use permanent delete when absolutely necessary
- Always check dependencies before deletion

### 3. Bulk Operations
- Review selected items before bulk operations
- Monitor operation results for partial failures
- Use bulk operations for efficiency with large datasets

### 4. Integration Management
- Coordinate bank changes with bank account teams
- Ensure chart of accounts consistency
- Validate API integrations after changes

---

## 🔄 API Support

### CURL Integration
The controller supports API operations via CURL posts:

```php
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    // API response format
    $data = array(
        'status' => 1,  // 1=success, 2=error
        'message' => 'تمت العمليه بنجاح',
        'message_en' => 'Success'
    );
    echo json_encode($data);
}
```

**API Actions Supported**:
- Add bank institution
- Update bank institution
- Delete bank institution
- Bulk operations

### External API Integration
- `webApiId` field supports external system integration
- Enables synchronization with external banking systems
- Facilitates data exchange with third-party applications

---

## 📋 Relationship Dependencies

### Parent-Child Relationships
```
Bank (Parent)
    └── Bank Accounts (Children)
            └── Account Movements (Grandchildren)
                    └── Journal Entries (Great-grandchildren)
```

**Deletion Cascade Rules**:
- Cannot delete bank if bank accounts exist
- Must delete in reverse dependency order
- Chart of accounts elements cleaned up automatically

---

**Critical Note**: This controller manages bank institution master data only. Actual bank account management, transactions, and balances are handled by separate controllers (bankaccountController, etc.). Changes to bank institutions should be coordinated with bank account operations to maintain data integrity.