#!/usr/bin/env php
<?php
/**
 * Cleanup Old Uploads
 * Removes temporary files and orphaned case attachments
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/upload-handler.php';

$uploader = getUploadHandler();
$logFile = __DIR__ . '/../logs/cleanup.log';

function logMessage($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
    echo $message . "\n";
}

logMessage("=== Starting uploads cleanup ===");

// Clean temporary files older than 24 hours
$tempCleaned = $uploader->cleanTemp(24);
logMessage("Cleaned $tempCleaned temporary files");

// Clean orphaned case attachments (files without database record)
$pdo = getDB();
$uploadDir = __DIR__ . '/../assets/uploads/cases/';

if (is_dir($uploadDir)) {
    $caseDirs = glob($uploadDir . '*', GLOB_ONLYDIR);
    $orphanedCount = 0;
    
    foreach ($caseDirs as $caseDir) {
        $caseId = basename($caseDir);
        
        // Check if case exists
        $stmt = $pdo->prepare("SELECT id FROM cases WHERE id = ?");
        $stmt->execute([$caseId]);
        
        if (!$stmt->fetch()) {
            // Case doesn't exist, delete entire directory
            $files = glob($caseDir . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                    $orphanedCount++;
                }
            }
            rmdir($caseDir);
            logMessage("Deleted orphaned case directory: $caseId ($orphanedCount files)");
        } else {
            // Check for files without database records
            $dbFiles = $pdo->prepare("SELECT filename FROM case_attachments WHERE case_id = ?");
            $dbFiles->execute([$caseId]);
            $dbFilenames = $dbFiles->fetchAll(PDO::FETCH_COLUMN);
            
            $diskFiles = glob($caseDir . '/*');
            foreach ($diskFiles as $file) {
                $filename = basename($file);
                if (!in_array($filename, $dbFilenames)) {
                    unlink($file);
                    $orphanedCount++;
                    logMessage("Deleted orphaned file: $caseId/$filename");
                }
            }
        }
    }
    
    logMessage("Cleaned $orphanedCount orphaned files");
}

// Get final statistics
$stats = $uploader->getStats();
logMessage("=== Upload Statistics ===");
logMessage("Cases: {$stats['cases']['file_count']} files, {$stats['cases']['total_size_formatted']}");
logMessage("Profiles: {$stats['profiles']['file_count']} files, {$stats['profiles']['total_size_formatted']}");
logMessage("Temp: {$stats['temp']['file_count']} files, {$stats['temp']['total_size_formatted']}");

logMessage("=== Uploads cleanup completed ===");