<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\DTO\SearchData;

class UserNameLog extends Model
{
    protected $table = 'tb_user_name_log';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = true;
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = null;
    const DELETED_AT = null;

    protected $guarded = [];

    /**
     * 이름 변경 제한 일
     */
    public function getChangeDay(): int
    {
        return intval(config('change_nickname_day', 0));
    }

    /**
     * 이름 변경 남은 일 수
     */
    public function getDayLeft(int $uid): int
    {
        $a = $this->getChangeDay();
        $b = $this->getLastChangeDay($uid);
        $c = ($a - $b);

        if($a === 0) {
            return -1;
        }else if($c > 0) { // 남은 기간
            return $c;
        }else if($c < 0) { // 지난 기간
            return $c;
        }
    }

    /**
     * 마지막 이름 변경 일
     */
    public function getLastChangeDay(int $uid): int
    {
        return (collect(DB::select(
                    'SELECT TIMESTAMPDIFF(DAY, created_at, NOW()) AS diff FROM tb_user_name_log WHERE user_id = ? ORDER BY id DESC LIMIT 1'
                    , [$uid]))->get(0)->diff ?? 0);
    }

    /**
     * 이름 변경이 가능한지 확인
     */
    public function isUpdateAble(int $uid):  bool
    {
        $lastChangeDay = $this->getLastChangeDay($uid);
        if(!$lastChangeDay || $this->getChangeDay() <= $lastChangeDay) {
            return true;
        }
        return false;
    }

    /**
     * 이름 변경 기록 입력
     */
    public function setLog(User $user, string $name): bool
    {
        return $this->insert([
            'user_id' => $user->id,
            'before' => $user->nickname,
            'after' => $name,
            'created_at' => now()
        ]);
    }

    /**
     * 이름 변경 기록 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select('users.sid', 'tb_user_name_log.*');

        if ($params->keyword) {
            switch ($params->field) {
                case 'tb_user_name_log.before' :
                case 'tb_user_name_log.after' :
                case 'users.name' :
                case 'users.email' :
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'tb_user_name_log.id' :
                case 'users.id' :
                case 'users.sid' :
                    $query->where($params->field, '=', $params->keyword);
                    break;
            }
        }

        $query->leftJoin('users', 'users.id', '=', 'tb_user_name_log.user_id');
        $query->orderByDesc('tb_user_name_log.id');

        $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
        $total = $this->count();
        $rows = $list->count();

        return (object)[
            'total' => $total,
            'rows' => $rows,
            'list' => $list
        ];
    }
}
