# Branches Controller Documentation

**File**: `/controllers/branchesController.php`  
**Purpose**: Manages company branches/locations, branch settings, and branch-related operations  
**Last Updated**: December 19, 2024  
**Total Functions**: 6  
**Lines of Code**: 262

---

## 📋 Overview

The Branches Controller manages the company's physical branches and locations in the ERP system. It handles:
- Creating and managing company branches/locations
- Branch contact information and settings
- Branch logo/image management
- Branch status management (active/inactive)
- Multi-language branch names (Arabic/English)
- Branch taxation numbers and addresses

### Primary Functions
- [x] Add new company branches
- [x] View all branches in listing format
- [x] Edit existing branch information
- [x] Update branch details
- [x] Delete branches from system
- [x] Toggle branch active/inactive status
- [x] Branch logo upload and management
- [x] Print branch details

### Related Controllers
- [programsettingsController.md](programsettingsController.md) - Company settings
- [userController.md](userController.md) - User management per branch
- [storeController.md](storeController.md) - Warehouses per branch
- [sellbillController.md](sellbillController.md) - Sales operations per branch
- [buyBillController.md](buyBillController.md) - Purchase operations per branch
- [clientController.md](clientController.md) - Customer management per branch
- [supplierController.md](supplierController.md) - Supplier management per branch
- [employeeController.md](employeeController.md) - Employee management per branch
- [saveController.md](saveController.md) - Cash registers per branch
- [dailyentry.md](dailyentry.md) - Accounting entries per branch

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **branch** | Branch master data | branchId, branchName, nameEn, phone, mobile, email, branchAddress, addressEn, branchTaxNo, logo, status, createdAt, updatedAt |

### Reference Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **youtubelink** | Associated video content | Referenced for branch marketing |
| **user** | Branch employees | Users assigned to specific branches |
| **store** | Branch warehouses | Each store belongs to a branch |
| **buybill** | Purchase operations | buybill.branchid references branch |
| **sellbill** | Sales operations | sellbill.branchid references branch |

### File Storage
| Directory | Purpose | File Types |
|-----------|---------|------------|
| **../views/default/images/branch_image** | Branch logos | JPG, PNG, GIF (250x250 px) |

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Create a new company branch with all details  
**Called By**: Form submission with `?do=add`  
**Line**: 145

**Parameters** (via $_POST):
- `branchname` (string) - Branch name in Arabic
- `nameEn` (string) - Branch name in English
- `phone` (string) - Branch telephone number
- `mobile` (string) - Branch mobile number
- `email` (string) - Branch email address
- `branchNo` (string) - Branch identification number
- `branchAddress` (string) - Branch address in Arabic
- `addressEn` (string) - Branch address in English
- `message` (text) - Branch description/notes
- `branchTaxNo` (string) - Branch tax identification number
- `status` (int) - Branch status (1=active, 0=inactive)
- `logo` (file) - Branch logo image file

**Process Flow**:
```
Form Data Collection
         ↓
Image Upload Processing (250x250px)
         ↓
Branch Object Creation
         ↓
Database Insert
         ↓
Redirect to Success
```

**Business Logic**:
1. Collects all branch information from form
2. Sets automatic dates (branchDate, createdAt, updatedAt)
3. Processes logo upload using uploadImages() with 250x250 resize
4. Creates Branch DTO object with all data
5. Inserts into database via BranchDAO

### 2. show()
**Purpose**: Display all branches in system listing  
**Called By**: Navigation to `?do=show`  
**Line**: 183

**Return Value**: Array of all branch objects

**Process Flow**:
```
Database Query (queryAll)
         ↓
Return Branch Array
         ↓
Template Assignment
         ↓
Display Branch List
```

**Business Logic**:
1. Queries all branches from database
2. Returns complete branch data array
3. Used by template to display branch listing

### 3. edit()
**Purpose**: Load branch data for editing form  
**Called By**: Edit link with `?do=edit&id=X`  
**Line**: 192

**Parameters** (via $_GET):
- `id` (int) - Branch ID to edit

**Return Value**: Branch object with all data

**Process Flow**:
```
Get Branch ID from URL
         ↓
Load Branch from Database
         ↓
Return Branch Object
         ↓
Populate Edit Form
```

### 4. update()
**Purpose**: Update existing branch information  
**Called By**: Form submission with `?do=update`  
**Line**: 202

**Parameters** (via $_POST):
- `branchid` (int) - Branch ID to update
- All same parameters as add() function

**Process Flow**:
```
Load Existing Branch
         ↓
Collect Form Data
         ↓
Process Image Update
         ↓
Update Branch Object
         ↓
Database Update
         ↓
Redirect to Success
```

**Business Logic**:
1. Loads existing branch to preserve original creation date
2. Updates all modifiable fields
3. Handles logo image update or keeps existing
4. Uses updateImages() for image management
5. Updates updatedAt timestamp automatically

### 5. delete()
**Purpose**: Remove branch from system  
**Called By**: Delete action with `?do=delete&id=X`  
**Line**: 243

**Parameters** (via $_GET):
- `id` (int) - Branch ID to delete

**Process Flow**:
```
Get Branch ID
         ↓
Database Delete
         ↓
Redirect to Success
```

**Business Logic**:
1. Hard deletes branch record from database
2. Note: Should check for dependencies before deletion

### 6. toggleStatus()
**Purpose**: Toggle branch active/inactive status  
**Called By**: Status toggle with `?do=toggleStatus&id=X`  
**Line**: 251

**Parameters** (via $_GET):
- `id` (int) - Branch ID to toggle

**Process Flow**:
```
Load Branch Record
         ↓
Toggle Status (0↔1)
         ↓
Update Database
         ↓
Redirect to Success
```

**Business Logic**:
1. Loads current branch record
2. Toggles status: 1→0 or 0→1
3. Updates record in database
4. Enables/disables branch for operations

---

## 🔄 Business Logic Flow

### Branch Creation Workflow
```
User Form Entry
       ↓
┌─────────────────┐
│ Validate Data   │
│ - Name required │
│ - Email format  │ 
│ - Phone format  │
└─────────────────┘
       ↓
┌─────────────────┐
│ Process Logo    │
│ - Upload file   │
│ - Resize 250px  │
│ - Save to disk  │
└─────────────────┘
       ↓
┌─────────────────┐
│ Create Branch   │
│ - Set dates     │
│ - Set status    │
│ - Insert DB     │
└─────────────────┘
       ↓
Success/Error Redirect
```

### Branch Status Management
```
Branch Status Toggle Request
            ↓
┌──────────────────────────┐
│ Load Current Branch      │
│ - Get current status     │
│ - Validate permissions   │
└──────────────────────────┘
            ↓
┌──────────────────────────┐
│ Toggle Status            │
│ - 1 (active) → 0 (off)   │
│ - 0 (inactive) → 1 (on)  │
└──────────────────────────┘
            ↓
┌──────────────────────────┐
│ Update Database          │
│ - Save new status        │
│ - Trigger side effects   │
└──────────────────────────┘
            ↓
Status Updated Successfully
```

---

## ⚠️ Common Issues

### 1. **Image Upload Failures**
**Symptoms**: Logo not displaying after upload  
**Causes**: 
- Directory permissions on ../views/default/images/branch_image
- File size too large
- Invalid image format

**Solutions**:
- Ensure directory is writable (755 permissions)
- Check file size limits in PHP config
- Validate image format before upload

### 2. **Branch Deletion Dependencies**
**Symptoms**: Foreign key constraint errors  
**Causes**: Branch has related records in other tables

**Solutions**:
- Check for users assigned to branch
- Check for stores under branch
- Check for bills/transactions for branch
- Implement soft delete instead of hard delete

### 3. **Status Toggle Not Working**
**Symptoms**: Branch status doesn't change  
**Causes**: 
- Missing permissions
- Database connection issues
- Caching issues

**Solutions**:
- Verify user has branch management permissions
- Check database connectivity
- Clear application cache

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations and session management
- `../public/config.php` - Database and system configuration
- `../public/include_dao.php` - Data Access Object includes
- `../library/uploadImages.php` - Image upload and processing utilities

### Required DAOs
- `BranchDAO.class.php` - Branch data access interface
- `Branch.class.php` - Branch data transfer object
- `BranchMySqlDAO.class.php` - MySQL implementation for branch operations
- `BranchMySqlExtDAO.class.php` - Extended branch operations
- `YoutubeLinkDAO.class.php` - YouTube link management
- `YoutubeLink.class.php` - YouTube link DTO
- `YoutubeLinkMySqlDAO.class.php` - YouTube link MySQL operations
- `YoutubeLinkMySqlExtDAO.class.php` - Extended YouTube operations

### Template Files
- `branchesview/add.html` - Branch creation form
- `branchesview/show.html` - Branch listing display
- `branchesview/edit.html` - Branch editing form
- `branchesview/editprint.html` - Printable branch details
- `header.html` - Standard page header
- `footer.html` - Standard page footer
- `succes.html` - Success message template
- `error.html` - Error message template

### Image Upload Configuration
- **Target Directory**: `../views/default/images/branch_image`
- **Image Dimensions**: 250x250 pixels (automatically resized)
- **Supported Formats**: JPG, PNG, GIF
- **Upload Class**: Uses custom upload class from uploadImages.php

---

## 🎯 Integration Points

### Multi-Branch Operations
Many other controllers reference branch data:
- Sales operations filter by branch
- Purchase operations assign to branch
- User management assigns users to branches
- Warehouse/store management per branch
- Financial reporting per branch

### Security Considerations
- Authentication required for all operations
- File upload validation needed
- Input sanitization for all form fields
- Permission checks for branch management

### Performance Notes
- Branch data frequently cached due to frequent lookups
- Logo images should be optimized for web display
- Status checks impact user interface availability