# Project Daily Report Controller Documentation

**File**: `/controllers/projectdailyreportController.php`  
**Purpose**: Manage daily progress reports with multimedia attachments for active projects  
**Last Updated**: 2024-12-20

---

## 📋 Overview

### Primary Functions
- [x] Daily report creation with multimedia
- [x] File and image upload management
- [x] Report viewing and editing
- [x] Project progress tracking
- [x] Ajax-based report management

### Related Controllers
- [projectController.php](projectController.md) - Project master data
- [projectstagesdataController.php](projectstagesdataController.md) - Stage progress

---

## 🗄️ Database Tables

### Primary Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| projectdailyreports | Daily progress reports | id, projectid, title, descripe, datechosse, images, files |
| project | Project master data | id, name, del, finish |

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

---

## 🔧 Key Functions

### 1. savedata()
**Purpose**: Create or update daily report with multimedia attachments  
**Called By**: AJAX POST to `?do=savedata`  
**Parameters**:
- `$projectid` (int) - Associated project ID
- `$datechosse` (date) - Report date
- `$title` (string) - Report title
- `$descripe` (text) - Report description
- `$projectdailyreportid` (int) - Report ID for updates

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

**Database Operations**:
- INSERT/UPDATE `projectdailyreports`
- Multiple file uploads to `/upload/project/`

**Business Logic**:
1. **File Upload Processing**:
   ```php
   if (!$projectdailyreportid) {
       $images = uploadfileMultipleWithName("images", '../upload/project'); 
       $files = uploadfileMultipleWithName("files", '../upload/project'); 
   } else {
       if (isset($_FILES["images"]) && !empty($_FILES["images"])) {
           $images = uploadfileMultipleWithName("images", '../upload/project', explode(',', $oldimages));
       }
   }
   ```

2. **Data Storage**:
   ```php
   $projectclients->images = implode(',', $images[0]);
   $projectclients->files = implode(',', $files[0]);
   $projectclients->nameimages = implode(',', $images[1]);
   $projectclients->namefiles = implode(',', $files[1]);
   ```

### 2. showajax()
**Purpose**: DataTables-compatible data source for report listing  
**Called By**: AJAX POST to `?do=showajax`  
**Parameters**:
- `$start_date` (string) - Filter start date
- `$end_date` (string) - Filter end date  
- `$data1` (int) - Project ID filter
- Standard DataTables parameters

**Returns**: JSON DataTables response

**Database Operations**:
- SELECT with JOIN to user and project tables
- COUNT for pagination
- Dynamic WHERE clause construction

**Business Logic**:
1. **Dynamic Filtering**:
   ```php
   if($data1 != '') {
       $searchQuery .= " and projectdailyreports.projectid = ".$data1;
   }
   if($start_date != '' && $end_date != '') {
       $searchQuery .= 'and projectdailyreports.addtoday >= "'.$start_date.' 00-00-00" 
                        and projectdailyreports.addtoday <= "'.$end_date.' 23-59-55"';
   }
   ```

2. **Output Formatting**:
   ```php
   $sub_array[] = $row["id"];
   $sub_array[] = $row["name"];     // Project name
   $sub_array[] = $row["title"];    // Report title
   $sub_array[] = $row["datechosse"]; // Report date
   $sub_array[] = $row["addtoday"];   // Creation date
   $sub_array[] = $row['employeename']; // Creator name
   ```

### 3. File Management Functions
**Purpose**: Handle multimedia attachments for reports

**File Processing**:
1. **Image Handling**:
   - Multiple image upload
   - Original filename preservation
   - Comma-separated storage

2. **Document Handling**:
   - Multiple file upload
   - Name and file path separation
   - Support for various file types

3. **Update Logic**:
   ```php
   $allfiles = explode(',', $projectdailyreport->files);
   $namefiles = explode(',', $projectdailyreport->namefiles);
   $files = [];
   for ($i=0; $i < count($allfiles); $i++) { 
       $files[] = ['name' => $namefiles[$i], 'file' => $allfiles[$i]];
   }
   ```

---

## 📊 Main Workflows

### Workflow 1: Daily Report Creation
```
1. Select active project
   ↓
2. Set report date
   ↓
3. Add title and description
   ↓
4. Upload images and files
   ↓
5. Submit via AJAX
   ↓
6. Process file uploads
   ↓
7. Store report data
   ↓
8. Return success status
```

**Files Involved**:
- View: `/views/default/projectdailyreportview/add.html`
- Upload: `/upload/project/` directory

### Workflow 2: Report Display & Management
```
1. Load report listing
   ↓
2. Apply project filters
   ↓
3. DataTables AJAX request
   ↓
4. Build query with filters
   ↓
5. Return paginated data
   ↓
6. Render with action buttons
```

### Workflow 3: Project Progress Overview
```
1. Select project (prodetail)
   ↓
2. Load all project reports
   ↓
3. Process multimedia files
   ↓
4. Display chronological view
   ↓
5. Show project timeline
```

---

## 🔗 File Dependencies

### Includes
```php
include("../public/impOpreation.php");
include("../library/uploadImages.php");  // For file upload processing
```

### Upload Directory
- Location: `/upload/project/`
- File types: Images and documents
- Naming: Original filenames preserved

### Related Views
- `/views/default/projectdailyreportview/add.html` - Report creation
- `/views/default/projectdailyreportview/show.html` - Report listing
- `/views/default/projectdailyreportview/edit.html` - Report editing
- `/views/default/projectdailyreportview/detail.html` - Report details
- `/views/default/projectdailyreportview/prodetail.html` - Project overview

---

## 🎯 URL Routes & Actions

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

---

## ⚠️ Known Issues & Fixes

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

### Issue 2: Student-specific Cleanup (Lines 274-277)
**Problem**: Updates student-related tables in removecontroller()  
**Cause**: Copy-paste error  
**Fix**: Remove or replace with appropriate cleanup  
**File**: Lines 274-277

### Issue 3: File Update Logic (Lines 130-135)
**Problem**: Complex conditional logic for file updates  
**Cause**: Handles both new and existing files  
**Fix**: Simplify with helper functions  
**File**: Lines 130-135

### Issue 4: Missing File Validation
**Problem**: No validation for file types or sizes  
**Cause**: Direct upload without checks  
**Fix**: Add file validation before upload  
**File**: Multiple upload locations

---

## 🔐 Permissions & Security

### Required Permissions
- Project daily report management
- File upload permissions

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

### File Security
- Upload directory restrictions
- File type validation needed
- Size limitations required

### Input Validation
- All POST data filtered with `filter_input()`
- Project ID validation
- Date format validation

---

## 📁 File Management

### Upload Structure
```
/upload/project/
├── images/
│   ├── report_image_1.jpg
│   └── report_image_2.png
└── documents/
    ├── progress_report.pdf
    └── specifications.doc
```

### File Storage Format
```php
// Database storage
$report->images = "file1.jpg,file2.png,file3.gif";
$report->nameimages = "Progress Photo,Site View,Equipment";
$report->files = "doc1.pdf,doc2.docx";  
$report->namefiles = "Daily Report,Specifications";
```

### File Retrieval
```php
// Convert to usable format
$allfiles = explode(',', $projectdailyreport->files);
$namefiles = explode(',', $projectdailyreport->namefiles);
$files = [];
for ($i=0; $i < count($allfiles); $i++) { 
    $files[] = [
        'name' => $namefiles[$i],
        'file' => $allfiles[$i]
    ];
}
```

---

## 📝 Notes

### Important Considerations
- Only active projects (finish = 0) can have daily reports
- Reports support multiple images and files per entry
- Original filenames are preserved for user reference
- Reports are soft-deleted to maintain audit trail

### Project Integration
- Reports link to specific projects
- Project name displayed in report listings
- All project reports viewable in single interface

### Future Improvements
- [ ] Add report templates
- [ ] Implement approval workflow
- [ ] Add email notifications
- [ ] Create progress charts
- [ ] Add GPS location tracking
- [ ] Implement report analytics

### Performance Considerations
- Large file uploads may timeout
- Consider image compression
- Implement file cleanup for deleted reports

---

## 📚 Related Documentation
- [Project Master](projectController.md)
- [File Upload Library](../libraries/uploadImages.md)
- [Project Stages](projectstagesdataController.md)
- [DataTables Integration](../frontend/datatables.md)