# 404 Error Fixes - Dilrukshi Tex POS System

## ⚠️ LATEST FIX: Intermittent 404 Errors (December 29, 2025)

**PROBLEM**: System sometimes gets 404 errors when navigating from dashboard, but works after refresh.

**ROOT CAUSE**: Relative path redirects in navigation files (e.g., `header('Location: products.php')`) resolve inconsistently depending on browser context, referrer, and cache state.

**SOLUTION**: Converted all navigation redirects to absolute paths (e.g., `header('Location: /malshanlast/products/products.php')`).

**FILES FIXED**: products/index.php, dashboard.php, index.php, login.php, customers/view_history.php

**STATUS**: ✅ RESOLVED - Navigation should now be consistent with no intermittent 404 errors.

📄 **Full details**: See [INTERMITTENT_404_FIX.md](INTERMITTENT_404_FIX.md)

---

## Issues Identified and Fixed

### 1. **.htaccess Overly Aggressive Rules** ✅ FIXED
**Problem:** The `.htaccess` file was blocking legitimate user requests due to overly broad bot detection rules.
- Original rule blocked ANY user agent containing "bot", "crawler", or "spider"
- This could block legitimate browser features and extensions

**Solution:**
- Updated rules to only block known malicious bots (masscan, scrapy, nikto, sqlmap)
- Narrowed down the pattern matching to be more specific
- Changed query parameter blocking to only catch SQL injection attempts

### 2. **API Authentication Missing** ✅ FIXED
**Problem:** `api/low_stock.php` lacked proper authentication and error handling
- Could cause 401 errors when session expired
- No proper error responses

**Solution:**
- Added session validation at the beginning of the file
- Returns proper HTTP 401 status code for unauthorized access
- Added try-catch block for database errors
- Returns JSON error responses

### 3. **Relative Path Issues in AJAX Calls** ✅ FIXED
**Problem:** Dashboard was using relative paths for API calls
- `fetch('api/enhanced_stats.php')` could fail depending on current page location
- No retry logic on failure
- Poor error handling for expired sessions

**Solution:**
- Changed all fetch calls to use absolute paths from web root: `/malshanlast/api/...`
- Added credentials: 'same-origin' to maintain session cookies
- Added HTTP status checking (401 redirects to login)
- Added automatic retry logic with 2-second delay
- Better error messages in console

### 4. **Session Expiration Handling** ✅ FIXED
**Problem:** When sessions expired, AJAX calls would fail silently or cause confusing redirects

**Solution in `auth.php`:**
- Detect AJAX requests via HTTP_X_REQUESTED_WITH header
- Return JSON response with 401 status for AJAX calls
- Properly handle API endpoint authentication
- Calculate relative paths based on directory depth for regular page redirects

### 5. **Products Page Redirect** ✅ FIXED
**Problem:** Relative path redirect in `products/index.php` causing **intermittent 404 errors**
- Browser interprets relative path `products.php` inconsistently
- Depending on referrer/navigation context, redirect sometimes resolves to wrong path
- Works after refresh because browser context changes

**Solution:**
- Changed from relative path `products.php` to absolute path `/malshanlast/products/products.php`
- Absolute paths ensure consistent resolution regardless of navigation context
- Added file existence check before redirecting
- Provides meaningful error message if products.php is missing
- Uses proper exit() after header redirect

**This was the PRIMARY cause of "works on refresh" 404 errors**

## Files Modified

1. `.htaccess` - Updated security rules
2. `api/low_stock.php` - Added authentication and error handling
3. `api/enhanced_stats.php` - Improved error handling and HTTP status codes
4. `dashboard.php` - Fixed fetch API calls to use absolute paths
5. `auth.php` - Better session expiration handling for AJAX and API requests
6. `products/index.php` - **CRITICAL FIX**: Changed relative redirect to absolute path to prevent intermittent 404 errors

## New Files Created

1. `debug_404.php` - Custom 404 error page that logs errors for debugging
2. `404_errors.log` - Will be created automatically to track 404 errors

## How to Monitor 404 Errors

1. Check the `404_errors.log` file in the root directory
2. The custom 404 page shows technical details to help diagnose issues
3. All 404 errors are logged with:
   - Timestamp
   - Requested URL
   - Referring page
   - User agent
   - User ID (if logged in)

## Testing Checklist

- [x] Dashboard loads without errors
- [x] Adding products works correctly
- [x] Navigating to dashboard after adding products
- [x] API calls return proper data
- [x] Session expiration redirects properly
- [x] Low stock modal loads correctly
- [x] Stats refresh every 30 seconds

## Common Causes of 404 Errors (Now Fixed)

1. ~~Expired sessions causing redirect loops~~
2. ~~Relative paths failing in subdirectories~~
3. ~~Bot detection blocking legitimate requests~~
4. ~~Missing authentication checks on API endpoints~~
5. ~~Improper error handling in fetch calls~~

## Prevention Tips

1. Always use absolute paths for API calls: `/malshanlast/api/endpoint.php`
2. Include credentials in fetch calls: `credentials: 'same-origin'`
3. Check HTTP status codes before parsing JSON responses
4. Add try-catch blocks around all database queries
5. Log errors for later review

## If 404 Errors Still Occur

1. Check `404_errors.log` for patterns
2. Review browser console for specific error messages
3. Check Apache error log: `C:\xampp\apache\logs\error.log`
4. Verify session is active: Check browser cookies
5. Clear browser cache and try again

## Browser Console Debugging

Open browser developer tools (F12) and look for:
- Red network errors (failed requests)
- Console error messages
- Status codes (401 = unauthorized, 404 = not found, 500 = server error)

## Contact Support

If issues persist:
1. Capture the exact error from `404_errors.log`
2. Note the steps to reproduce
3. Check browser console for additional details
4. Review the timestamp when error occurred
