<?php

namespace pictpostpersonal\controller\page;

use pictpostpersonal\controller\ControllerBase;

use pictpostpersonal\Request;
use pictpostpersonal\Result;

class ThemePage extends ControllerBase
{

    /**
     * /theme/file_path のリクエストについて、指定されたテーマに基づき
     * /env/themes/file_path のファイルを返す
     *
     * @param request $req
     * 
     * @return Result|null
     * 
     */
    public function getFile(Request $req): ?Result
    {
        $theme = $this->setting->getValue('theme', '');
        if ($theme === '') {
            $theme_path = './system_resouce/def_theme';
        } else {
            $theme_path = "./themes/$theme";
        }
        $file_path = str_replace('/theme/', '', $req->url);
        $file_path = str_replace('./', '', $file_path);
        $base_dir = realpath($theme_path);
        $file_path = realpath("$theme_path/$file_path");

        if ($file_path === false || strpos($file_path, $base_dir) !== 0) {
            return new Result(403);
        }
        if (strpos($file_path, '..') !== false) {
            return new Result(403);
        }
        if (!file_exists($file_path)) {
            return new Result(404);
        }

        //ファイル実体を返す
        if (str_ends_with('.css', $file_path)) {
            $mime_type = 'text/css';
        } else {
            $mime_type = mime_content_type($file_path);
        }
        header("Content-Type: $mime_type");
        readfile($file_path);

        return null;
    }

    public function getResourceFile(Request $req): ?Result
    {
        $theme = $this->setting->getValue('theme', '');
        if ($theme == '') {
            $theme_path = './system_resource';
        } else {
            $theme_path = "./user_resource/themes_resource/$theme";
        }
        $file_path = str_replace('/theme/resource', '', $req->url);
        $file_path = str_replace('./', '', $file_path);
        $file_path = "$theme_path/$file_path";
        if (!file_exists($file_path)) {
            $theme = $this->setting->getValue('theme', '');
            if ($theme == '') {
                $theme_path = './templates/resource';
            } else {
                $theme_path = "./env/$theme/resource";
            }
            $file_path = str_replace('/theme/resource', '', $req->url);
            $file_path = str_replace('./', '', $file_path);
            $file_path = "$theme_path/$file_path";
            if (!file_exists($file_path)) {
                return new Result(404);
            }
        }

        //ファイル実体を返す
        if (str_ends_with('.css', $file_path)) {
            $mime_type = 'text/css';
        } else {
            $mime_type = mime_content_type($file_path);
        }
        header("Content-Type: $mime_type");
        readfile($file_path);

        return null;
    }
}
