# Notice Path Auto-Fixer

## Overview

This auto-updater fixes notice attachment paths by:
1. Finding notices with incorrect or missing attachment paths
2. Searching for matching files in the correct directory (`/php/uploads/notices/`)
3. Using intelligent filename matching with similarity scoring
4. Automatically updating the database with correct paths

## How It Works

### Matching Algorithm

The script uses a multi-level matching system:

1. **Exact Match (100%)** - Filename matches exactly
2. **Timestamp Match (90%)** - Same timestamp prefix (e.g., `1770114560_...`)
3. **Filename Match (95%)** - Same filename without extension
4. **Partial Match (80%)** - Filename contains or is contained in the other
5. **No Match (< 80%)** - Marked as not found

Only matches with **80% or higher** are automatically updated.

## Usage

### Option 1: Web Interface (Recommended)

Access the admin panel:
```
/php/admin/fix_notice_paths.php
```

**Requirements:**
- Must be logged in as admin
- Click "Run Auto-Fixer" button
- View detailed results with color-coded status

### Option 2: Command Line

Run from the root directory:
```bash
php fix_notice_paths_cli.php
```

**Output:**
- Shows each notice being processed
- Displays match scores
- Prints summary at the end

### Option 3: API Script

Call the script directly:
```bash
curl http://your-domain/php/scripts/fix_notice_paths.php
```

Returns JSON response with results.

## Results Status

### ✓ CORRECT
- Path is already in `uploads/notices/`
- File exists in the correct location
- No action needed

### ✓ FIXED
- Path was incorrect or missing
- Matching file found in correct directory
- Database updated automatically
- Shows match score (80-100%)

### ✗ NOT_FOUND
- Path was incorrect or missing
- No matching file found in correct directory
- Best match score shown (if any)
- Manual intervention may be required

## Example Scenarios

### Scenario 1: Exact Match
```
Database: uploads/KKCPNotdpdfs/1770114560.pdf
File exists: uploads/notices/1770114560.pdf
Result: FIXED (100% match)
```

### Scenario 2: Timestamp Match
```
Database: uploads/old/1770114560_document.pdf
File exists: uploads/notices/1770114560_report.pdf
Result: FIXED (90% match)
```

### Scenario 3: Filename Match
```
Database: uploads/temp/salary_report.pdf
File exists: uploads/notices/salary_report.pdf
Result: FIXED (95% match)
```

### Scenario 4: No Match
```
Database: uploads/archive/missing_file.pdf
File exists: (not found in uploads/notices/)
Result: NOT_FOUND (0% match)
```

## Database Updates

The script updates the `notices` table:

```sql
UPDATE notices 
SET AttachmentUrl = 'uploads/notices/correct_filename.pdf' 
WHERE Id = ?
```

Only updates when match score >= 80%.

## Safety Features

✅ **Read-only by default** - Web interface shows results before updating
✅ **Minimum match threshold** - Only 80%+ matches are updated
✅ **Logging** - All changes are logged
✅ **Reversible** - Can manually update database if needed
✅ **No file deletion** - Only updates database paths

## Troubleshooting

### No matches found
- Check if files actually exist in `/php/uploads/notices/`
- Verify file permissions (should be readable)
- Check filename format and extensions

### Low match scores
- Files may have been renamed
- Timestamps may not match
- Consider manual review of unmatched notices

### Database not updating
- Check database permissions
- Verify user has UPDATE privilege on notices table
- Check error logs for SQL errors

## Performance

- Scans all notices: O(n)
- Scans all files in directory: O(m)
- Matching algorithm: O(n × m)
- Typical runtime: < 1 second for 100 notices

## Files Involved

- `/php/scripts/fix_notice_paths.php` - Core script (API)
- `/php/admin/fix_notice_paths.php` - Web interface
- `/fix_notice_paths_cli.php` - Command-line interface
- `/php/uploads/notices/` - Target directory for attachments

## Current Status (March 15, 2026)

### Critical Discovery
- **543 notices have broken attachment URLs** pointing to `/img/attachments/Attachment_XXX.pdf`
- **All files are missing** - not in `/img/attachments/`, not in `/php/uploads/notices/`, nowhere on server
- **Multiple notices share the same file** - indicates data integrity issue
- **Auto-fixer cannot work** because files don't exist to match against

### Recommended Action
The auto-fixer approach won't work because the files are completely missing. Instead:

1. **Run cleanup tool** to remove broken URLs from database
   - Tool: `/php/admin/cleanup_notices_simple.php`
   - Action: Clears all 543 broken attachment URLs
   - Result: Notices display normally without attachment links

2. **Investigate data integrity** to understand why multiple notices share files
   - Tool: `/php/admin/investigate_duplicate_attachments.php`
   - Action: Identifies which notices share attachments
   - Result: Determines if issue is intentional or bug

3. **Implement prevention** to ensure proper file handling for future uploads
   - Use: `/php/includes/FileUpload.php`
   - Action: Validates uploads and prevents duplicates
   - Result: No more broken attachments

## Next Steps

1. **Execute cleanup** - Remove broken URLs from database
2. **Investigate** - Understand data integrity issue
3. **Implement prevention** - Ensure proper file handling for future uploads
4. **Monitor** - Watch for broken links in future

## Manual Fixes

If auto-fixer can't find a match, manually update:

```sql
UPDATE notices 
SET AttachmentUrl = 'uploads/notices/correct_filename.pdf' 
WHERE Id = 123;
```

Or move the file to the correct directory:
```bash
mv /php/uploads/old_location/file.pdf /php/uploads/notices/file.pdf
```

## Automation

To run automatically on a schedule, add to cron:

```bash
# Run daily at 2 AM
0 2 * * * cd /path/to/kkcp && php fix_notice_paths_cli.php >> logs/notice_fixer.log 2>&1
```

## Support

For issues or questions:
1. Check the detailed results in the web interface
2. Review error logs in `/logs/` directory
3. Verify file permissions and database access
4. Check that files actually exist in `/php/uploads/notices/`
