<?php

namespace DZ\ImageShield\XF\Admin\Controller;

use DZ\ImageShield\Shield;
use DZ\ImageShield\TemplateHelper;
use DZ\ImageShield\Service\OverlayRenderer;
use XF;
use XF\Http\Upload;
use XF\Mvc\Reply\AbstractReply;

class ToolsController extends XFCP_ToolsController
{
    public function actionShieldImage(): AbstractReply
    {
        $this->assertPostOnly();

        /** @var Upload|false $file */
        $file = $this->request()->getFile('file', false);
        if (!$file) {
            // Try alternative field name used in template
            $file = $this->request()->getFile('__file', false);
        }
        if (!$file) {
            return $this->error(XF::phrase('uploaded_file_must_be_valid_image'));
        }

        $file->setImageOptimize(false);
        $file->requireImage();
        $file->setAllowedExtensions(['png']);

        if (!$file->isValid($errors)) {
            return $this->error($errors);
        }

        $output = Shield::storeOverlayImage($file);

        $message = $this->message(XF::phrase('changes_saved'));
        $message->setJsonParam('shield_image', TemplateHelper::getImageEncoded($output));

        return $message;
    }

    /**
     * Generate a font preview image.
     */
    public function actionShieldFontPreview(): AbstractReply
    {
        $fontPath = $this->filter('font', 'str');
        $previewText = $this->filter('text', 'str') ?: 'AaBbCc 123';

        // Validate font path is within our fonts directory
        $fontsDir = XF::getAddOnDirectory() . '/DZ/ImageShield/fonts';
        
        if (empty($fontPath)) {
            // Use default font
            $fontPath = $fontsDir . '/Arial.ttf';
        }

        // Security check - ensure font is in our fonts directory
        $realFontsDir = realpath($fontsDir);
        $realFontPath = realpath($fontPath);
        
        if ($realFontPath === false || $realFontsDir === false || strpos($realFontPath, $realFontsDir) !== 0) {
            return $this->message('Invalid font path');
        }

        if (!file_exists($fontPath)) {
            return $this->message('Font file not found');
        }

        // Generate preview image
        OverlayRenderer::setFontPath($fontPath);
        $previewFile = OverlayRenderer::fromText($previewText, 24, '#f0f0f0', '#333333', 10);
        
        $imageData = file_get_contents($previewFile);
        $base64 = 'data:image/png;base64,' . base64_encode($imageData);

        $reply = $this->message('OK');
        $reply->setJsonParam('preview', $base64);
        return $reply;
    }
}
