# Profit (Faida) Controller Documentation

**File**: `/controllers/FaidaController.php`  
**Purpose**: Manages profit/sales reports, customer specific reports, and promotional bill tracking  
**Last Updated**: December 19, 2024  
**Total Functions**: 17  
**Lines of Code**: 1,106

---

## 📋 Overview

The Faida (Profit) Controller manages profit-related operations and customer-specific promotional reports in the ERP system. It handles:
- Creating and editing promotional/profit bills (Faida)
- Tracking customer-specific promotional offerings
- Managing profit bill products and details
- Calculating promotional pricing and discounts
- Inventory tracking for promotional items
- Profit analysis and reporting
- Quick profit calculations and cost analysis
- Integration with store management and accounting

### Primary Functions
- [x] Create promotional bills (Faida)
- [x] Edit existing promotional bills
- [x] Delete promotional bills
- [x] View promotional bill details
- [x] Track promotional products
- [x] Calculate profit margins
- [x] Update inventory quantities
- [x] Generate profit reports
- [x] Manage customer promotions
- [x] Handle cost calculations

### Related Controllers
- [sellbillController.php](sellbillController.md) - Sales operations
- [buyBillController.php](buyBillController.md) - Purchase operations
- [clientController.php](clientController.md) - Customer management
- [productController.php](productController.md) - Product management
- [storeController.php](storeController.md) - Warehouse/store management
- [balancereportController.php](balancereportController.md) - Balance sheet reports
- [storereportController.php](storereportController.md) - Stock reports
- [FinancialPositionController.php](FinancialPositionController.md) - Financial position

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `faida` | Main promotional bills | id, clientId, premmium, installment_duration, total_amount, comment, user_id, storeId, conditions, presenter |
| `faidaproduct` | Promotional bill products | id, faidaId, productId, pronum, proprice, faidaproducttotalprice, pricetypepro, discounttype |

### Related Tables (Read Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `client` | Customer information | clientid, clientname, clientphone, clientaddress |
| `product` | Product catalog | productId, productName, productBuyPrice, lastbuyprice, meanbuyprice |
| `storedetail` | Product inventory | storedetailid, storeid, productid, productquantity |
| `storereport` | Inventory movements | storereportid, productid, storeid, productquantity, processname |
| `quickprofitstore` | Store profit tracking | storeId, theDate, sellVal, sellCostBuyPrice |
| `quickprofitproduct` | Product profit tracking | productId, theDate, sellVal, sellCostMeanBuyPrice |

### Reference Tables (Lookups)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `store` | Warehouse/store master | storeid, storename, storeaddress |
| `unit` | Unit of measures | unitid, unitname, unitsymbol |
| `productunit` | Product-unit relationships | productid, unitid, productnumber |
| `billname` | Bill type definitions | billnameid, billname, billdescription |
| `billsettings` | Bill configuration | billsettingsid, billnameid, property, value |

---

## 🔧 Key Functions

### Core Operations

#### `add()` (Lines 416-441)
**Purpose**: Creates a new promotional bill (Faida)
**Parameters**: 
- `$_POST['supplier']` - Client/customer ID
- `$_POST['premium']` - Premium time period
- `$_POST['Installment_duration']` - Payment installment duration
- `$_POST['total_amount']` - Total promotional amount
- `$_POST['textDetails']` - Comments/details
- `$_POST['storeid']` - Store ID
- `$_POST['presenter']` - Presenter ID

**Process Flow**:
```
┌─ Start add() ─┐
│ Get POST data │
├─ Create Faida ┤
│ Set properties │
├─ Insert to DB ┤
│ Get new ID    │
├─ Call addFaida┤
│ Add products  │
└─ Complete ────┘
```

**Code Example**:
```php
$myFaida->clientId = $client_id;
$myFaida->premmium = $premium_time;
$myFaida->total_amount = $total_amount;
$myFaidaId = $myFaidaDAO->insert($myFaida);
addFaida($myFaidaId);
```

#### `addFaida($myFaidaId)` (Lines 443-524)
**Purpose**: Adds promotional products to a Faida bill and updates inventory
**Parameters**: `$myFaidaId` - The promotional bill ID

**Process Flow**:
```
┌─ Get Products ─┐
│ Loop through   │
├─ Set Product ─┤
│ Properties     │
├─ Insert to DB ┤
│ Update Store   │
├─ Track Report ┤
│ Insert history │
└─ Complete ─────┘
```

**Returns**: Updates inventory and creates store reports

#### `show()` (Lines 526-545)
**Purpose**: Retrieves all promotional bills for display
**Parameters**: None (uses session user ID)

**Process Flow**:
```
┌─ Query Bills ──┐
│ Get all Faida  │
├─ Load User ────┤
│ Get username   │
├─ Load Client ─┤
│ Get clientname │
└─ Return Data ──┘
```

**Returns**: Array of promotional bills with user and client names

#### `update()` (Lines 547-577)
**Purpose**: Updates existing promotional bill
**Parameters**: 
- All POST parameters from add() function
- `$_POST['faida_id']` - The promotional bill ID to update

**Process Flow**:
```
┌─ Get Data ─────┐
│ From POST      │
├─ Update Faida ┤
│ Main record    │
├─ Delete Old ──┤
│ Products       │
├─ Add New ─────┤
│ Products       │
└─ Complete ────┘
```

#### `delete()` (Lines 579-586)
**Purpose**: Deletes a promotional bill and its products
**Parameters**: `$_GET['id']` - The promotional bill ID

### Utility Functions

#### `loadClient()` (Lines 634-639)
**Purpose**: Loads all active clients for dropdown selection
**Returns**: Array of client data

#### `loadUnit()` (Lines 641-646)
**Purpose**: Loads all units for product unit selection
**Returns**: Array of unit data

#### `loadProductUnitWithProductAndUnit($productId, $unitId)` (Lines 648-657)
**Purpose**: Gets product-unit relationship data
**Parameters**: `$productId`, `$unitId`
**Returns**: Product unit data object

### Inventory Management Functions

#### `decreaseProductQuantity(...)` (Lines 660-722)
**Purpose**: Decreases product quantity in store and handles size/color variants
**Parameters**: Multiple parameters for store detail, quantity changes, and tracking

**Process Flow**:
```
┌─ Calculate ────┐
│ New quantity   │
├─ Handle Size ─┤
│ Color variants │
├─ Update Store ┤
│ Detail record  │
├─ Update Price ┤
│ Calculations   │
└─ Track Report ┘
```

#### `insertStoredetail(...)` (Lines 725-759)
**Purpose**: Inserts new store detail record for product
**Parameters**: Store, product, and quantity information

#### `getStoreDetails($storeId, $productId, $unittype, $sizeColorStoreDetailId, $sizeId, $colorId)` (Lines 787-811)
**Purpose**: Retrieves current store detail information for a product
**Returns**: Array with store detail data, ID, and current quantity

### Profit Calculation Functions

#### `quickProfitRow(...)` (Lines 896-962)
**Purpose**: Calculates and tracks profit data for promotional sales
**Parameters**: Product data, quantities, prices, and store information

**Process Flow**:
```
┌─ Calculate ────┐
│ Profit margins │
├─ Handle Return┤
│ vs Regular    │
├─ Update DB ───┤
│ Profit tables │
├─ Track Costs ─┤
│ Array totals   │
└─ Complete ────┘
```

#### `ifCollectiveProductReCalculateCost($buyProduct)` (Lines 813-848)
**Purpose**: Recalculates cost for collective/bundle products
**Parameters**: `$buyProduct` - Product object
**Returns**: Updated product object with recalculated costs

#### `lastAndMeanBuyPrice_Sell(...)` (Lines 850-894)
**Purpose**: Updates last and mean buy prices for sold products
**Parameters**: Price tracking and calculation parameters

### Specialized Functions

#### `ifCollectiveDecreaseItsIngriedientsInStore(...)` (Lines 964-1034)
**Purpose**: Handles inventory decrease for collective product ingredients
**Parameters**: Product data, quantities, and store information

#### `onlineTempStoreDetailFunc(...)` (Lines 1036-1054)
**Purpose**: Updates temporary online store detail for web integration
**Parameters**: Store, product, size, color, quantity, and edit status

#### `insertStorereportupdate(...)` (Lines 1080-1106)
**Purpose**: Inserts store report entries for audit trail
**Parameters**: Product, store, quantity changes, and process information

---

## 🔄 Business Logic Flow

### Creating a Promotional Bill

```
Start → Validate User → Load Form Data → Select Products
  ↓
Display Form → User Input → Submit Data → Validate Input
  ↓
Create Faida Record → Add Products → Update Inventory → Generate Reports
  ↓
Calculate Profits → Track Changes → Update Online Store → Complete
```

### Promotional Product Management

```
Product Selection → Unit Calculation → Price Determination
  ↓
Discount Application → Total Calculation → Inventory Check
  ↓
Stock Decrease → Cost Calculation → Profit Tracking → Report Generation
```

### Inventory Integration Flow

```
Product Sale → Check Store Details → Update Quantities
  ↓
Handle Size/Color → Calculate Costs → Update Prices
  ↓
Generate Reports → Track Movements → Sync Online Store
```

---

## ⚠️ Common Issues

### PHP 8.2 Compatibility Issues
1. **Object initialization issues**: Function creates objects properly using `new stdClass()`
2. **Count() usage**: Uses proper array checking with `count()` and `!empty()`
3. **Type casting**: Properly handles numeric conversions

### Performance Considerations
1. **Complex calculations**: Heavy profit calculation functions may impact performance
2. **Multiple database operations**: Each product addition triggers multiple DB updates
3. **Store synchronization**: Online store updates add overhead

### Business Logic Warnings
1. **Inventory validation**: No validation for negative stock after promotional sales
2. **Price calculations**: Complex profit margin calculations may have rounding issues
3. **Collective products**: Bundle product handling adds complexity

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Database configuration
- `../public/authentication.php` - User authentication
- Various DAO and DTO files for data access

### Database Dependencies
- MySQL database with proper table relationships
- Triggers or procedures for inventory management
- Views for reporting and profit calculations

### External Dependencies
- Smarty templating engine for views
- Session management for user tracking
- Online store integration capabilities

### Related Controllers
- Store management for inventory operations
- Client management for customer data
- Product management for catalog operations
- Billing system for promotional pricing

---

**Database Schema Notes**:
- `faida` table stores promotional bill headers
- `faidaproduct` table stores promotional bill line items
- Complex relationships with inventory and profit tracking tables
- Integration with online store synchronization system