<?php

namespace SGC\eGiftCard\Hooks\Handler;

defined('ABSPATH') || exit; // Prevent direct file access.

/**
 * Class CleanupHandler
 *
 * Handles plugin scheduled tasks.
 */
class CleanupHandler
{
    /**
     * Delete uploaded files that are older than a month.
     */
    public static function may_be_delete_uploaded_files()
    {
        $upload_dir = wp_upload_dir();
        $upload_path = $upload_dir['basedir'] . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID . '/' . '_temp';

        // Check if the upload directory exists
        if (is_dir($upload_path)) {
            // Get all files in the upload directory
            $files = scandir($upload_path);
            $deleted_files_count = 0;

            // Loop through each file
            foreach ($files as $file) {
                // Skip the '.' and '..' directories
                if ($file === '.' || $file === '..') {
                    continue;
                }

                // Get the file's last modified date
                $file_path = $upload_path . '/' . $file;
                $last_modified = new \DateTime();
                $last_modified->setTimestamp(filemtime($file_path));
                
                // Check if the file is older than a month
                if ($last_modified < (new \DateTime())->modify('-1 month')) {
                    // Attempt to delete the file
                    if (wp_delete_file($file_path)) {
                        $deleted_files_count++;
                    }
                }
            }
        }
    }
}
