<?php

namespace WPIS;

class Logger {

    const LOG_DIR = 'wp-immo-sync';
    const EXPIRATION_DAYS = 30;
    const MAX_SIZE = 10 * 1024 * 1024; // 10MB

    private static string $cacheDirectory;

    private static function init(): void {
        if (!isset(self::$cacheDirectory)) {
            date_default_timezone_set('Europe/Brussels');

            $uploadDir = wp_get_upload_dir();
            self::$cacheDirectory = $uploadDir['basedir'] . DIRECTORY_SEPARATOR . self::LOG_DIR;

            if (!is_dir(self::$cacheDirectory)) {
                mkdir(self::$cacheDirectory, 0775, true);
            }

            self::autoCleanLogs();
        }
    }


    public static function log($name, $message): void {
        self::init();

        $logFile = self::$cacheDirectory . DIRECTORY_SEPARATOR . $name . '.log';

        if (!file_exists($logFile)) {
            touch($logFile);
        }

        $date = (new \DateTime())->format("Y-m-d H:i:s");

        $messages = is_array($message) ? $message : [$message];
        $logEntries = '';

        foreach ($messages as $line) {
            $logEntries .= "\r\n{$date} {$line}";
        }

        file_put_contents($logFile, $logEntries, FILE_APPEND);
    }

    private static function autoCleanLogs(): void {
        $logFiles = glob(self::$cacheDirectory . DIRECTORY_SEPARATOR . '*.log');

        foreach ($logFiles as $file) {
            if (filemtime($file) < time() - self::EXPIRATION_DAYS * 86400 || filesize($file) > self::MAX_SIZE) {
                unlink($file);
            }
        }
    }
}