<?php

namespace pictpostpersonal\controller\api;

use pictpostpersonal\controller\ControllerBase;

use Exception;
use pictpostpersonal\Result;
use pictpostpersonal\Request;
use pictpostpersonal\model\Message;

/**
 * メッセージ操作にかかわるAPIを提供するクラス
 */
class MessageApi extends ControllerBase
{

    private function validate($req)
    {
        $title = htmlspecialchars($req->getArgs('tittle', ''));
        $name = htmlspecialchars($req->getArgs('name', 'unknown'));
        $email = htmlspecialchars($req->getArgs('email', ''));
        $return_message = htmlspecialchars($req->getArgs('return_message', ''));
        $message = trim(htmlspecialchars($req->getArgs('comment', '')));

        //自動入力排除用
        if ($title != '') {
            die('{"status":"error","message":"送信できません"}');
        }

        //送信元確認用
        $from = $_SERVER['HTTP_REFERER'] ?? '';
        if ($from == '') {
            die('{"status":"error","message":"送信できません"}');
        }

        // SPAMチェック
        include('./env/spamfilter.php');

        return [$name, $email, $message, $return_message];
    }

    private function crawlerResult()
    {
        //クローラー判定
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $is_crawler = preg_match('/bot|crawl|slurp|spider/i', $user_agent);
        if ($is_crawler) {
            //とりあえず成功ということにしとく
            echo '{"status":"success"}';
            exit();
        }
    }
    /**
     * メッセージを作成/更新する
     *
     * @param Request $req
     *
     * @return Result
     *
     */
    function create(Request $req): Result
    {
        $this->crawlerResult();

        [$name, $email, $message, $return_message] = $this->validate($req);

        if ($message == '') {
            $result = new Result();
            $result->mime_type = 'application/json';
            $result->output = "{\"status\":\"error\", \"message\":\"コメントを入力してください\"}";
            return $result;
        }

        try {
            $article = new Message($this->db, $this->setting);
            $id = $article->create(-1, $name, $email, $message);
            $result = new Result();
            $result->mime_type = 'application/json';
            $result->output = "{\"status\":\"success\", \"id\":\"$id\", \"message\":\"$return_message\"}";
            return $result;
        } catch (Exception $ex) {
            $result = new Result();
            $result->mime_type = 'application/json';
            $result->output = "{\"status\":\"error\", \"message\":\"{$ex->getMessage()}\"}";
            return $result;
        }
    }

    function read(Request $req): Result
    {
        try {
            $article = new Message($this->db, $this->setting);
            $article->read($req->getArgs('id'), true);

            $result = new Result();
            $result->mime_type = 'application/json';
            $result->output = "{\"status\":\"success\", \"message\":\"success\"}";
            return $result;
        } catch (Exception $ex) {
            $result = new Result();
            $result->mime_type = 'application/json';
            $result->output = "{\"status\":\"error\", \"message\":\"{$ex->getMessage()}\"}";
            return $result;
        }
    }

    /**
     * メッセージを削除する
     *
     * @param Request $req
     *
     * @return Result
     *
     */
    function delete(Request $req): Result
    {
        $this->crawlerResult();

        try {
            $messages = new Message($this->db, $this->setting);
            $id = $messages->deletes([$req->getArgs('id')]);

            $result = new Result();
            $result->mime_type = 'application/json';
            $result->output = "{\"status\":\"success\", \"id\":\"$id\", \"message\":\"success\"}";
            return $result;
        } catch (Exception $ex) {
            $result = new Result();
            $result->mime_type = 'application/json';
            $result->output = "{\"status\":\"error\", \"message\":\"{$ex->getMessage()}\"}";
            return $result;
        }
    }
}
