<?php

namespace App\Models;

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

class UserDormant extends Model
{
    protected $table = 'tb_user_dormant';
    protected $primaryKey = 'id';

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

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $guarded = [];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'last_login_at' => 'datetime', // 마지막 로그인 일시
        'email_verified_at' => 'datetime', // 이메일 인증일시
        'auth_certified_at' => 'datetime', // 본인 인증일시
        'password_updated_at' => 'datetime' // 비밀번호 변경일시
    ];

    protected $dates = [
        'last_login_at',
        'created_at',
        'updated_at',
        'deleted_at',
        'email_verified_at',
        'auth_certified_at',
        'password_updated_at',
        'dormant_at'
    ];

    /**
     * 등록된 휴면회원 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select('tb_user_dormant.*');

        if ($params->keyword) {
            switch ($params->field) {
                case 'tb_user_dormant.id':
                case 'tb_user_dormant.sid':
                    $query->where($params->field, '=', $params->keyword);
                    break;
                case 'tb_user_dormant.name':
                case 'tb_user_dormant.nickname':
                case 'tb_user_dormant.email':
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'tb_user_dormant.created_at':
                case 'tb_user_dormant.last_login_at':
                    $query->whereDate($params->field, $params->keyword);
                    break;
            }
        }

        $query->orderByDesc('tb_user_dormant.id');

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

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

    /**
     * 휴면 처리
     */
    public function dormancy(int $userID): bool
    {
        return DB::transaction(function () use ($userID)
        {
            $user = (new User)->findOrNew($userID);
            if (!$user->exists) {
                return false;
            }

            $userColumns = $this->_userColumns();

            foreach($userColumns as $column => $value)
            {
                if(array_key_exists($column, $user->getAttributes())) {
                    // 휴면 회원 정보 설정
                    $this->{$column} = $user->{$column};

                    if($column == 'id') {
                        continue;
                    }

                    // 기존 회원 정보를 null 처리
                    $user->{$column} = $value;
                }
            }

            // 휴면 등록일시
            $this->dormant_at = now();

            $user->save();

            return $this->save();
        });
    }

    /**
     * 휴면 해제
     */
    public function recover(int $userID): bool
    {
        return DB::transaction(function () use ($userID)
        {
            $dormant = $this->findOrNew($userID);
            if (!$dormant->exists) {
                return false;
            }

            $user = (new User)->findOrNew($userID);
            if (!$user->exists) {
                return false;
            }

            $userColumns = $this->_userColumns();

            foreach($userColumns as $column => $value)
            {
                if(array_key_exists($column, $dormant->getAttributes())) {
                    // 회원 정보 설정
                    $user->{$column} = $dormant->{$column};
                }
            }

            // 휴면계정 삭제
            $dormant->forceDelete();

            return $user->save();
        });
    }

    /**
     * 회원 공통 속성
     */
    private function _userColumns(): array
    {
        return [
            'id' => null,
            'user_group_id' => null,
            'user_grade_id' => null,
            'sid' => '',
            'email' => '',
            'name' => null,
            'nickname' => null,
            'password' => '',
            'remember_token' => null,
            'today_message' => null,
            'group' => 0,
            'grade' => 0,
            'level' => 0,
            'point' => 0,
            'exp' => 0,
            'phone' => null,
            'birthday' => null,
            'gender' => 0,
            'icon' => null,
            'thumb' => null,
            'zip_code' => null,
            'address_1' => null,
            'address_2' => null,
            'address_3' => null,
            'address_4' => null,
            'receive_email' => 0,
            'receive_sms' => 0,
            'receive_note' => 0,
            'register_ip' => null,
            'last_login_at' => null,
            'last_login_ip' => null,
            'is_open_profile' => 0,
            'is_email_cert' => 0,
            'is_auth_cert' => 0,
            'is_adult_cert' => 0,
            'is_denied' => 0,
            'is_admin' => 0,
            'is_withdraw' => 0,
            'about_me' => null,
            'memo' => null,
            'following' => 0,
            'followed' => 0,
            'created_at' => null,
            'updated_at' => null,
            'deleted_at' => null,
            'email_verified_at' => null,
            'auth_certified_at' => null,
            'password_updated_at' => null
        ];
    }
}
