<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  Joomla_Administrator_Component
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

namespace Mefi\Component\MefisAssetBridge\Administrator\Traits\CoreBridge;

defined('_JEXEC') or die;
\defined('JPATH_PUBLIC') || \define('JPATH_PUBLIC', JPATH_ROOT);
use Joomla\CMS\Uri\Uri;

trait CoreCacheTrait
{
    /**
     * Initialise cache directory paths and URLs.
     * Called from AssetsController::__construct() before CoreCache is instantiated.
     */
    protected function initCoreCache(): void
    {
        // define caches
        $this->MEDIA_CACHE_DIR = JPATH_PUBLIC . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'plg_system_mefisassetbridge' . DIRECTORY_SEPARATOR . 'cache';
        $this->MEDIA_CACHE_DIR_PREVIEW = JPATH_PUBLIC . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'plg_system_mefisassetbridge' . DIRECTORY_SEPARATOR . 'preview_cache';

        $p = explode('/', rtrim(Uri::base(), '/'));
        foreach($p as $i => $part) {
            if($part === 'administrator') {
                unset($p[$i]);
                break;
            }
        }
        $baseUrl = implode('/', $p) . '/';
        $this->MEDIA_CACHE_URL = $baseUrl.'/media/plg_system_mefisassetbridge/cache';
        $this->MEDIA_CACHE_URL_PREVIEW = $baseUrl.'/media/plg_system_mefisassetbridge/preview_cache';

        // Ensure index.php guards exist in media root, cache/, and preview_cache/.
        // Runs on every API call; file_exists() guard keeps it cheap.
        $mediaRoot = \JPATH_PUBLIC . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'plg_system_mefisassetbridge';
        foreach ([$mediaRoot, $this->MEDIA_CACHE_DIR, $this->MEDIA_CACHE_DIR_PREVIEW] as $_dir) {
            if (is_dir($_dir) && !file_exists($_dir . DIRECTORY_SEPARATOR . 'index.php')) {
                @file_put_contents($_dir . DIRECTORY_SEPARATOR . 'index.php', '<?php http_response_code(403); exit;' . PHP_EOL);
            }
        }
    }

    /** @deprecated Use $this->coreCache->isOlderThan() instead */
    protected function coreIsCacheOlderThan(string $userUuid, string $fileName, int $timestamp): bool
    {
        $filePath = $this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid . DIRECTORY_SEPARATOR . $fileName;
        if (file_exists($filePath)) {
            return filemtime($filePath) < $timestamp;
        }
        return true;
    }

    /** @deprecated Use $this->coreCache->get() instead */
    protected function coreGetFromCache(string $userUuid, string $fileName, int $timestamp = null): ?string
    {
        if($timestamp !== null) {
            if ($this->coreIsCacheOlderThan($userUuid, $fileName, $timestamp)) {
                return null;
            }
        }
        $filePath = $this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid . DIRECTORY_SEPARATOR . $fileName;
        if (file_exists($filePath)) {
            return file_get_contents($filePath);
        }
        return null;
    }

    /** @deprecated Use $this->coreCache->set() instead */
    protected function coreSetToCache(string $userUuid, string $content, string $fileName): bool
    {
        try {
            if (!is_dir($this->MEDIA_CACHE_DIR)) {
                mkdir($this->MEDIA_CACHE_DIR, 0755, true);
            }

            if(!is_dir($this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid)) {
                mkdir($this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid, 0755, true);
            }

            file_put_contents($this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid . DIRECTORY_SEPARATOR . $fileName, $content);
            return true;

        } catch (\Throwable $th) {
            return false;
        }
    }

    /** @deprecated Use $this->coreCache->setFromFile() instead */
    protected function coreSetFileToCache(string $userUuid, string $filePathSource, string $fileName): bool
    {
        try {
            if(file_exists($filePathSource) === false) {
                return false;
            }
            if (!is_dir($this->MEDIA_CACHE_DIR)) {
                mkdir($this->MEDIA_CACHE_DIR, 0755, true);
            }

            if(!is_dir($this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid)) {
                mkdir($this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid, 0755, true);
            }

            copy($filePathSource, $this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid . DIRECTORY_SEPARATOR . $fileName);
            return true;

        } catch (\Throwable $th) {
            return false;
        }
    }

    /**
     * Delete a cached file
     *
     * @param string $userUuid User UUID
     * @param string $fileName File name (e.g., 'assetUuid.thumb')
     * @return bool True on success, false on failure
     */
    /** @deprecated Use $this->coreCache->delete() instead */
    protected function coreDeleteFromCache(string $userUuid, string $fileName): bool
    {
        try {
            $filePath = $this->MEDIA_CACHE_DIR . DIRECTORY_SEPARATOR . $userUuid . DIRECTORY_SEPARATOR . $fileName;
            if (file_exists($filePath)) {
                return unlink($filePath);
            }
            return true; // File doesn't exist, consider it already deleted
        } catch (\Throwable $th) {
            return false;
        }
    }

    /**
     * Delete all cached files for an asset (thumb + data)
     *
     * @param string $userUuid User UUID
     * @param string $assetUuid Asset UUID
     * @return bool True if at least one file was deleted or didn't exist
     */
    /** @deprecated Use $this->coreCache->deleteAsset() instead */
    protected function coreDeleteAssetCache(string $userUuid, string $assetUuid): bool
    {
        $thumbDeleted = $this->coreDeleteFromCache($userUuid, $assetUuid . '.thumb');
        $dataDeleted = $this->coreDeleteFromCache($userUuid, $assetUuid . '.data');

        return $thumbDeleted && $dataDeleted;
    }
}