<?php

namespace pictpostpersonal\controller\page;

use pictpostpersonal\controller\ControllerBase;
use pictpostpersonal\Request;
use pictpostpersonal\Result;
use pictpostpersonal\FlashMessage;
use pictpostpersonal\Logger;
use pictpostpersonal\Environment;
use pictpostpersonal\model\SystemActivity;
use pictpostpersonal\NoSixTemplate2;
use pictpostpersonal\CsrfUtility;
use pictpostpersonal\service\ThemeService;
use pictpostpersonal\Utility;

class LoginPage extends ControllerBase
{
    /**
     * ログインページ表示
     */
    function show(Request $req)
    {
        //すでにログイン済みの場合はコンソールへリダイレクト
        if ($this->auth->isLogin()) {
            Result::redirect(BASE_URL . '/console');
        }

        $user = '';
        $password = '';
        $demo_msg = '';
        if (Environment::isDemoMode()) {
            $user = 'sample';
            $password = 'Sample12345';
            $demo_msg = 'デモ版です。このままログインできます。';
        }

        $flash = FlashMessage::getMessage('login', ['message' => '', 'url' => '']);
        $message = $flash['message'];
        $redirect_url =  $flash['url'];;

        $template = ThemeService::getThemeTemplate('template2_login.php', $this->db, $this->setting);
        //$template = new NoSixTemplate2("template2_login.php", ['./core/templates_sys'], "./env/template_cache");
        self::setSiteData($template); //サイト関連情報を設定
        self::setSystemArea($template); //管理系情報を設定

        //CSRF対策トークン埋め込み
        $template->set_data('csrf', CsrfUtility::createCSRFTokenHtml());

        $template->set_data('message', $message);
        $template->set_data('redirect_url', $redirect_url);
        $template->set_data('user', $user);
        $template->set_data('password', $password);
        $template->set_data('demo_message', $demo_msg);

        return new Result(200, $template->getString());
    }

    function login(Request $req)
    {
        Utility::SessionStart(true); //セッションID再生成
        $username = $req->getArgs('username', '');
        $password = $req->getArgs('password', '');
        $redirect_url = $req->getArgs('redirect_url', '');

        $activity = new SystemActivity($this->db);
        $retry_cnt = $activity->getActivityCount(SystemActivity::SYSTEM_ACTION_LOGIN_FAIL, 30);
        if (!Environment::isDemoMode() && $retry_cnt >= 30) {
            //30分以内に20回以上ログイン試行があった場合、ログイン試行せずにエラーとする
            FlashMessage::setMessage('login', ['message' => 'ログイン試行回数が規定回数を超えました。一定時間ロック状態になります。', 'url' => '']);
            $login_text = htmlspecialchars($username);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
            $user_agent = htmlspecialchars($_SERVER['HTTP_USER_AGENT']) ?? 'unknown';
            $this->log->log("LoginReject try-id:$login_text ipaddress:$ip userAgent:$user_agent", Logger::LOG_LEVEL_SECURITY);
            Result::redirect(BASE_URL . '/login');
        }

        $login_check = $this->auth->login($username, $password);
        if ($login_check) {
            $activity->create('login');

            if (
                $redirect_url !== '' && strpos($redirect_url, '/') === 0
                && strpos($redirect_url, '//') !== 0
            ) {
                Result::redirect(BASE_URL . $redirect_url);
            } else {
                Result::redirect(BASE_URL . '/console');
            }
        } else {
            $activity->create('login_error');
            FlashMessage::setMessage('login', ['message' => 'IDまたはパスワードが正しくありません', 'url' => '']);

            $login_text = htmlspecialchars($username);
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
            $user_agent = htmlspecialchars($_SERVER['HTTP_USER_AGENT']) ?? 'unknown';

            $this->log->log("LoginReject try-id:$login_text ipaddress:$ip userAgent:$user_agent", Logger::LOG_LEVEL_SECURITY);
            Result::redirect(BASE_URL . '/login');
        }
    }

    function logout(Request $req)
    {
        $this->auth->logout();
        Utility::clearSession();
        Result::redirect(SITE_URL);
    }
}
