# Store Controller Documentation

**File**: `/controllers/storeController.php`  
**Purpose**: Manages warehouse/store operations, inventory evaluation, and store configurations  
**Last Updated**: December 19, 2024  
**Total Functions**: 9  
**Lines of Code**: 643

---

## 📋 Overview

The Store Controller is responsible for managing warehouse/store operations in the ERP system. It handles:
- Creating and editing store/warehouse records
- Managing store inventory evaluation
- Store visibility and permissions
- Inventory value calculations with different pricing methods
- Store location and branch associations
- Store operations (hide/show/delete)

### Primary Functions
- [x] Create new stores/warehouses
- [x] Edit existing stores
- [x] Delete stores (with validation)
- [x] View store inventory with evaluation
- [x] Hide/show stores (soft delete)
- [x] Calculate store inventory values
- [x] Batch operations on stores
- [x] Store branch management
- [x] Inventory pricing evaluation

### Related Controllers
- [buyBillController.php](buyBillController.md) - Purchase operations
- [sellbillController.php](sellbillController.md) - Sales operations
- [productController.php](productController.md) - Product management
- [storedetailController.php](#) - Store inventory details
- [storemovementController.php](#) - Stock transfers between stores
- [storereportController.php](#) - Store reports and valuations
- [branchController.php](#) - Branch management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **store** | Main store records | storeId, storeName, storeDescription, conditions, branchId, userId |
| **storedetail** | Store inventory details | storedetailid, storeid, productid, quantity, buyprice |

### Related Tables
| Table Name | Purpose | Usage |
|------------|---------|-------|
| **branch** | Store branches | Links stores to branches |
| **accountstree** | Accounting integration | Store accounts (treeId, treeIdBetween) |
| **programsetting** | System settings | Inventory evaluation method |
| **youtubelink** | Help videos | Store management tutorials |

### Reference Tables
| Table Name | Usage |
|------------|-------|
| **user** | Store creation/modification tracking |
| **product** | Products stored in warehouses |

---

## 🔧 Key Functions

### 1. **add()** - Create New Store
**Signature**: `add(): void`  
**Purpose**: Creates a new store/warehouse with accounting integration  
**Parameters**: Gets data from $_POST array

**Process Flow**:
```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Get POST      │───▶│   Create Store  │───▶│  Add Tree       │
│   Data          │    │   Record        │    │  Elements       │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                │                        │
                                ▼                        ▼
                       ┌─────────────────┐    ┌─────────────────┐
                       │  Insert Store   │    │  Update Store   │
                       │  Database       │    │  With TreeIds   │
                       └─────────────────┘    └─────────────────┘
```

**Key Logic**:
- Validates store name and details
- Creates accounting tree elements (main + intermediate)
- Sets creation date and user
- Stores branch association
- Creates API integration ID

**SQL Operations**:
```sql
INSERT INTO store (storeName, storeDescription, branchId, storeDate, userId, ...)
SELECT * FROM accountstree WHERE id = ?
UPDATE store SET treeId = ?, treeIdBetween = ? WHERE storeId = ?
```

### 2. **show()** - Display Store Inventory
**Signature**: `show(): array`  
**Purpose**: Retrieves and calculates store inventory with evaluation pricing  
**Returns**: Array of store data with calculated values

**Process Flow**:
```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│ Check Session   │───▶│  Query Store    │───▶│  Apply Pricing  │
│ Store Filter    │    │  Evaluation     │    │  Evaluation     │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                        │                        │
         ▼                        ▼                        ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│  All Stores /   │    │  Get Program    │    │  Return Store   │
│ Selected Store  │    │  Settings       │    │  Data Array     │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

**Pricing Evaluation Methods**:
- **first**: First purchase price
- **last**: Last purchase price  
- **mean**: Average purchase price
- **last_discount**: Last price with discount
- **mean_discount**: Average price with discount
- **generalPrice**: Overall average price
- **tax**: Last price with tax
- **mean_tax**: Average price with tax

**Key Logic**:
```php
foreach ($storeData as $story) {
    switch ($Programsettingdata->Inventoryevaluation) {
        case "first":
            $totQtyPrice = (float) $story->tot_productBuyPrice;
            break;
        case "last":
            $totQtyPrice = (float) $story->tot_lastbuyprice;
            break;
        // ... other methods
    }
    $story->totQtyPrice2 = $totQtyPrice;
}
```

### 3. **delete($storeId)** - Delete Store
**Signature**: `delete($storeId): array`  
**Purpose**: Safely deletes a store after validation  
**Parameters**: 
- `$storeId` (int): Store ID to delete  
**Returns**: Array [message, status_code]

**Process Flow**:
```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│  Validate       │───▶│  Check Store    │───▶│  Delete Tree    │
│  Store ID       │    │  Dependencies   │    │  Elements       │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                        │                        │
         ▼                        ▼                        ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│  Status = 2     │    │ Has Products?   │    │  Delete Store   │
│  (Error)        │    │ Status = 1      │    │  Status = 0     │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

**Validation Logic**:
- Checks if store has products in storedetail table
- Prevents deletion if dependencies exist
- Removes accounting tree elements
- Returns appropriate status code

### 4. **edit()** - Load Store for Editing
**Signature**: `edit(): object`  
**Purpose**: Retrieves store data for editing form  
**Parameters**: Gets `storeId` from $_GET  
**Returns**: Store object with all properties

### 5. **update()** - Update Store
**Signature**: `update(): void`  
**Purpose**: Updates existing store record with new data  
**Parameters**: Gets data from $_POST array

**Process Flow**:
```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│  Get POST       │───▶│  Load Existing  │───▶│  Update Store   │
│  Data           │    │  Store          │    │  Properties     │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                │                        │
                                ▼                        ▼
                       ┌─────────────────┐    ┌─────────────────┐
                       │  Update Tree    │    │  Save to        │
                       │  Element Names  │    │  Database       │
                       └─────────────────┘    └─────────────────┘
```

**Key Logic**:
- Updates both main and intermediate tree element names
- Preserves accounting integration
- Updates modification user and date

### 6. **executeOperation()** - Batch Operations
**Signature**: `executeOperation(): void`  
**Purpose**: Performs batch operations on selected stores  
**Parameters**: Gets operation type and selected items from $_POST

**Supported Operations**:
1. **Hide Stores (1)**: Soft delete multiple stores
2. **Show Stores (2)**: Restore hidden stores  
3. **Delete Stores (3)**: Permanently delete stores

**Process Flow**:
```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│  Get Selected   │───▶│  Loop Through   │───▶│  Perform        │
│  Store IDs      │    │  Each Store     │    │  Operation      │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                │                        │
                                ▼                        ▼
                       ┌─────────────────┐    ┌─────────────────┐
                       │  Log Results    │    │  Display        │
                       │  Per Store      │    │  Summary        │
                       └─────────────────┘    └─────────────────┘
```

### 7. **tempdelete($storeId)** - Hide Store
**Signature**: `tempdelete($storeId): string`  
**Purpose**: Hides store (soft delete) by setting conditions = 1  
**Parameters**: 
- `$storeId` (int): Store ID to hide  
**Returns**: Success or error message

### 8. **returndelete($storeId)** - Restore Store
**Signature**: `returndelete($storeId): string`  
**Purpose**: Restores hidden store by setting conditions = 0  
**Parameters**: 
- `$storeId` (int): Store ID to restore  
**Returns**: Success or error message

---

## 🔄 Workflows

### Store Creation Workflow
```
┌──────────────────┐
│   User Access    │
│   Add Store      │
│     Form         │
└────────┬─────────┘
         ▼
┌──────────────────┐    ┌──────────────────┐
│   Validate       │───▶│   Create Store   │
│   Input Data     │    │   Record         │
└──────────────────┘    └────────┬─────────┘
                                 ▼
                        ┌──────────────────┐
                        │   Add Tree       │
                        │   Elements       │
                        └────────┬─────────┘
                                 ▼
                        ┌──────────────────┐
                        │   Update Store   │
                        │   With TreeIds   │
                        └────────┬─────────┘
                                 ▼
                        ┌──────────────────┐
                        │   Success        │
                        │   Response       │
                        └──────────────────┘
```

### Inventory Evaluation Workflow
```
┌──────────────────┐
│    Access        │
│  Store List      │
└────────┬─────────┘
         ▼
┌──────────────────┐    ┌──────────────────┐
│  Check Session   │───▶│  Load Program    │
│  Store Filter    │    │  Settings        │
└──────────────────┘    └────────┬─────────┘
                                 ▼
                        ┌──────────────────┐
                        │  Query Store     │
                        │  Evaluation Data │
                        └────────┬─────────┘
                                 ▼
                        ┌──────────────────┐
                        │  Apply Pricing   │
                        │  Method          │
                        └────────┬─────────┘
                                 ▼
                        ┌──────────────────┐
                        │  Display Store   │
                        │  With Values     │
                        └──────────────────┘
```

### Store Deletion Workflow
```
┌──────────────────┐
│   Select Store   │
│   For Deletion   │
└────────┬─────────┘
         ▼
┌──────────────────┐    ┌──────────────────┐
│  Validate Store  │───▶│  Check for       │
│  ID Exists       │    │  Dependencies    │
└──────────────────┘    └────────┬─────────┘
                                 ▼
                        ┌──────────────────┐
                        │  Dependencies    │◄──┐
                        │  Found?          │   │
                        └────────┬─────────┘   │
                                 ▼             │
                        ┌──────────────────┐   │
                        │  Delete Tree     │   │
                        │  Elements        │   │
                        └────────┬─────────┘   │
                                 ▼             │
                        ┌──────────────────┐   │
                        │  Delete Store    │   │
                        │  Record          │   │
                        └────────┬─────────┘   │
                                 ▼             │
                        ┌──────────────────┐   │
                        │  Success         │   │
                        │  Response        │   │
                        └──────────────────┘   │
                                               │
                        ┌──────────────────┐   │
                        │  Error: Cannot   │───┘
                        │  Delete Store    │
                        └──────────────────┘
```

---

## 🌐 URL Routes & Actions

| Route | Action | Purpose | Authentication |
|-------|--------|---------|----------------|
| `storeController.php` | Default (empty do) | Show add store form | Required |
| `?do=add` | `add()` | Process store creation | Required |
| `?do=show` | `show()` | Display store list with inventory | Required |
| `?do=edit&storeId={id}` | `edit()` | Show edit store form | Required |
| `?do=update` | `update()` | Process store update | Required |
| `?do=delete&storeId={id}` | `delete()` | Delete store permanently | Required |
| `?do=tempdelete&storeId={id}` | `tempdelete()` | Hide store (soft delete) | Required |
| `?do=returndelete&storeId={id}` | `returndelete()` | Restore hidden store | Required |
| `?do=executeOperation` | `executeOperation()` | Batch operations | Required |
| `?do=success` | N/A | Show success message | None |
| `?do=error` | N/A | Show error message | None |

### CURL Support
All main actions support CURL requests by setting `$_POST['curlpost'] = 1`:
- Returns JSON responses instead of redirects
- Includes status codes and messages
- Arabic and English error messages

---

## 🐛 Known Issues & Fixes

### 1. **Store Deletion Validation**
**Issue**: Need to check for inventory before deletion  
**Fix**: Validates storedetail records before allowing deletion

**Code Fix**:
```php
$storedetailData = $myStoredetailRecord->queryByStoreid($storeId);
if (count($storedetailData) <= 0) {
    // Safe to delete
} else {
    // Cannot delete - has inventory
}
```

### 2. **Inventory Evaluation Performance**
**Issue**: Multiple pricing calculations can be slow  
**Fix**: Use appropriate database indexes and optimize queries

### 3. **Tree Element Cleanup**
**Issue**: Orphaned tree elements when deletion fails  
**Fix**: Proper transaction handling and rollback

**Code Fix**:
```php
try {
    delTreeElementById($oldStore->treeId);
    delTreeElementById($oldStore->treeIdBetween);
    $myStoreRecord->delete($storeId);
} catch (Exception $e) {
    // Rollback tree deletions
}
```

---

## 🔒 Security & Permissions

### Authentication Requirements
- All operations require valid user session
- Authentication checked via `../public/authentication.php`
- User ID tracked in all operations

### Data Validation
- Store name validation (required, not empty)
- Store ID validation for operations
- Branch ID validation against existing branches
- User permission checks for store access

### SQL Injection Prevention
- Uses DAO pattern with prepared statements
- Input sanitization for all user data
- Parameter binding for all queries

---

## 🧪 Testing & Debugging

### Test Cases

#### Store Creation
1. **Valid Store Creation**
   - Input: Valid store name, description, branch
   - Expected: Store created, tree elements added, success response
   
2. **Duplicate Store Name**
   - Input: Existing store name
   - Expected: Validation error, no database changes

3. **Invalid Branch**
   - Input: Non-existent branch ID
   - Expected: Foreign key constraint error

#### Store Deletion
1. **Empty Store Deletion**
   - Input: Store with no inventory
   - Expected: Store and tree elements deleted, success response

2. **Store with Inventory**
   - Input: Store with existing storedetail records
   - Expected: Deletion prevented, error message

3. **Invalid Store ID**
   - Input: Non-existent store ID
   - Expected: Error response, no database changes

### Debugging Tips

1. **Check Tree Integration**:
```sql
SELECT * FROM accountstree WHERE id IN (SELECT treeId FROM store WHERE storeId = ?)
```

2. **Verify Store Dependencies**:
```sql
SELECT COUNT(*) FROM storedetail WHERE storeid = ?
```

3. **Monitor Inventory Values**:
```sql
SELECT * FROM store_evaluation_view WHERE storeId = ?
```

---

## ⚡ Performance Considerations

### Query Optimization
- **Store List**: Use pagination for large datasets
- **Inventory Evaluation**: Consider caching calculated values
- **Tree Operations**: Batch tree updates when possible

### Indexing Recommendations
```sql
-- Store table indexes
CREATE INDEX idx_store_conditions ON store(conditions);
CREATE INDEX idx_store_branch ON store(branchId);
CREATE INDEX idx_store_user ON store(userId);

-- Store detail indexes
CREATE INDEX idx_storedetail_store ON storedetail(storeid);
```

### Memory Management
- Avoid loading all store data at once
- Use streaming for large inventory reports
- Implement proper result set pagination

### Caching Strategy
- Cache program settings for inventory evaluation
- Store calculated inventory values temporarily
- Use session caching for user store permissions

---

## 📚 Related Documentation

- [Product Controller](productController.md) - Product management
- [Buy Bill Controller](buyBillController.md) - Purchase operations affecting store inventory
- [Sell Bill Controller](sellbillController.md) - Sales operations affecting store inventory
- [Store Detail Controller](#) - Detailed inventory operations
- [Branch Controller](#) - Branch management for store assignments
- [Accounting Integration](#) - Tree element management for stores

---

**Last Updated**: December 19, 2024  
**Version**: 1.0  
**Maintainer**: ERP Development Team