# Project Client Management Controller Documentation

**File**: `/controllers/projectclientsController.php`  
**Purpose**: Manage web client access to project data and mobile application integration  
**Last Updated**: 2024-12-20

---

## 📋 Overview

### Primary Functions
- [x] Web client creation and management
- [x] Project-client relationship mapping
- [x] Mobile app user authentication
- [x] Client access control
- [x] Ajax-based data operations

### Related Controllers
- [projectController.php](projectController.md) - Project master data
- [clientController.php](#) - Client master management

---

## 🗄️ Database Tables

### Primary Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| webclients | Web/mobile client users | id, name, mobile, user_name, password, clientids |
| webclientprojects | Client-project relationships | webclientid, clientid, projectid |
| project | Project master data | id, name, clientid |
| client | Customer master data | clientid, clientname |

### Secondary Tables (Referenced)
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| user | System users | Foreign Key: webclients.adduserid |

---

## 🔧 Key Functions

### 1. savedata()
**Purpose**: Create or update web client with project access  
**Called By**: AJAX POST to `?do=savedata`  
**Parameters**:
- `$name` (string) - Client display name
- `$mobile` (string) - Mobile phone number
- `$user_name` (string) - Login username
- `$password` (string) - Login password
- `$clientids` (array) - Associated client IDs
- `$webclientidold` (int) - Existing ID for updates

**Returns**: JSON response (1 = success, 0 = error)

**Database Operations**:
- INSERT/UPDATE `webclients`
- DELETE from `webclientprojects` (for updates)
- INSERT into `webclientprojects`
- File upload for client image

**Business Logic**:
1. **Create New Client**:
   ```php
   $projectclients = R::dispense('webclients');
   $projectclients->del = 0;
   $projectclients->addtoday = $today;
   ```

2. **Update Existing Client**:
   ```php
   $projectclients = R::load('webclients',$webclientidold);
   $projectclients->del = 1;
   $projectclients->updatetoday = $today;
   ```

3. **Project-Client Mapping**:
   ```php
   for ($i=0; $i <= count($clientids); $i++) { 
       $project = R::findOne('project', 'clientid = ? ',[$clientids[$i]]);
       $webclientprojects = R::dispense('webclientprojects');
       $webclientprojects->webclientid = $webclientid;
       $webclientprojects->clientid = $clientids[$i];
       $webclientprojects->projectid = $project->id;
       R::store($webclientprojects);
   }
   ```

### 2. showajax()
**Purpose**: DataTables-compatible AJAX data source  
**Called By**: AJAX POST to `?do=showajax`  
**Parameters**:
- `$start_date` (string) - Filter start date
- `$end_date` (string) - Filter end date
- `$del` (string) - Deletion status filter
- `$data1`, `$data2`, `$data3` - Additional filters
- DataTables pagination/search parameters

**Returns**: JSON DataTables response

**Database Operations**:
- Complex SELECT with JOINs for web client data
- COUNT query for total records
- Dynamic filtering based on parameters

**Business Logic**:
1. **Build Dynamic Query**:
   ```php
   $searchQuery = " ";
   if($data1 != '') {
       $searchQuery .= " and webclients.id = ".$data1;
   }
   if($start_date != '' && $end_date != '') {
       $searchQuery .= 'and webclients.addtoday >= "'.$start_date.'" 
                        and webclients.addtoday <= "'.$end_date.'"';
   }
   ```

2. **Format Output**:
   ```php
   foreach ($rResult as $row) {
       $clients = R::getAll('SELECT client.* FROM client 
                           LEFT JOIN webclientprojects ON client.clientid = webclientprojects.clientid 
                           WHERE webclientprojects.webclientid = ?',[$row["id"]]);
       $clientname = '';
       foreach ($clients as $value) {
           $clientname .= $value['clientname'] . ' / ';
       }
   }
   ```

### 3. removecontroller()
**Purpose**: Soft delete web client  
**Called By**: AJAX POST to `?do=removecontroller`  
**Parameters**:
- `$id` (int) - Web client ID

**Returns**: JSON response (1 = success, 0 = error)

**Database Operations**:
- UPDATE `webclients` SET del = 2
- UPDATE related tables with deletion status

**Business Logic**:
1. Mark client as deleted
2. Update deletion timestamp and user
3. Cascade deletion to related records

---

## 📊 Main Workflows

### Workflow 1: Web Client Creation
```
1. User fills client form
   ↓
2. Select associated projects
   ↓
3. Upload client image
   ↓
4. Submit via AJAX
   ↓
5. Create webclient record
   ↓
6. Map to projects
   ↓
7. Return success status
```

**Files Involved**:
- View: `/views/default/projectclientsview/add.html`
- Upload: `/views/default/images/webclients/`

### Workflow 2: Client Data Display
```
1. Load DataTables interface
   ↓
2. AJAX request with filters
   ↓
3. Build dynamic SQL query
   ↓
4. Execute with pagination
   ↓
5. Format client data
   ↓
6. Return JSON response
   ↓
7. Render in DataTables
```

### Workflow 3: Client-Project Relationship
```
1. Select client IDs array
   ↓
2. For each client ID:
   ├── Find associated project
   ├── Create relationship record
   └── Link webclient to project
   ↓
3. Handle relationship updates
   ↓
4. Remove old relationships
   ↓
5. Add new relationships
```

---

## 🔗 File Dependencies

### Includes
```php
include("../public/impOpreation.php");
include("../library/uploadImages.php");
```

### Image Processing
- Upload to `/views/default/images/webclients/`
- Resize to 300x300 pixels
- Support for multiple formats

### Related Views
- `/views/default/projectclientsview/add.html` - Creation form
- `/views/default/projectclientsview/show.html` - Client listing with DataTables
- `/views/default/projectclientsview/edit.html` - Edit form

### JavaScript Dependencies
- DataTables for client listing
- AJAX for form submissions
- Image preview functionality

---

## 🎯 URL Routes & Actions

| Action (`?do=`) | Method | Description | View Template |
|-----------------|--------|-------------|---------------|
| (empty) | GET | Display creation form | add.html |
| show | GET | Display client listing | show.html |
| edit | GET | Display edit form | edit.html |
| savedata | POST | Create/update client (AJAX) | JSON response |
| showajax | POST | DataTables data source (AJAX) | JSON response |
| removecontroller | POST | Delete client (AJAX) | JSON response |

---

## ⚠️ Known Issues & Fixes

### Issue 1: Wrong Table Reference in Delete (Line 272)
**Problem**: Function loads 'students' table instead of 'webclients'  
**Cause**: Copy-paste error from student controller  
**Fix**: Change to `R::load('webclients',$id)`  
**File**: Line 272

### Issue 2: Student-specific Updates in Delete (Lines 278-281)
**Problem**: Updates student-related tables instead of webclient tables  
**Cause**: Copy-paste error  
**Fix**: Remove or replace with appropriate webclient operations  
**File**: Lines 278-281

### Issue 3: Inconsistent Project Session Filter (Lines 14, 24, 43)
**Problem**: Some queries check `$_SESSION['projectids']`, others don't  
**Cause**: Inconsistent permission implementation  
**Fix**: Standardize session-based filtering  
**File**: Multiple locations

### Issue 4: Image File Management
**Problem**: Old files not properly cleaned up on updates  
**Cause**: Manual file deletion without existence check  
**Fix**: Add file existence validation before `unlink()`  
**File**: Line 95

---

## 🔐 Permissions & Security

### Required Permissions
- Web client management access
- Project viewing permissions

### Security Checks
```php
include_once("../public/authentication.php");
```

### Session-based Filtering
```php
if( $_SESSION['projectids'] != 0){
    $search_params = ' AND project.id in (' . $_SESSION['projectids'] . ')';
}
```

### Input Validation
- All POST data filtered with `filter_input()`
- File upload validation through upload library
- AJAX endpoint protection

---

## 📱 Mobile App Integration

### Authentication Fields
- `user_name` - Mobile app login username
- `password` - Mobile app login password
- `device_id` - Device identification
- `is_active` - Account status

### Project Access Control
```php
if (in_array("0", $clientids)) {
    $projectclients->clientids = '0'; // All projects access
} else {
    $projectclients->clientids = '-1,'.implode(",", $clientids); // Specific projects
}
```

### File Sharing
- `filepdf` - Shared documents/contracts
- `showpdf` - PDF visibility flag
- Image upload for client identification

---

## 📝 Notes

### Important Considerations
- Web clients are different from system clients
- Each web client can access multiple projects
- Image uploads are resized to standard dimensions
- Soft deletion preserves audit trail

### Database Relationships
```
webclients (1) → (M) webclientprojects (M) ← (1) project
webclients (1) → (M) webclientprojects (M) ← (1) client
```

### Future Improvements
- [ ] Add bulk client operations
- [ ] Implement client activity tracking
- [ ] Add API token authentication
- [ ] Enhance mobile app features
- [ ] Add client notification system

---

## 📚 Related Documentation
- [Project Master](projectController.md)
- [Client Management](../client/clientController.md)
- [Mobile API Documentation](../api/mobile.md)
- [File Upload Library](../libraries/uploadImages.md)