#!/usr/bin/env php
<?php
/**
 * Backup cleanup script - manages local storage and removes old backups
 * Should be run periodically via cron to maintain storage health
 */

require_once(__DIR__ . '/../configs/config.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once(__DIR__ . '/../libs/BackupLocalStorage.php');

use WHPBackup\BackupLocalStorage;

function log_message($message) {
    $timestamp = date('Y-m-d H:i:s');
    echo "[$timestamp] $message\n";
    error_log("[$timestamp] BackupCleanup: $message");
}

function cleanup_local_storage() {
    try {
        $mysql = new mysqlmgmt();
        $db = $mysql->getMySQLConnection();
        $db->exec("USE whp");

        $localStorage = new BackupLocalStorage($db);

        log_message("Starting local storage cleanup...");

        // Get current space info
        $spaceInfo = $localStorage->getSpaceInfo();
        log_message("Current storage usage: " .
                   number_format($spaceInfo['current_size_gb'], 2) . " GB / " .
                   $spaceInfo['max_size_gb'] . " GB (" .
                   number_format($spaceInfo['usage_percentage'], 1) . "%)");

        // Perform cleanup based on configured policy
        $results = $localStorage->performCleanup();

        if ($results['files_deleted'] > 0) {
            log_message("Cleanup completed: " .
                       $results['files_deleted'] . " files deleted, " .
                       number_format($results['bytes_freed'] / 1024 / 1024, 2) . " MB freed");

            if (!empty($results['errors'])) {
                log_message("Cleanup errors encountered:");
                foreach ($results['errors'] as $error) {
                    log_message("  - $error");
                }
            }
        } else {
            log_message("No cleanup needed");
        }

        // Get updated space info
        $spaceInfo = $localStorage->getSpaceInfo();
        log_message("After cleanup: " .
                   number_format($spaceInfo['current_size_gb'], 2) . " GB / " .
                   $spaceInfo['max_size_gb'] . " GB (" .
                   number_format($spaceInfo['usage_percentage'], 1) . "%)");

        return $results;

    } catch (Exception $e) {
        log_message("Error during local storage cleanup: " . $e->getMessage());
        return ['files_deleted' => 0, 'bytes_freed' => 0, 'errors' => [$e->getMessage()]];
    }
}

function cleanup_old_upload_queue_entries() {
    try {
        $mysql = new mysqlmgmt();
        $db = $mysql->getMySQLConnection();
        $db->exec("USE whp");

        log_message("Cleaning up old upload queue entries...");

        // Remove completed/failed entries older than 30 days
        $stmt = $db->prepare("
            DELETE FROM backup_upload_queue
            WHERE status IN ('completed', 'failed', 'cancelled')
            AND completed_at < DATE_SUB(NOW(), INTERVAL 30 DAY)
        ");
        $stmt->execute();
        $deleted = $stmt->rowCount();

        if ($deleted > 0) {
            log_message("Removed $deleted old upload queue entries");
        }

        return $deleted;

    } catch (Exception $e) {
        log_message("Error cleaning up upload queue: " . $e->getMessage());
        return 0;
    }
}

function cleanup_orphaned_local_files() {
    try {
        $mysql = new mysqlmgmt();
        $db = $mysql->getMySQLConnection();
        $db->exec("USE whp");

        log_message("Checking for orphaned local backup files...");

        $localStorage = new BackupLocalStorage($db);
        $basePath = '/docker/backups/local'; // This should match the config

        $orphaned = 0;
        $freed = 0;

        $directories = ['temp', 'ready', 'failed'];
        foreach ($directories as $dir) {
            $dirPath = $basePath . '/' . $dir;
            if (!is_dir($dirPath)) {
                continue;
            }

            $files = glob($dirPath . '/*');
            foreach ($files as $file) {
                if (!is_file($file)) {
                    continue;
                }

                $filename = basename($file);

                // Check if this file is referenced in backup_history
                $stmt = $db->prepare("
                    SELECT COUNT(*) FROM backup_history
                    WHERE local_path = ? OR local_path LIKE ?
                ");
                $stmt->execute([$file, '%' . $filename]);
                $referenced = $stmt->fetchColumn();

                if ($referenced == 0) {
                    // Check if it's old enough to be considered orphaned (24 hours)
                    if (filemtime($file) < time() - 86400) {
                        $fileSize = filesize($file);
                        if (unlink($file)) {
                            $orphaned++;
                            $freed += $fileSize;
                            log_message("Removed orphaned file: $filename");
                        } else {
                            log_message("Failed to remove orphaned file: $filename");
                        }
                    }
                }
            }
        }

        if ($orphaned > 0) {
            log_message("Cleaned up $orphaned orphaned files, freed " .
                       number_format($freed / 1024 / 1024, 2) . " MB");
        } else {
            log_message("No orphaned files found");
        }

        return ['files' => $orphaned, 'bytes' => $freed];

    } catch (Exception $e) {
        log_message("Error checking for orphaned files: " . $e->getMessage());
        return ['files' => 0, 'bytes' => 0];
    }
}

function update_storage_statistics() {
    try {
        $mysql = new mysqlmgmt();
        $db = $mysql->getMySQLConnection();
        $db->exec("USE whp");

        $localStorage = new BackupLocalStorage($db);
        $actualUsage = $localStorage->getCurrentUsage();

        // Update the database with actual usage
        $stmt = $db->prepare("
            UPDATE backup_local_storage
            SET current_size_bytes = ?
            WHERE is_active = 1
        ");
        $stmt->execute([$actualUsage]);

        log_message("Updated storage statistics: " .
                   number_format($actualUsage / 1024 / 1024, 2) . " MB actual usage");

    } catch (Exception $e) {
        log_message("Error updating storage statistics: " . $e->getMessage());
    }
}

// Main execution
if (php_sapi_name() === 'cli') {
    log_message("Starting backup cleanup process");

    try {
        // 1. Clean up local storage based on policy
        $cleanup_results = cleanup_local_storage();

        // 2. Clean up old upload queue entries
        cleanup_old_upload_queue_entries();

        // 3. Remove orphaned local files
        cleanup_orphaned_local_files();

        // 4. Update storage statistics
        update_storage_statistics();

        log_message("Backup cleanup process completed successfully");

        // Exit with status code based on results
        exit(empty($cleanup_results['errors']) ? 0 : 1);

    } catch (Exception $e) {
        log_message("Fatal error in backup cleanup: " . $e->getMessage());
        exit(1);
    }
} else {
    echo "This script can only be run from command line\n";
    exit(1);
}