<?php

namespace pictpostpersonal\controller\page;

use pictpostpersonal\controller\ControllerBase;

use pictpostpersonal\Environment;
use pictpostpersonal\PPPDateTime;
use pictpostpersonal\Request;
use pictpostpersonal\Result;
use pictpostpersonal\model\Article;
use pictpostpersonal\model\Template;
use pictpostpersonal\NoSixTemplate2;

use const pictpostpersonal\TAGCLOUD_PATH;

class EditPage extends ControllerBase
{
    private $article_data;

    /**
     * 記事の新規作成ページを表示する
     *
     * @param Request $req
     * 
     * @return result
     * 
     */
    function create(Request $req): result
    {
        if ($req->getArgs('id') != '') {
            //ID指定されている場合は編集モード
            $result = new Result();
            $result->redirect_action = 'page\EditPage:edit';
            return $result;
        }

        //新規モードのため全て空にする

        $created_at = PPPDateTime::Date('Y-m-d H:i:s');

        //タイトルテンプレートを解決
        $now_date = PPPDateTime::Date('Y-m-d');
        $now_y =    PPPDateTime::Date('Y');
        $now_m =    PPPDateTime::Date('m');
        $now_d =    PPPDateTime::Date('d');
        $now_time = PPPDateTime::Date('H:i:s');
        $title = str_replace('%date%', $now_date, str_replace('%datetime%', $created_at, $this->setting->getValue('title_template', '')));
        $title = str_replace('%yyyy%', $now_y, $title);
        $title = str_replace('%mm%', $now_m, $title);
        $title = str_replace('%dd%', $now_d, $title);
        $title = str_replace('%time%', $now_time, $title);

        $comment = $this->setting->getValue('contents_template', '');
        $tags = '';

        $use_user_thumbnail = '';
        $thumbnail = '';
        $nsfw = '';
        $pin = '';
        $hidden_at_list = '';

        $views = '-';
        $like = '-';

        $alt_url = '';

        $sort = '1';

        $article_style = $this->setting->getValue('default_style', 0);
        $previews = '';
        if ($req->getArgs('status', '') == 'draft') {
            $status = 1;
        } else {
            $status =  $this->setting->getValue('default_status', 0);
        }

        //インデックス編集モードか判定
        $edit_index = $req->getArgs('edit_index', false);

        $templates = new Template($this->db);
        $exif_templates = $templates->getTemplates('exif');
        if (count($exif_templates) == 1) {
            $exif_template = $exif_templates[0]['value'];
        } else {
            $exif_template = '';
        }
        $share_templates = $templates->getTemplates('share_link');
        $share_template_list = '';
        $share_template_obj = [];
        foreach ($share_templates as $item) {
            $share_template_obj[] = [
                'title' => h($item['value']),
                'action' => h($item['option1'] . $item['option2'])
            ];
        }
        if ($share_template_list == "") {
            $share_template_list = "[]";
        }

        //UIレンダリング
        if ($edit_index) {
            $article_style = '9999';
            $template = new NoSixTemplate2('template2_edit_index.php', ['./core/templates_sys'], './env/template_cache');
        } else {
            $template = new NoSixTemplate2('template2_edit.php', ['./core/templates_sys'], './env/template_cache');
        }

        self::setSiteData($template); //サイト関連情報を設定
        self::setSystemArea($template); //管理系情報を設定
        $template->set_data('list_thumbs', $this->listThumbnails('./user_resource/thumbnails'));
        //ページ関連情報を設定
        $template->set_data_h('page_description', '');
        $template->set_data_h('page_keywords', '');
        $template->set_data_h('page_author', $this->setting->GetValue('display_name', ''));
        $template->set_data_h('page_title', '投稿画面 - ' . $this->setting->GetValue('site_title', '新しいサイト'));
        $template->set_data('page_url', '');
        $template->set_data('mode', 'create');

        $template->set_data('max_send_size',  $this->getMaxUploadSize());

        //コンテンツデータを設定
        $template->set_data('type', 0);
        $template->set_data('article_status', $status);
        $template->set_data('guest_mode', 'false');
        $template->set_data('article_id', '');
        $template->set_data_h('created_at', $created_at);
        $template->set_data_h('title', $title);
        $template->set_data_h('contents', $comment);
        $template->set_data_h('tags', $tags);
        $template->set_data('use_user_thumbnail', $use_user_thumbnail);
        $template->set_data('thumbnail', $thumbnail);
        $template->set_data('nsfw', $nsfw);
        $template->set_data('pin', $pin);
        $template->set_data('hidden', $hidden_at_list);
        $template->set_data('views', $views);
        $template->set_data('like', $like);
        $template->set_data_h('alt_url', $alt_url);
        $template->set_data_h('sort', $sort);
        $template->set_data('article_style', $article_style);
        $template->set_data('previews', $previews);
        $template->set_data('submit_title', '投稿');

        $template->set_data('post_mode_class', '');
        $template->set_data('edit_mode_class', 'hide');
        $template->set_data('exif_template', $exif_template);
        $template->set_data('share_templates', $share_template_list);
        $template->set_data('use_clipboard', $this->setting->getValue('sns_share_use_clipboard', false));

        $template->set_data('resize_border', $this->setting->getValue('resize_border', 1980));
        $template->set_data('use_rnd_filename', $this->setting->getValue('use_rnd_filename', false) ? 'true' : 'false');

        //タグクラウド定義を読み込み
        require_once(TAGCLOUD_PATH);
        $template->set_data('tagcloud_nolink_sys', $tagcloud_nolink_sys ?? '');
        $template->set_data('tagcloud_nolink_more_sys', $tagcloud_nolink_more_sus ?? '');
        $template->set_data('tagcloud_nolink', $tagcloud_nolink ?? '');
        $template->set_data('tagcloud_nolink_more', $tagcloud_nolink_more ?? '');


        //デモ動作
        $template->set_data('demo_mode', Environment::isDemoMode());

        $output = $template->getString();

        $result = new result();
        $result->output = $output;
        return $result;
    }

    /**
     * 記事の編集ページを表示する
     *
     * @param Request $req  引数「id」に記事IDを指定する
     * 
     * @return Result
     * 
     */
    function edit(Request $req): Result
    {
        $site_url = SITE_URL;
        $id = $req->getArgs('id');
        $article = new Article($this->db, $this->setting);
        $values = $article->getById($id, true);

        if ($values == null) {
            //記事が存在しない場合は404エラー
            $result = new result();
            $result->status = 404;
            return $result;
        }

        if (Environment::isDemoMode() && $values['type'] != 0) {
            //デモ版ではIndex,NSFW,Entryの編集不可
            $result = new result();
            $result->status = 404;
            return $result;
        }

        $editing_values = $article->getEditingById($id);
        $editing = false;

        if ($editing_values == null) {
            $created_at = $values['created_at'];
            $title = $values['title'];
            $comment = $values['contents'];
            $tags = trim($values['tags']);
            $use_user_thumbnail = '';
            $thumbnail = $values['thumbnail'];
            $nsfw = $values['nsfw'] ? 'checked' : '';
            $pin = $values['pin'] ? 'checked' : '';
            $use_alt_ogimage = $values['use_alt_ogimage'] ? 'checked' : '';
            $hidden_at_list = $values['hidden_at_list'] ? 'checked' : '';
            $views = $values['views'];
            $like = $values['like'];
            $alt_url = $values['alt_url'];
            $sort = $values['sort'];
            $article_style = $values['style'];
            $status = $values['status'];
            $type = $values['type'];
        } else {
            //編集中データ(途中保存)を読み込む
            $created_at = $editing_values['created_at'];
            $title = $editing_values['title'];
            $comment = $editing_values['contents'];
            $tags = trim($editing_values['tags']);
            $use_user_thumbnail = '';
            $thumbnail = $editing_values['thumbnail'];
            $nsfw = $editing_values['nsfw'] ? 'checked' : '';
            $pin = $editing_values['pin'] ? 'checked' : '';
            $use_alt_ogimage = $editing_values['use_alt_ogimage'] ? 'checked' : '';
            $hidden_at_list = $editing_values['hidden_at_list'] ? 'checked' : '';
            $views = $editing_values['views'];
            $like = $editing_values['like'];
            $alt_url = $editing_values['alt_url'];
            $sort = $editing_values['sort'];
            $article_style = $editing_values['style'];
            $status = $editing_values['status'];
            $type = $editing_values['type'];
            $editing = true;
        }

        $previews = '';
        foreach ($values['media'] as $media) {
            $thumb = h($media['thumb_l_name']);
            $sub_dir = h($media['sub_dir']);
            $media_type = h($media['type']);
            $media_comment = h($media['comment'] ?? '');
            $previews = $previews . "<li class=\"preview_item\" data-id=\"{$media['id']}\" data-subdir=\"{$sub_dir}\" data-filename=\"{$media['file_name']}\" onMouseUp=\"imageTap(event)\" onTouchEnd=\"imageTap(event)\">" .
                "<img  data-type=\"$media_type\" class=\"preview_item_image\" id=\"preview_{$media['file_name']}\" src=\"$site_url/images/{$sub_dir}{$thumb}\" >" .
                "<button type=\"button\" onClick=\"addRemoveImageList(event)\" class=\"delete_button\">×</button>" .
                "<i class=\"fa-regular fa-circle-right mover\" style=\"display:none\"></i><i class=\"fa-regular fa-circle-left movel\"  style=\"display:none\"></i><i class=\"fa-solid fa-bars contextmenubutton\"  style=\"display:none\"></i>" .
                "<input type=\"hidden\" class=\"image_comment\"  name=\"updated_image_comments[]\" value=\"{$media_comment}\">" .
                "<input type=\"hidden\" class=\"image_sort\" name=\"updated_image_sort[]\" value=\"{$media['sort']}\">" .
                "<input type=\"hidden\" name=\"updated_image_id[]\" value=\"{$media['id']}\"></li>";
        }

        $templates = new Template($this->db);
        $exif_templates = $templates->getTemplates('exif');
        if (count($exif_templates) == 1) {
            $exif_template = $exif_templates[0]['value'];
        } else {
            $exif_template = '';
        }
        $share_templates = $templates->getTemplates('share_link');
        $share_template_list = '';
        $share_template_obj = [];
        foreach ($share_templates as $item) {
            $share_template_obj[] = [
                'title' => h($item['value']),
                'action' => h($item['option1'] . $item['option2'])
            ];
        }
        $share_template_list = json_encode($share_template_obj);
        if ($share_template_list == "") {
            $share_template_list = "[]";
        }


        //UIレンダリング
        //インデックス編集モードか判定
        $edit_index = $req->getArgs('edit_index', false);
        if ($edit_index || $type >= 2) {
            $article_style = '9999';
            $template = new NoSixTemplate2('template2_edit.php', ['./core/templates_sys'], './env/template_cache');
        } else {
            $template = new NoSixTemplate2('template2_edit.php', ['./core/templates_sys'], './env/template_cache');
        }
        self::setSiteData($template); //サイト関連情報を設定
        self::setSystemArea($template); //管理系情報を設定
        $template->set_data('list_thumbs', $this->listThumbnails('./user_resource/thumbnails'));
        //ページ関連情報を設定
        $template->set_data('page_description', '');
        $template->set_data('page_keywords', '');
        $template->set_data('page_author', $this->setting->GetValue('display_name', ''));
        $template->set_data('page_title', '投稿画面 - ' . $this->setting->GetValue('site_title', '新しいサイト'));
        $template->set_data('page_url', '');
        $template->set_Data('log_page_url', Environment::getLogUrlBase() . $id);
        $template->set_data('mode', 'edit');

        $template->set_data('resize_border', $this->setting->getValue('resize_border', '1980'));
        $template->set_data('use_rnd_filename', $this->setting->getValue('use_rnd_filename', true));

        $template->set_data('max_send_size',  $this->getMaxUploadSize());

        //編集中データを表示中か否か
        $template->set_data('artice_editing', $editing);

        //コンテンツデータを設定
        $template->set_data('guest_mode', 'false');
        $template->set_data('article_id', $id);
        $template->set_data('article_status', $status);
        $template->set_data('type', $type);
        $template->set_data('created_at', h($created_at));
        $template->set_data('title', h($title));
        $template->set_data('contents', h($comment));
        $template->set_data('tags', h($tags));
        $template->set_data('use_user_thumbnail', $use_user_thumbnail);
        $template->set_data('thumbnail', $thumbnail);
        $template->set_data('nsfw', $nsfw);
        $template->set_data('pin', $pin);
        $template->set_data('hidden', $hidden_at_list);
        $template->set_data('use_alt_ogimage', $use_alt_ogimage);
        $template->set_data('views', $views);
        $template->set_data('like', $like);
        $template->set_data('alt_url', h($alt_url));
        $template->set_data('sort', h($sort));
        $template->set_data('article_style', $article_style);
        $template->set_data('previews', '');
        $template->set_data('previews', $previews);

        $template->set_data('submit_title', '更新');

        $template->set_data('post_mode_class', 'hide');
        $template->set_data('edit_mode_class', '');
        $template->set_data('exif_template', $exif_template);
        $template->set_data('share_templates', $share_template_list);
        $template->set_data('use_clipboard', $this->setting->getValue('sns_share_use_clipboard', false));

        //タグクラウド定義を読み込み
        require_once(TAGCLOUD_PATH);
        $template->set_data('tagcloud_nolink_sys', $tagcloud_nolink_sys ?? '');
        $template->set_data('tagcloud_nolink_more_sys', $tagcloud_nolink_more_sus ?? '');
        $template->set_data('tagcloud_nolink', $tagcloud_nolink ?? '');
        $template->set_data('tagcloud_nolink_more', $tagcloud_nolink_more ?? '');

        //デモ動作
        $template->set_data('demo_mode', Environment::isDemoMode());

        $output = $template->getString();

        $result = new result();
        $result->output = $output;
        return $result;
    }
    //最大アップロード可能ファイルサイズ取得(バイト単位)
    function getMaxUploadSize()
    {
        $limit_max = ($this->ini_get_bytes('post_max_size') < $this->ini_get_bytes('upload_max_filesize')) ? 'post_max_size' : 'upload_max_filesize';
        $limit_max = ($this->ini_get_bytes($limit_max) < $this->ini_get_bytes('memory_limit')) ?  $limit_max : 'memory_limit';

        return $this->ini_get_bytes($limit_max);
    }
    //設定オプションを整数表現に変換して返す
    function ini_get_bytes($var_name)
    {
        $val = ini_get($var_name);
        $last = strtolower(substr($val,  -1));
        $val = (int)($val);
        switch ($last) {
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }

        return $val;
    }

    function listThumbnails(string $directory): array
    {
        if (!is_dir($directory)) {
            return [];
        }
        $contents = scandir($directory);
        $thumbs = [];
        foreach ($contents as $item) {
            // . や .. を除外し、サブディレクトリのみを取得
            if ($item !== '.' && $item !== '..' && $item !== 'index.html'  && is_file($directory . DIRECTORY_SEPARATOR . $item)) {
                $thumbs[] = $item;
            }
        }
        return $thumbs;
    }
}
