<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Pagination\LengthAwarePaginator;

class User extends Model
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    protected $table = 'user';
    protected $primaryKey = 'user_seq';
    public $timestamps = true;

    // 本人確認チェックフラグの定数
    const USER_ID_CARD_CHK_FLG = [
        0 => '未確認',
        1 => '確認済み'
    ];

    // 身分証明書種別の定数
    const USER_IDCARD = [
        '運転免許証' => '運転免許証',
        '健康保険証' => '健康保険証',
        'パスポート' => 'パスポート',
        '学生証' => '学生証',
        'その他' => 'その他'
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'user_id',
        'member_id',
        'user_pass',
        'user_manual_regist_flag',
        'user_mailing_flag',
        'contract_number',
        'user_tag_serial',
        'user_tag_serial_64',
        'qr_code',
        'tag_qr_flag',
        'user_aid',
        'user_park_number',
        'user_place_qrid',
        'user_categoryid',
        'user_name',
        'user_phonetic',
        'user_gender',
        'user_birthdate',
        'user_age',
        'ward_residents',
        'user_mobile',
        'user_homephone',
        'user_primemail',
        'user_submail',
        'user_regident_zip',
        'user_regident_pre',
        'user_regident_city',
        'user_regident_add',
        'user_relate_zip',
        'user_relate_pre',
        'user_relate_city',
        'user_relate_add',
        'user_workplace',
        'user_school',
        'user_graduate',
        'user_reduction',
        'user_idcard',
        'user_idcard_chk_flag',
        'user_chk_day',
        'user_chk_opeid',
        'user_tag_issue',
        'issue_permission',
        'user_quit_flag',
        'user_quitday',
        'user_remarks',
        'photo_filename1',
        'photo_filename2',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'user_pass',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'user_birthdate' => 'date',
            'user_chk_day' => 'datetime',
            'user_quitday' => 'date',
            'user_manual_regist_flag' => 'boolean',
            'user_mailing_flag' => 'boolean',
            'tag_qr_flag' => 'boolean',
            'user_idcard_chk_flag' => 'boolean',
            'issue_permission' => 'boolean',
            'user_quit_flag' => 'boolean',
        ];
    }

    /**
     * ユーザー検索
     */
    public static function search($inputs)
    {
        $query = self::query();

        // 検索条件の適用
        if (!empty($inputs['user_id'])) {
            $query->where('user_id', 'like', '%' . $inputs['user_id'] . '%');
        }
        if (!empty($inputs['member_id'])) {
            $query->where('member_id', 'like', '%' . $inputs['member_id'] . '%');
        }
        if (!empty($inputs['user_tag_serial'])) {
            $query->where('user_tag_serial', 'like', '%' . $inputs['user_tag_serial'] . '%');
        }
        if (!empty($inputs['user_phonetic'])) {
            $query->where('user_phonetic', 'like', '%' . $inputs['user_phonetic'] . '%');
        }
        if (!empty($inputs['phone'])) {
            $query->where(function($q) use ($inputs) {
                $q->where('user_mobile', 'like', '%' . $inputs['phone'] . '%')
                  ->orWhere('user_homephone', 'like', '%' . $inputs['phone'] . '%');
            });
        }
        if (isset($inputs['black_list']) && $inputs['black_list'] !== '') {
            $query->where('user_quit_flag', $inputs['black_list']);
        }
        if (isset($inputs['ward_residents']) && $inputs['ward_residents'] !== '') {
            $query->where('ward_residents', $inputs['ward_residents']);
        }
        if (!empty($inputs['user_tag_serial_64'])) {
            $query->where('user_tag_serial_64', 'like', '%' . $inputs['user_tag_serial_64'] . '%');
        }

        // ソート
        if (!empty($inputs['sort'])) {
            $sortType = !empty($inputs['sort_type']) ? $inputs['sort_type'] : 'asc';
            $query->orderBy($inputs['sort'], $sortType);
        } else {
            $query->orderBy('user_seq', 'desc');
        }

        // エクスポート用の場合はページネーションしない
        if (!empty($inputs['isExport'])) {
            return $query->get();
        }

        // ページネーション（Utilsクラスの定数を使用）
        return $query->paginate(\App\Utils::item_per_page);
    }

    /**
     * シーケンスでユーザーを取得
     */
    public static function getUserBySeq($seq)
    {
        return self::where('user_seq', $seq)->first();
    }

    /**
     * シーケンス配列でユーザーを削除
     */
    public static function deleteUsersBySeq($seqArray)
    {
        try {
            return self::whereIn('user_seq', $seqArray)->delete();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * ユーザータイプとのリレーション
     */
    public function getUserType()
    {
        return $this->belongsTo(Usertype::class, 'user_categoryid', 'id');
    }
    
    public static function getList()
    {
        return self::pluck('user_name', 'user_seq');
    }

    public static function getUserPhone()
    {
        return self::select('user_seq', 'user_name', 'user_mobile', 'user_homephone')->get();
    }
}
