<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Config;
use App\Models\User;
use App\Models\Movie\MovieReview;
use App\Models\DTO\ResponseData;
use App\Rules\DeniedEmail;
use App\Rules\SpecialCharLength;
use App\Rules\UppercaseLength;
use App\Rules\NumberLength;
use App\Rules\AllowNickname;
use Exception;

class ApiController extends Controller
{
    public function __construct()
    {

    }

    /**
     * 로그인 확인
     */
    public function loginCheck(): int
    {
        return intval(auth()->check());
    }

    /**
     * 금지 단어 확인
     */
    public function filterSpamKeyword(Request $request, ResponseData $response): ResponseData
    {
        $subject = $request->input('subject');
        $content = $request->input('content');
        $response->subject = "";
        $response->content = "";
        $spamWord = explode(',', trim((new Config)->item("spam_word")));

        if ($spamWord) {
            for ($i = 0; $i < count($spamWord); $i++) {
                $str = trim($spamWord[$i]);
                if ($subject) {
                    $pos = stripos($subject, $str);
                    if ($pos !== false) {
                        $response->subject = $str;
                        break;
                    }
                }
                if ($content) {
                    $pos = stripos($content, $str);
                    if ($pos !== false) {
                        $response->content = $str;
                        break;
                    }
                }
            }
        }

        return $response;
    }

    /**
     * 중복 이메일 여부
     */
    public function isEmailAble(Request $request): bool
    {
        try {

            $email = $request->input('email');
            if (!$email) {
                throw new Exception;
            }

            // 중복 여부
            if ((new User)->where('email', $email)->exists()) {
                throw new Exception;
            }

            // 유효성 확인
            if (!(new DeniedEmail)->passes(null, $email)) {
                throw new Exception;
            }

            return true;
        } catch (Exception) {
            return false;
        }
    }

    /**
     * 비밀번호 유효성 검사
     */
    public function isPasswordAble(Request $request): bool
    {
        try {

            $password = $request->input('password');
            if (!$password) {
                throw new Exception;
            }

            // 유효성 확인
            if (!(new SpecialCharLength)->passes(null, $password)) {
                throw new Exception;
            }

            if (!(new UppercaseLength)->passes(null, $password)) {
                throw new Exception;
            }

            if (!(new NumberLength)->passes(null, $password)) {
                throw new Exception;
            }

            return true;
        } catch (Exception) {
            return false;
        }
    }

    /**
     * 중복 닉네임 여부
     */
    public function isNicknameAble(Request $request): bool
    {
        try {

            $nickname = $request->input('nickname');
            if (!$nickname) {
                throw new Exception;
            }

            // 중복 여부
            if (
                (new User)->where([
                    ['nickname', $nickname],
                    ['user_id', UID]
                ])->exists()
            ) {
                throw new Exception;
            }

            // 유효성 확인
            if (!(new AllowNickname)->passes(null, $nickname)) {
                throw new Exception;
            }

            return true;
        } catch (Exception) {
            return false;
        }
    }

    /**
     * 정기 비밀번호 변경 다음에 하기
     */
    public function passwordCampaignSkip()
    {
        return (new User)->where('id', UID)->update([
            'password_updated_at' => now()
        ]);
    }

    /**
     * TinyMCE 에디터 이미지 첨부 화면
     */
    public function uploader()
    {
        return view('component.uploader');
    }

    /**
     * 영화 평점 및 후기
     * @method GET
     * @see /api/moview/review/latest/{movieCd}
     */
    public function movieReviewLatest(string $base64, MovieReview $movieReviewModel)
    {
        try {

            if(!$base64) {
                throw new Exception('잘못된 접근입니다. [1]');
            }

            $movieCd = base64_decode($base64);

            if(!$movieCd) {
                throw new Exception('잘못된 접근입니다. [2]');
            }

            $latest = $movieReviewModel->latest($movieCd, UID);

            if($latest->total > 0) {
                foreach($latest->list as &$row) {
                    $length = strlen($row->sid);
                    $row->owner = ($row->name . '(' . Str::mask($row->sid, '*', intval($length / 2), $length) . ')');
                    $row->rate = round($row->rate, 2);
                    $row->createdAt = date('Y.m.d', strtotime($row->created_at));
                }
            }

            return view(layout('movie.review.latest'), [
                'latest' => $latest
            ]);

        }catch(Exception $e) {
            abort($e->getCode(), $e->getMessage());
        }
    }
}
