<?php

namespace Eadesigndev\GLS\Cron;

use Magento\Framework\App\Filesystem\DirectoryList;
use Psr\Log\LoggerInterface;

class CleanupAwb
{
    const GLS_SAVE_AWB_PATH = 'awbs/gls/';
    const DAYS_TO_KEEP = 30;

    /**
     * @var DirectoryList
     */
    private $directoryList;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param DirectoryList $directoryList
     * @param LoggerInterface $logger
     */
    public function __construct(
        DirectoryList $directoryList,
        LoggerInterface $logger
    ) {
        $this->directoryList = $directoryList;
        $this->logger = $logger;
    }

    /**
     * Delete GLS AWB files older than 30 days
     * Runs daily at 02:00 AM
     *
     * @return void
     */
    public function execute()
    {
        try {
            $varPath = $this->directoryList->getPath(DirectoryList::VAR_DIR);
            $awbPath = $varPath . '/' . self::GLS_SAVE_AWB_PATH;

            if (!file_exists($awbPath) || !is_dir($awbPath)) {
                $this->logger->info('GLS AWB Cleanup: Directory does not exist: ' . $awbPath);
                return;
            }

            $cutoffTime = time() - (self::DAYS_TO_KEEP * 24 * 60 * 60);
            $deletedCount = 0;
            $errorCount = 0;

            $files = scandir($awbPath);
            foreach ($files as $file) {
                if ($file === '.' || $file === '..') {
                    continue;
                }

                $filePath = $awbPath . $file;

                if (!is_file($filePath) || pathinfo($filePath, PATHINFO_EXTENSION) !== 'pdf') {
                    continue;
                }

                $fileModifiedTime = filemtime($filePath);

                if ($fileModifiedTime < $cutoffTime) {
                    if (unlink($filePath)) {
                        $deletedCount++;
                        $this->logger->info('GLS AWB Cleanup: Deleted old AWB file: ' . $file);
                    } else {
                        $errorCount++;
                        $this->logger->error('GLS AWB Cleanup: Failed to delete file: ' . $file);
                    }
                }
            }

            $this->logger->info(sprintf(
                'GLS AWB Cleanup completed: %d files deleted, %d errors',
                $deletedCount,
                $errorCount
            ));

        } catch (\Exception $e) {
            $this->logger->error('GLS AWB Cleanup error: ' . $e->getMessage());
        }
    }
}
