<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../config/database.php';

// Debug-Logging
function debugLog($message) {
    $logFile = '../logs/file_cleanup_debug.log';
    $timestamp = date('Y-m-d H:i:s');
    if (!file_exists(dirname($logFile))) {
        mkdir(dirname($logFile), 0755, true);
    }
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND | LOCK_EX);
}

try {
    $data = json_decode(file_get_contents('php://input'), true);
    $action = $data['action'] ?? '';
    $appointmentId = $data['appointment_id'] ?? null;

    debugLog("Action: $action, Appointment ID: $appointmentId");

    $uploadDir = '../uploads/tire_offers/';
    
    if ($action === 'cleanup_appointment_files') {
        if (!$appointmentId) {
            echo json_encode(['success' => false, 'error' => 'Appointment ID is required.']);
            exit;
        }
        
        $filesToDelete = [
            $uploadDir . 'offer_customer_' . $appointmentId . '.html',
            $uploadDir . 'offer_merged_' . $appointmentId . '.html',
            $uploadDir . 'offer_uploaded_' . $appointmentId . '.html'
        ];
        
        // Find uploaded files with timestamp
        $uploadedFiles = glob($uploadDir . 'uploaded_' . $appointmentId . '_*.html');
        $filesToDelete = array_merge($filesToDelete, $uploadedFiles);
        
        $deletedFiles = [];
        $errors = [];
        
        foreach ($filesToDelete as $file) {
            if (file_exists($file)) {
                if (unlink($file)) {
                    $deletedFiles[] = basename($file);
                    debugLog("Deleted file: " . basename($file));
                } else {
                    $errors[] = "Could not delete: " . basename($file);
                }
            }
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Files cleaned up successfully.',
            'deleted_files' => $deletedFiles,
            'errors' => $errors
        ]);

    } elseif ($action === 'cleanup_old_files') {
        // Clean up files older than 7 days
        $cutoffTime = time() - (7 * 24 * 60 * 60); // 7 days ago
        $deletedFiles = [];
        $errors = [];
        
        $files = glob($uploadDir . '*');
        foreach ($files as $file) {
            if (is_file($file) && filemtime($file) < $cutoffTime) {
                if (unlink($file)) {
                    $deletedFiles[] = basename($file);
                    debugLog("Deleted old file: " . basename($file));
                } else {
                    $errors[] = "Could not delete old file: " . basename($file);
                }
            }
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Old files cleaned up successfully.',
            'deleted_files' => $deletedFiles,
            'errors' => $errors
        ]);

    } elseif ($action === 'get_file_info') {
        if (!$appointmentId) {
            echo json_encode(['success' => false, 'error' => 'Appointment ID is required.']);
            exit;
        }
        
        $files = [
            'customer' => $uploadDir . 'offer_customer_' . $appointmentId . '.html',
            'merged' => $uploadDir . 'offer_merged_' . $appointmentId . '.html',
            'uploaded' => $uploadDir . 'offer_uploaded_' . $appointmentId . '.html'
        ];
        
        $fileInfo = [];
        foreach ($files as $type => $path) {
            if (file_exists($path)) {
                $fileInfo[$type] = [
                    'exists' => true,
                    'filename' => basename($path),
                    'size' => filesize($path),
                    'modified' => date('Y-m-d H:i:s', filemtime($path)),
                    'url' => '../uploads/tire_offers/' . basename($path)
                ];
            } else {
                $fileInfo[$type] = ['exists' => false];
            }
        }
        
        echo json_encode([
            'success' => true,
            'files' => $fileInfo
        ]);

    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid action.']);
    }

} catch (Exception $e) {
    debugLog("Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'File cleanup failed: ' . $e->getMessage()]);
}
?>
