# Free Buys Controller Documentation

**File**: `/controllers/freebuys.php`  
**Purpose**: Free purchase transactions reporting and analysis  
**Last Updated**: December 20, 2024  
**Total Functions**: 6+  
**Lines of Code**: ~631

---

## 📋 Overview

The Free Buys Controller manages and reports on purchase transactions with zero cost (free purchases). It provides:
- Free purchase transaction analysis
- Product-wise free purchase reporting
- Category and date-based filtering
- Detailed transaction drill-down
- Cost analysis and profit calculations
- Multi-bill type support (regular, return, combined)

### Primary Functions
- [x] Free purchase transaction reports
- [x] Product profitability analysis for free items
- [x] Category-based filtering and grouping
- [x] Date range analysis
- [x] Detailed transaction history
- [x] Cost and profit calculations
- [x] Multi-bill type consolidation

### Related Controllers
- [freesales.php](freesales.md) - Free sales reporting
- [buyBillController.php](buyBillController.md) - Purchase management
- [returnBuyBillController.php](returnBuyBillController.md) - Purchase returns

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **buybilldetail** | Purchase bill line items | buybilldetailid, buybillid, buybilldetailproductid, buybilldetailquantity, buybilldetailtotalprice, productunitid, parcode, note, discountvalue |
| **returnbuybilldetail** | Purchase return details | returnbuybilldetailid, returnbuybillid, returnbuybilldetailproductid, returnbuybilldetailquantity, returnbuybilldetailtotalprice |
| **buyandruternbilldetail** | Combined buy/return details | buyandruternbilldetailid, buybillid, buybilldetailproductid, buybilldetailquantity, buybilldetailtotalprice, billtype |

### Bill Header Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **buybill** | Purchase bills | buybillid, buybilldate, buybillsupplierid, buybillstoreid |
| **returnbuybill** | Purchase returns | returnbuybillid, returnbuybilldate, returnbuybillsupplierid |
| **buyandruternbill** | Combined bills | buybillid, buybilldate, buybillsupplierid |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **product** | Product master data | productId, productName, productCatId, productBuyPrice |
| **productcat** | Product categories | productCatId, productCatName, productCatParent |
| **productunit** | Unit conversions | productunitid, productid, unitid, productnumber |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default Action** - Free Purchases Report Interface
**Location**: Line 105  
**Purpose**: Display search interface and generate free purchase reports

**Process Flow**:
1. Load category hierarchy for filtering
2. Process search parameters (dates, categories, products)
3. Build query strings for different bill types
4. Filter for zero-cost transactions (`buybilldetailtotalprice = 0`)
5. Call `getData()` to process and display results

**Search Parameters**:
- `datefrom/dateto` - Date range filtering
- `level` - Category hierarchy level
- `productCatId{level}` - Category selection
- `productId` - Specific product filter
- `searchtype` - Search mode (0=standard)
- `proIsOptic` - Optical products flag

### 2. **getData()** - Core Report Processing
**Location**: Line 278  
**Purpose**: Process free purchase transactions and calculate totals

**Function Signature**:
```php
function getData($queryString1, $queryString1R, $queryString1SR, $searchtype, $productCatId, $theStore)
```

**Product Data Class**:
```php
class productData {
    public $id;
    public $productName;
    public $soldNo = 0;      // Purchased quantity
    public $soldVal = 0;     // Purchase value (should be 0)
    public $returnNo = 0;    // Returned quantity
    public $returnVal = 0;   // Return value
    public $netNo = 0;       // Net quantity (purchased - returned)
    public $netVal = 0;      // Net value
    public $realCost = 0;    // Actual cost from product master
    public $netProfit = 0;   // Calculated profit/loss
    public $buyPrice = 0;    // Reference buy price
    public $currentQuantity = 0; // Current stock
}
```

**Processing Logic**:
1. **Purchase Bills**: Query free items (`buybilldetailtotalprice = 0`)
2. **Return Bills**: Query free returns (`returnbuybilldetailtotalprice = 0`)
3. **Combined Bills**: Query free combined transactions
4. **Unit Conversion**: Convert quantities to standard units
5. **Discount Calculation**: Handle bill-level discounts
6. **Aggregation**: Sum quantities and values by product
7. **Cost Analysis**: Calculate real cost vs. free acquisition

### 3. **getDetails()** - Transaction Details
**Location**: Line 490  
**Purpose**: Get detailed transaction list for drill-down analysis

**Process Flow**:
1. Apply same filters as summary report
2. Query individual transaction records
3. Convert quantities using unit multipliers
4. Format for detailed display with bill links

**Detail Data Class**:
```php
class productDetails {
    public $billid = 0;      // Bill identifier
    public $billURL;         // Link to bill details
    public $billdate;        // Transaction date
    public $productno = 0;   // Quantity in standard units
    public $clientname;      // Stored in discountvalue field
    public $storename;       // Stored in note field
}
```

### 4. **getAllSubCat()** - Category Hierarchy Traversal
**Location**: Line 592  
**Purpose**: Recursively get all subcategories for filtering

**Parameters**:
- `$catid` - Starting category ID
- `$mode` - 1=all subcategories, 2=leaf categories only

---

## 🔄 Workflows

### Workflow 1: Free Purchase Analysis
```
┌─────────────────────────────────────────────────────────────┐
│                START: Select Criteria                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Filter Configuration                                    │
│     - Set date range for analysis                         │
│     - Select product category (optional)                  │
│     - Choose specific product (optional)                  │
│     - Include optical products flag                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Query Free Transactions                                │
│     - Purchase bills with zero cost                       │
│     - Purchase returns with zero cost                     │
│     - Combined bills with zero cost items                 │
│     - Apply category and date filters                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process and Calculate                                  │
│     FOR EACH product with free transactions:              │
│       │                                                     │
│       ├─→ Convert quantities to standard units            │
│       ├─→ Calculate bill-level discounts                  │
│       ├─→ Sum purchased vs. returned quantities           │
│       ├─→ Calculate net quantities and values             │
│       ├─→ Get real cost from product master               │
│       ├─→ Calculate profit/loss on free items             │
│       └─→ Get current inventory levels                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Generate Report                                        │
│     - Display product-wise summary                        │
│     - Show quantities and profit analysis                 │
│     - Provide drill-down to transaction details          │
│     - Calculate category and overall totals               │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Free purchases report interface |
| `do=detail` | `getDetails()` | Detailed transaction drill-down |

### Required Parameters

**Summary Report**:
- `datefrom/dateto` - Date range (optional, defaults to today)
- `level` - Category hierarchy level
- `productCatId{level}` - Category filter
- `productId` - Product filter
- `searchtype` - Must be 0 for standard search
- `proIsOptic` - Optical products flag

**Detail Report** (`do=detail`):
- Same as summary plus:
- `id` - Product ID for detailed view

---

## 🧮 Calculation Methods

### Unit Conversion
```php
$productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
$productnumber = $productunitData->productnumber;
$finalquantity = $quantity * $productnumber;
```

### Discount Allocation
```php
$dicount = $value->parcode - $value->note;  // Bill discount
if ($dicount != 0) {
    $billpecies = $buyBillDetailEX->queryBillNoOfPecies($value->buybillid);
    $billNoOfProduct = $billpecies->note;
    $theDiscount = ($finalquantity * $dicount) / $billNoOfProduct;
    $theDiscount -= $value->discountvalue;  // Line discount
}
```

### Profit Calculation
```php
$data->realCost = $data->netNo * $buyDatail->productBuyPrice;
$data->netProfit = $data->netVal - $data->realCost;
```

---

## 🔒 Security & Permissions

### Authentication Required
- All actions require valid session
- User authentication via `../public/authentication.php`

### Data Access Control
- Queries limited to accessible bill types
- No sensitive supplier or cost data exposed in free context

---

## 📊 Performance Considerations

### Query Optimization
1. **Zero Cost Filter**: Early filtering on `totalprice = 0`
2. **Date Indexing**: Efficient date range queries
3. **Category Expansion**: Recursive category traversal cached

### Memory Management
- Product aggregation uses efficient array indexing
- Avoids loading unnecessary bill details

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Free Transactions**
**Issue**: Known free items not appearing in report  
**Cause**: Total price stored as non-zero value

**Debug**:
```sql
-- Check for near-zero values
SELECT * FROM buybilldetail 
WHERE buybilldetailproductid = [PRODUCT_ID]
AND buybilldetailtotalprice BETWEEN -0.01 AND 0.01;
```

### 2. **Incorrect Quantity Calculations**
**Issue**: Unit conversion producing wrong quantities  
**Cause**: Missing or incorrect productunit records

**Fix**:
```sql
-- Verify unit conversions
SELECT pu.productnumber, u.unitName 
FROM productunit pu 
JOIN unit u ON u.unitId = pu.unitid 
WHERE pu.productid = [PRODUCT_ID];
```

### 3. **Category Filter Not Working**
**Issue**: Category selection not filtering products  
**Cause**: Recursive category expansion issues

**Debug**: Test `getAllSubCat()` function with specific category ID

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Free Purchase Report
```
1. Set date range covering known free purchases
2. Run report without filters
3. Verify free items appear with zero cost
4. Check quantity calculations
5. Confirm profit analysis accuracy
```

### Test Case 2: Category Filtering
```
1. Select specific product category
2. Verify only category products shown
3. Test subcategory inclusion
4. Confirm category totals match
```

### Test Case 3: Transaction Details
```
1. Click on product for details
2. Verify all related transactions shown
3. Check bill links work correctly
4. Confirm date and quantity accuracy
```

---

## 📚 Related Documentation

- [freesales.md](freesales.md) - Free sales reporting
- [buyBillController.md](buyBillController.md) - Purchase management
- [returnBuyBillController.md](returnBuyBillController.md) - Purchase returns

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur