# Project Master Management Controller Documentation

**File**: `/controllers/projectController.php`  
**Purpose**: Complete project lifecycle management - creation, editing, finishing, and deletion  
**Last Updated**: 2024-12-20

---

## 📋 Overview

### Primary Functions
- [x] Project creation with client/cost center integration
- [x] Project editing and timeline management
- [x] Project finishing with financial calculations
- [x] Project deletion with dependency checking
- [x] Project stage management
- [x] Project timeline items management
- [x] Accounting tree integration

### Related Controllers
- [projectKindController.php](projectKindController.md) - Project type management
- [projectoperationController.php](projectoperationController.md) - Material operations
- [projectReportController.php](projectReportController.md) - Project analytics
- [clientController.php](#) - Client management

---

## 🗄️ Database Tables

### Primary Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| project | Master project data | id, name, clientid, costcenterid, treeid, treeproid, totalcontract |
| projectstagechosse | Project stages selection | projectid, projectstageid |
| projecttimetableitems | Timeline/milestones | projectid, clause, amount, startdate, enddate |
| projectstages | Available stages | id, name, is_active |

### Secondary Tables (Referenced)
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| client | Customer data | Foreign Key: project.clientid |
| costcenter | Project cost centers | Foreign Key: project.costcenterid |
| accountstree | Accounting structure | Foreign Key: project.treeid, treeproid |
| projectkind | Project types | Foreign Key: project.projectkindid |
| dailyentry | Financial entries | Foreign Key: project.entryid |

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Create new project with integrated financial setup  
**Called By**: POST action to `?do=add`  
**Parameters**:
- `$txtName` (string) - Project name
- `$txtDebt` (float) - Total contract value
- `$chwckaddclient` (int) - Whether to create client
- `$projectkindid` (int) - Project type
- `$projectstageids` (array) - Selected stages
- `$timetableitemsitr` (int) - Number of timeline items

**Returns**: Redirects to success/error page

**Database Operations**:
- INSERT into `costcenter` - Creates cost center
- INSERT into `client` (optional) - Creates client if requested
- INSERT into `accountstree` - Creates two tree entries (debtor/asset)
- INSERT into `project` - Master project record
- INSERT into `projectstagechosse` - Project stages
- INSERT into `projecttimetableitems` - Timeline items

**Business Logic**:
1. Create cost center for project tracking
2. Optionally create client with accounting tree entry
3. Create accounting tree entries for project (debtor side & asset side)
4. Insert project with all metadata
5. Link selected stages to project
6. Create timeline items with dates and amounts

**Example**:
```php
// Create project with stages and timeline
$_POST['txtName'] = 'New Building Project';
$_POST['txtDebt'] = 100000;
$_POST['projectstageids'] = [1, 2, 3]; // Design, Construction, Completion
add();
```

### 2. update()
**Purpose**: Update existing project information  
**Called By**: POST action to `?do=update`  
**Parameters**:
- `$editid` (int) - Project ID
- Same parameters as add() function

**Returns**: Redirects to success/error page

**Database Operations**:
- UPDATE `costcenter` - Updates cost center name
- UPDATE `client` - Updates client information  
- UPDATE `accountstree` - Updates tree entries
- UPDATE `project` - Updates all project fields
- DELETE/INSERT `projectstagechosse` - Updates stage selections
- UPDATE/INSERT `projecttimetableitems` - Updates timeline

**Business Logic**:
1. Update cost center and client names
2. Update accounting tree entries with new values
3. Update project record with all changes
4. Synchronize stage selections (remove old, add new)
5. Update timeline items (modify existing, add new)

### 3. finishproject($projectid)
**Purpose**: Complete project with financial closure calculations  
**Called By**: GET action to `?do=finish&id=$projectid`  
**Parameters**:
- `$projectid` (int) - Project to finish

**Returns**: Success/error redirect

**Database Operations**:
- UPDATE `project` SET finish = 1
- UPDATE `client` SET conditions = 1 (mark as finished)
- UPDATE `costcenter` SET condation = 1
- INSERT into `dailyentry` - Final accounting entry
- Complex SELECT queries for financial calculations

**Business Logic**:
1. Mark project as finished in all related tables
2. Calculate client payments vs project costs
3. Calculate goods under settlement value
4. Create final accounting entry:
   - FROM: Client account (payments - goods value)
   - FROM: Goods under settlement (full cost)  
   - TO: Sales account (total client payments)

**Accounting Formula**:
```
Client Account = Client Payments - Project Costs
Sales = Client Payments
Goods Under Settlement = Project Material Costs
```

### 4. deleteproject($projectid)
**Purpose**: Delete project with dependency validation  
**Called By**: GET action to `?do=delete&id=$projectid`  
**Parameters**:
- `$projectid` (int) - Project to delete

**Returns**: Integer (1 = success, 0 = has dependencies)

**Database Operations**:
- SELECT from `projectexchmaterial` - Check for materials
- DELETE from `project`, `client`, `costcenter`
- DELETE from `accountstree` - Remove tree entries
- Reverse daily entries

**Business Logic**:
1. Check if project has material operations (prevents deletion)
2. If no dependencies:
   - Reverse all accounting entries
   - Delete tree elements by name
   - Delete project, client, and cost center
   - Mark as deleted (soft delete)

### 5. entryinsert_data($projectname, $value, $clientid, $projectid)
**Purpose**: Create double-entry accounting record for project creation  
**Parameters**:
- `$projectname` (string) - Project description
- `$value` (float) - Transaction amount
- `$clientid` (int) - Client tree ID (debtor)
- `$projectid` (int) - Project tree ID (creditor)

**Returns**: Entry ID

**Accounting Entry**:
```
DR: Client Account (Asset)     $value
    CR: Goods Under Settlement     $value
Comment: "تم اضافة مشروع اسمه {$projectname}"
```

---

## 📊 Main Workflows

### Workflow 1: Project Creation
```
1. User fills project form
   ↓
2. Validate required fields
   ↓
3. Create Cost Center
   ↓
4. Create Client (optional)
   ↓
5. Create Accounting Tree Entries
   ↓
6. Insert Project Master Record
   ↓
7. Link Project Stages
   ↓
8. Create Timeline Items
   ↓
9. Success/Error Response
```

**Files Involved**:
- View: `/views/default/projectview/add.html`
- Model: `/models/dto/Project.class.php`
- DAO: `/models/mysql/ProjectMySqlDAO.class.php`

### Workflow 2: Project Finishing
```
1. Validate Project ID
   ↓
2. Calculate Financial Position
   ↓
3. Mark All Records as Finished
   ↓
4. Create Final Accounting Entry
   ↓
5. Success Response
```

### Workflow 3: Project Deletion
```
1. Check Material Dependencies
   ↓
2. If Dependencies Found → Block Deletion
   ↓
3. Reverse All Accounting Entries
   ↓
4. Delete Tree Elements
   ↓
5. Soft Delete All Records
   ↓
6. Success Response
```

---

## 🔗 File Dependencies

### Includes
```php
include("../public/impOpreation.php");
include_once("../library/uploadImages.php");
include_once("../public/config.php");
include("../public/include_dao.php");
include_once("dailyentryfun.php");
```

### Required Models
- Project, Client, Costcenter, Accountstree, ProjectKind
- Dailyentry, Dailyentrycreditor, Dailyentrydebtor
- Projectexchmaterial, Programsettings, YoutubeLink

### Related Views
- `/views/default/projectview/add.html` - Project creation form
- `/views/default/projectview/show.html` - Project listing
- `/views/default/projectview/edit.html` - Project editing
- `/views/default/projectview/detailtimetableitems.html` - Timeline view

---

## 🎯 URL Routes & Actions

| Action (`?do=`) | Method | Description | View Template |
|-----------------|--------|-------------|---------------|
| (empty) | GET | Display creation form | add.html |
| show | POST | List projects with filters | show.html |
| add | POST | Create new project | - |
| edit | GET | Display edit form | edit.html |
| timetableitems | GET | Show timeline items | detailtimetableitems.html |
| update | POST | Update existing project | - |
| delete | GET | Delete project | - |
| finish | GET | Mark project as finished | - |
| sucess | GET | Success message | succes.html |
| error | GET | Error message | error.html |

---

## ⚠️ Known Issues & Fixes

### Issue 1: Undefined Variable in Tree Creation (Line 433)
**Problem**: `$txtName` used instead of `$projectName` in tree creation  
**Cause**: Copy-paste error from another function  
**Fix**: Replace `$txtName` with `$projectName`  
**File**: Line 433

### Issue 2: Unused Entry ID in Update (Line 567)  
**Problem**: `$NEWentryid` used but never defined  
**Cause**: Incomplete refactoring  
**Fix**: Remove unused variable or implement entry update logic  
**File**: Line 567

### Issue 3: Stage Array Check (Lines 443, 582)
**Problem**: Array check may fail with non-array inputs  
**Cause**: User input validation  
**Fix**: Add `is_array()` check before `in_array()`  
**File**: Lines 443, 582

---

## 🔐 Permissions & Security

### Required Permissions
- Project management access
- Client creation (if enabled)
- Accounting tree modification
- Cost center management

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

### Input Validation
- All POST data filtered with `filter_input()`
- File uploads validated through upload library
- Session-based user permissions

---

## 📝 Notes

### Important Considerations
- Project deletion only allowed if no material operations exist
- Finishing a project creates irreversible accounting entries
- Timeline items support date ranges and amounts
- Stage selection affects project workflow

### Future Improvements
- [ ] Add project templates
- [ ] Implement project approval workflow  
- [ ] Add project status history
- [ ] Enhance timeline management with dependencies

---

## 📚 Related Documentation
- [Project Operations](projectoperationController.md)
- [Project Reports](projectReportController.md)
- [Daily Entry Functions](dailyentryfun.md)
- [Accounting Tree Management](accountstree.md)