# Reset Discount Controller Documentation

**File**: `/controllers/resetdiscount.php`  
**Purpose**: Utility controller for fixing restaurant discount calculations on specific dates  
**Last Updated**: December 20, 2024  
**Total Functions**: 2  
**Lines of Code**: ~60

---

## 📋 Overview

The Reset Discount Controller is a specialized utility for correcting restaurant discount calculations. It handles:
- Restaurant-specific discount correction operations
- Date-based discount fixes
- YouTube tutorial link display
- Administrative discount maintenance
- Batch discount recalculation
- Error correction for discount misapplications

### Primary Functions
- [x] Fix restaurant discounts for specific dates
- [x] Display helpful tutorial videos
- [x] Administrative interface for discount maintenance
- [x] Batch correction of discount calculations
- [x] User permission validation
- [x] Results reporting and feedback

### Related Controllers
- [sellbillController.php](sellbillController.md) - Sales bill operations
- [restaurantController.php](#) - Restaurant operations
- [discountController.php](#) - General discount management
- [billController.php](#) - Bill management

---

## 🗄️ Database Tables

### Primary Tables (Indirect Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **sellbill** | Sales bills with discount data | sellbillid, sellbilldiscount, sellbilldiscounttype, sellbilldate, sellbilltotalbill |
| **youtubelink** | Tutorial video links | youtubelinkid, title, url, category |

### Referenced Tables (via Extended DAO)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **sellbilldetail** | Bill line items | sellbilldetailid, sellbillid, sellbilldetailprice, sellbilldetaildiscount |
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue |
| **user** | System users | userid, username, usergroupid |
| **usergroup** | User permissions | usergroupid, groupname, permissions |

---

## 🔑 Key Functions

### 1. **Default Action (empty $do)** - Discount Fix Interface
**Location**: Line 39  
**Purpose**: Display interface for fixing restaurant discounts with date selection

**Process Flow**:
1. Check user authentication and permissions
2. Process discount fix if date provided
3. Load YouTube tutorial links for assistance
4. Display fix interface template
5. Show results if operation performed

**Function Logic**:
```php
$billdate = filter_input(INPUT_POST, "billdate");
if (isset($billdate) && !empty($billdate)) {
    $rowsAffected = $sellbillEX->fixDiscountRestaurantFatma($billdate);
    $smarty->assign("rowsAffected", $rowsAffected);
}
```

**Features**:
- Date input validation
- Results feedback display
- Tutorial integration
- Permission checking

---

### 2. **fixDiscountRestaurantFatma()** - Core Fix Logic
**Location**: Called from SellbillMySqlExtDAO  
**Purpose**: Execute restaurant-specific discount corrections

**Process Flow**:
1. Query sales bills for specified date
2. Identify discount calculation errors
3. Apply corrected discount formulas
4. Update affected records
5. Return count of rows modified

**Expected Corrections**:
- Percentage vs fixed amount discount corrections
- Tax calculation adjustments
- Total bill amount recalculations
- Discount type standardization

---

## 🔄 Workflows

### Workflow 1: Discount Correction Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Access Discount Fix Tool               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. User Authentication                                     │
│     - Verify user login                                     │
│     - Check administrative permissions                      │
│     - Load user session data                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Fix Interface                                   │
│     - Show date selection form                              │
│     - Display YouTube tutorial links                        │
│     - Present previous operation results                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. User Selects Date                                       │
│     - Choose specific bill date                             │
│     - Submit form for processing                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Execute Discount Fix                                    │
│     - Call fixDiscountRestaurantFatma()                     │
│     - Process all bills for selected date                   │
│     - Apply discount corrections                            │
│     - Count affected records                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Display Results                                         │
│     - Show number of rows affected                          │
│     - Confirm completion status                             │
│     - Provide success feedback                              │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Show discount fix interface |

### Form Parameters
**POST Data**:
- `billdate` - Target date for discount corrections (YYYY-MM-DD)

---

## 🔒 Security & Permissions

### Access Control
```php
include_once("../public/authentication.php");
```

**Security Features**:
- User authentication required
- Session validation
- Input filtering with `filter_input(INPUT_POST)`
- Protected administrative function

### Permission Requirements
- Must be logged in user
- Administrative access level typically required
- Date modification permissions needed

---

## 🧮 Discount Fix Logic

### Restaurant-Specific Corrections
The `fixDiscountRestaurantFatma()` function likely corrects:

1. **Discount Type Mismatches**:
   ```sql
   -- Fix percentage discounts calculated as fixed amounts
   UPDATE sellbill SET 
   sellbillaftertotalbill = sellbilltotalbill - (sellbilltotalbill * sellbilldiscount / 100)
   WHERE sellbilldiscounttype = 0 AND sellbilldate = ?
   ```

2. **Fixed Amount Corrections**:
   ```sql
   -- Fix fixed discounts
   UPDATE sellbill SET 
   sellbillaftertotalbill = sellbilltotalbill - sellbilldiscount
   WHERE sellbilldiscounttype = 1 AND sellbilldate = ?
   ```

3. **Tax Recalculations**:
   ```sql
   -- Recalculate tax on corrected amounts
   UPDATE sellbill SET 
   tax_amount = (sellbillaftertotalbill * tax_rate / 100)
   WHERE sellbilldate = ?
   ```

---

## 📊 Performance Considerations

### Batch Operation Impact
- Processes all bills for specified date
- May affect hundreds or thousands of records
- Database locks during updates
- Potential timeout for large date ranges

### Optimization Strategies
1. **Index Usage**:
   - Ensure index on `sellbill(sellbilldate)`
   - Consider composite index for discount operations

2. **Batch Size Management**:
   - Process in smaller batches if needed
   - Add progress feedback for large operations

---

## 🐛 Common Issues & Troubleshooting

### 1. **No Rows Affected**
**Issue**: Fix operation returns 0 rows affected  
**Possible Causes**:
- No bills exist for selected date
- Bills already have correct discount calculations
- Date format incorrect

**Debug Steps**:
```sql
-- Check if bills exist for date
SELECT COUNT(*) FROM sellbill WHERE DATE(sellbilldate) = 'YYYY-MM-DD';

-- Check discount types and values
SELECT sellbillid, sellbilldiscount, sellbilldiscounttype, 
       sellbilltotalbill, sellbillaftertotalbill 
FROM sellbill WHERE DATE(sellbilldate) = 'YYYY-MM-DD';
```

### 2. **Timeout Errors**
**Issue**: Operation times out on large datasets  
**Solution**: Process smaller date ranges or implement batch processing

### 3. **Permission Denied**
**Issue**: User cannot access fix function  
**Solution**: Verify user has administrative permissions

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Discount Fix
```
1. Create test bills with incorrect discounts
2. Run fix for specific date
3. Verify discount calculations corrected
4. Check row count matches expected
```

### Test Case 2: Edge Cases
```
1. Test with date having no bills
2. Test with already correct discounts
3. Test with invalid date formats
4. Verify appropriate responses
```

### Test Case 3: Performance Testing
```
1. Create large number of bills for test date
2. Monitor execution time
3. Verify all records processed
4. Check database performance impact
```

---

## 💡 Tutorial Integration

### YouTube Links Feature
```php
$youtubes = $youtubeLinkDAO->queryAll();
$smarty->assign("youtubes", $youtubes);
```

**Purpose**:
- Provide instructional videos
- Guide users through discount fix process
- Document common scenarios and solutions

**Display Options**:
- Video thumbnails
- Tutorial titles
- Category-based organization
- Direct video links

---

## 📚 Business Context

### When to Use This Tool
1. **After System Updates**: When discount calculation logic changes
2. **Data Migration**: After importing bills with incorrect discounts
3. **Error Correction**: When bugs in discount calculation are discovered
4. **Audit Compliance**: To ensure consistent discount application
5. **Restaurant Specific Issues**: Address unique restaurant discount scenarios

### Typical Scenarios
- **Percentage vs Fixed Mix-ups**: Bills with wrong discount type
- **Tax Base Errors**: Tax calculated on wrong amount
- **Rounding Issues**: Discount calculations with precision problems
- **Multiple Discount Conflicts**: Bills with conflicting discount rules

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [sellbillController.md](sellbillController.md) - Sales operations
- [SellbillMySqlExtDAO.class.php](#) - Extended discount functions
- [Restaurant Operations Guide](#) - Restaurant-specific features

---

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