# Project Material Controller Documentation

**File**: `/controllers/projectmaterialController.php`  
**Purpose**: Manages raw materials and supplies for construction/project-based manufacturing  
**Last Updated**: December 19, 2024  
**Total Functions**: 12  
**Lines of Code**: ~601

---

## 📋 Overview

The Project Material Controller manages raw materials and supplies specifically for construction projects and project-based manufacturing. It handles:
- Project-specific material requisitions and consumption
- Material transfers to project sites
- Project-based inventory tracking
- Construction material cost tracking
- Project material receipt and issuing
- Material accountability by project
- Integration with project accounting
- Image documentation for materials
- Material cost allocation to projects

### Primary Functions
- [x] Create material requisitions for projects
- [x] Issue materials to project sites
- [x] Track material consumption by project
- [x] Record material receipts from suppliers
- [x] Manage project material inventory
- [x] Upload material images and documentation
- [x] Generate project material reports
- [x] Allocate material costs to projects
- [x] Handle material returns from projects
- [x] Integrate with project accounting

### Related Controllers
- [projectController.php](projectController.md) - Project management
- [storeController.php](storeController.md) - Main inventory management
- [productController.php](productController.md) - Product/material master data
- [buyBillController.php](buyBillController.md) - Material procurement
- [supplierController.php](supplierController.md) - Supplier management
- [clientController.php](clientController.md) - Client/project owner management
- [costcenterController.php](#) - Cost center allocation
- [dailyentryController.php](#) - Accounting entries
- [storedetailController.php](#) - Inventory management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `projectmaterials` | Project material header | `id`, `projectid`, `storeid`, `billdate`, `totalbuyprice`, `userid` |
| `projectmaterialdetails` | Material line items | `id`, `projectmaterialid`, `productid`, `productnumber`, `probuyprice`, `image` |

### Related Tables (Projects & Inventory)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `project` | Project master data | `projectid`, `name`, `startdate`, `enddate`, `clientid` |
| `storedetail` | Current inventory | `storedetailid`, `storeid`, `productid`, `productquantity` |
| `storereport` | Inventory movements | `storereportid`, `productid`, `processname`, `productbefore`, `productafter` |
| `product` | Material/product master | `productId`, `productName`, `productBuyPrice`, `productSellPrice` |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `store` | Warehouse/site locations | `storeid`, `storeName` |
| `client` | Project clients/owners | `clientid`, `clientname` |
| `costcenter` | Cost centers for allocation | `costcenterid`, `costcentername` |
| `user` | System users | `userid`, `employeename` |

---

## 🔧 Key Functions

### 1. **add() - Issue Materials to Project**
**Line**: 345  
**Purpose**: Creates material requisition and issues materials from warehouse to project

**Parameters**:
- `$_POST['projectname']` - Project ID
- `$_POST['storeid']` - Source warehouse
- `$_POST['billdate']` - Issue date
- `$_POST['totalpronumber']` - Total items count
- `$_POST['finaltotalprice']` - Total value
- `$_POST['casesid']` - Case/purpose ID
- Material details arrays for each line item

**Process Flow**:
```
┌─ Create Material Requisition ─┐
│                               │
▼                               │
Insert projectmaterials header ──┘
│
▼
For each material line item:
├─ Get product details
├─ Record material details  
├─ Process image upload
├─ Validate quantities
└─ Create detail record
│
▼
Update project costs
```

**Code Example**:
```php
// Create material header
$projectmaterials = R::dispense('projectmaterials');
$projectmaterials->projectid = $projectid;
$projectmaterials->storeid = $storeid;
$projectmaterials->totalbuyprice = $finaltotalprice;
$projectmaterials->userid = $_SESSION['userid'];
$projectmaterialid = R::store($projectmaterials);

// Add material details with image handling
for ($i = 1; $i <= $offerhidden_itr; $i++) {
    $handle = new upload($_FILES['image'. $i]);
    $imagePhoto = uploadImageswhioutresize($handle, "../upload/projectmaterials");
    
    $projectmaterialdetails = R::dispense('projectmaterialdetails');
    $projectmaterialdetails->projectmaterialid = $projectmaterialid;
    $projectmaterialdetails->productid = $productid;
    $projectmaterialdetails->image = $imagePhoto;
    R::store($projectmaterialdetails);
}
```

---

### 2. **show() - View Project Material Transactions**
**Line**: 202  
**Purpose**: Displays project material transactions with filtering options

**Parameters**:
- `$_POST['projectname']` - Filter by project
- `$_POST['datefrom']`, `$_POST['dateto']` - Date range filter
- `$_POST['casesid']` - Filter by case/purpose

**Process Flow**:
```
┌─ Material Transaction Report ─┐
│                               │
▼                               │
Build dynamic SQL query ────────┘
│ • Filter by project
│ • Filter by date range
│ • Filter by case type
│ • Apply user permissions
▼
Execute query and get results
│
▼
For each transaction:
├─ Get project name
├─ Get user/employee name
├─ Enrich transaction data
└─ Add to results array
│
▼
Display formatted results
```

**SQL Query Building**:
```php
$queryString = " where 1 ";
if (isset($projectid) && !empty($projectid)) {
    $queryString .= " and projectmaterials.projectid = " . $projectid;
}
if ($_SESSION['projectids'] != 0) {
    $queryString .= ' AND projectmaterials.projectid in (' . $_SESSION['projectids'] . ')';
}
if (isset($datefrom) && !empty($datefrom)) {
    $queryString .= ' and projectmaterials.sysdate >= "' . $datefrom . '" ';
}
```

---

### 3. **edit() - Modify Material Requisition**
**Line**: 255  
**Purpose**: Allows editing of existing material requisitions

**Process Flow**:
```
┌─ Edit Material Requisition ─┐
│                             │
▼                             │
Load existing requisition ────┘
│
▼
Load all material details
│
▼
For each detail line:
├─ Get product information
├─ Load current images
├─ Prepare edit form data
└─ Calculate totals
│
▼
Display edit form with current data
```

---

### 4. **update() - Save Material Changes**
**Line**: 404  
**Purpose**: Updates material requisition by deleting old and recreating

**Process Flow**:
```
┌─ Update Material Requisition ─┐
│                               │
▼                               │
Delete existing records ────────┘
│
▼
Call add() function with new data
│
▼
Recreate all records with updates
```

**Note**: Uses delete-and-recreate pattern for simplicity

---

### 5. **delete() - Remove Material Requisition**
**Line**: 411  
**Purpose**: Deletes material requisition and all associated details

**Process Flow**:
```
┌─ Delete Material Requisition ─┐
│                               │
▼                               │
Load main requisition record ────┘
│
▼
Find all detail records
│
▼
Delete all detail records
│
▼
Delete main requisition record
```

**Code Example**:
```php
$projectmaterials = R::load('projectmaterials', $id);
$projectmaterialdetails = R::findAll("projectmaterialdetails", " projectmaterialid = ? ", [$id]);
R::trashAll($projectmaterialdetails);
R::trash($projectmaterials);
```

---

### 6. **getStoredetailData() - Inventory Lookup**
**Line**: 510  
**Purpose**: Retrieves current inventory levels for a product in specific warehouse

**Parameters**:
- `$storeid` - Warehouse ID
- `$productid` - Product/material ID

**Returns**: Array containing store detail data, ID, and current quantity

---

### 7. **decreaseProductQuantity() - Reduce Inventory**
**Line**: 522  
**Purpose**: Reduces product quantity in warehouse when materials are issued

**Process Flow**:
```
┌─ Reduce Inventory ─┐
│                    │
▼                    │
Calculate new quantity ──┘
│ new_qty = current_qty - issued_qty
▼
Update storedetail record
│
▼
Create audit trail entry
│
▼
Return new quantity
```

---

### 8. **insertStorereport() - Audit Trail**
**Line**: 542  
**Purpose**: Creates inventory movement audit trail for material transactions

**Parameters**:
- Product and store information
- Quantities before/after transaction
- Process description
- Reference IDs

---

## 🔄 Business Logic Flow

### Project Material Workflow

```
┌─ Project Planning ─┐
│                    │
▼                    │
Material Requirements ──┘
│ • Define project materials needed
│ • Estimate quantities required
│ • Plan delivery schedule
▼
┌─ Material Procurement ─┐
│ • Purchase materials      │
│ • Receive in warehouse    │
│ • Quality inspection      │
│ • Update inventory        │
└───────────────────────────┘
│
▼
┌─ Material Requisition ─┐
│ • Request materials for project │
│ • Specify quantities needed     │
│ • Attach supporting images      │
│ • Get approvals                 │
└─────────────────────────────────┘
│
▼
┌─ Material Issue ─┐
│ • Verify inventory availability │
│ • Issue materials to project    │
│ • Reduce warehouse inventory    │
│ • Create audit trail           │
└───────────────────────────────┘
│
▼
┌─ Project Consumption ─┐
│ • Use materials in construction │
│ • Track actual usage vs planned │
│ • Record waste/spillage         │
│ • Update project costs          │
└─────────────────────────────────┘
```

### Material Accountability Chain

```
Purchase → Warehouse → Project Site → Consumption
    ↓          ↓           ↓             ↓
Buy Bills → Store Detail → Project Materials → Project Costs
```

---

## ⚠️ Common Issues

### 1. **Material Shortage for Projects**
**Symptoms**: Cannot issue required materials to project
**Causes**:
- Insufficient warehouse inventory
- Materials committed to other projects
- Incorrect quantity calculations

**Solutions**:
- Implement material reservation system
- Add inventory checking before requisition approval
- Create material availability reports

### 2. **Image Upload Failures**
**Symptoms**: Material images not saved or displayed
**Causes**:
- Upload directory permissions
- File size limitations
- Invalid file formats

**Solutions**:
- Verify upload directory permissions (../upload/projectmaterials)
- Check PHP upload settings
- Validate file types before upload

### 3. **Project Cost Allocation Issues**
**Symptoms**: Incorrect project material costs
**Causes**:
- Missing cost allocation entries
- Incorrect material prices
- Exchange rate fluctuations for imported materials

**Solutions**:
- Implement automated cost allocation
- Regular price validation procedures
- Currency conversion tracking

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Database configuration
- `../public/include_dao.php` - Data access objects
- `../library/uploadImages.php` - Image upload handling
- `dailyentryfun.php` - Accounting functions

### Required DAOs
- RedBean ORM for database operations
- Project-related DAOs for project data
- Product DAOs for material information
- Store DAOs for inventory management

### Upload Configuration
- Upload directory: `../upload/projectmaterials/`
- Supported formats: Images for material documentation
- Permission requirements: Write access for web server

### Session Dependencies
- `$_SESSION['userid']` - Current user for audit trail
- `$_SESSION['projectids']` - User's accessible projects
- `$_SESSION['storenegative']` - Allow negative inventory setting

---

## 📊 Project Material Formulas

### Cost Allocation
```php
// Project material cost allocation
$projectMaterialCost = Σ(material_quantity × material_unit_cost);
$projectTotalCost += $projectMaterialCost;

// Cost per unit calculation
$costPerUnit = $projectTotalCost / $projectOutputUnits;

// Material utilization rate
$utilizationRate = $actualConsumption / $issuedQuantity × 100;
```

### Inventory Valuation
```php
// Project inventory value
$projectInventoryValue = Σ(remaining_quantity × weighted_average_cost);

// Material efficiency
$materialEfficiency = $standardMaterialCost / $actualMaterialCost × 100;

// Waste percentage
$wastePercentage = ($issuedQuantity - $usedQuantity) / $issuedQuantity × 100;
```

---

## 🏗️ Construction Industry Features

### Material Types Supported
- **Raw Materials**: Cement, steel, sand, gravel
- **Finished Components**: Doors, windows, fixtures
- **Consumables**: Welding rods, bolts, fasteners
- **Equipment Supplies**: Fuel, lubricants, spare parts

### Project Phases Integration
- **Foundation Phase**: Concrete materials, reinforcement
- **Structure Phase**: Steel, formwork, scaffolding
- **Finishing Phase**: Tiles, paint, fixtures
- **MEP Phase**: Electrical, plumbing, HVAC materials

### Documentation Features
- Material delivery receipts with photos
- Quality certificates and test reports
- Material inspection records
- Usage certificates and approvals

---

**Manufacturing Concepts Covered**: Project-Based Manufacturing, Material Requisitions, Construction Materials Management, Project Cost Allocation, Material Accountability, Site Inventory Management, Material Documentation, Project Accounting Integration, Material Traceability, Construction Workflow Integration