<?php

namespace App;

use App\Traits\CsvImportable;
use App\Traits\CsvSplitable;
use Carbon\Carbon;

class Staff2000Staffu extends RichSearchableModel
{
    use CsvImportable;
    use CsvSplitable;

    public $incrementing = false;
    public $errors = [];
    const CREATED_AT = NULL;
    const UPDATED_AT = 'modified';
    protected $table = 'tcd_staff2000staffu';
    protected $primaryKey = 'code';
    protected $fillable = [
        'code',
        'name',
        'phonetic',
        'maiden_name',
        'sex',
        'nationality',
        'age',
        'zip',
        'address_1',
        'address_2',
        'address_3',
        'email_1',
        'email_2',
        'tel',
        'tel_cell_phone',
        'paid_leave_this_year',
        'paid_leave_previous_year',
        'work_weekly',
        'work_start_date',
        'paid_leave_start_date',
        'medical_checkup_date',
        'retire_date',
        'other_id',
        'st_id',
        'pg_id',
        'maternity_leave',
        'childcare_leave',
        'age_category',
        'residence_card_period',
        'remarks',
        'transfer_date',
        'health_insurance',
        'reason_health_insurance',
        'welfare_pension',
        'reason_welfare_pension',
        'employment_insurance',
        'reason_employment_insurance',
        'medical_checkup',
        'education_training',
        'business_name',
        'web_statement_output_indicator',
        'permanent_employee_classification',
    ];
    const DEFAULT_LIST = [
        'number' => 100,
        'search_method' => 1,
        'custom_list_sorts' => [
            [
                'field' => 'code',
                'sort' => CustomListSort::DESC,
                'priority' => 1
            ]
        ],
        'custom_list_conditions' => [],
        'custom_list_fields' => [
            [
                'field' => 'code'
            ],
            [
                'field' => 'contract_status'
            ],
            [
                'field' => 'name'
            ],
            [
                'field' => 'sex'
            ],
            [
                'field' => 'age'
            ],
            [
                'field' => 'email_1'
            ],
            [
                'field' => 'st_id'
            ],
            [
                'field' => 'pg_id'
            ],
            [
                'field' => 'modified'
            ],
        ],
    ];

    const FIELD_NAME = [
        'code' => 'ｽﾀｯﾌｺｰﾄﾞ',
        'name' => 'ｽﾀｯﾌ名',
        'phonetic' => 'ﾌﾘｶﾞﾅ',
        'maiden_name' => '旧姓',
        'sex' => '性別',
        'contract_status' => '契約ステータス',
        'nationality' => '国籍名',
        'age' => '年齢',
        'zip' => '郵便番号',
        'address_1' => '都道府県',
        'address_2' => '区市町村',
        'address_3' => '住所詳細',
        'email_1' => 'ﾒｰﾙｱﾄﾞﾚｽ1',
        'email_2' => 'ﾒｰﾙｱﾄﾞﾚｽ2',
        'tel' => '電話番号',
        'tel_cell_phone' => '携帯電話番号',
        'paid_leave_this_year' => '有給当年残日数',
        'paid_leave_previous_year' => '有給前年残日数',
        'work_weekly' => '週勤務',
        'work_start_date' => '勤務開始日',
        'paid_leave_start_date' => '有給起算日',
        'medical_checkup_date' => '健康診断日',
        'retire_date' => '退職日',
        'other_id' => '他 登録ID',
        'st_id' => 'スタッフID',
        'pg_id' => 'PG ID',
        'maternity_leave' => '産休',
        'childcare_leave' => '育休',
        'age_category' => '年齢区分',
        'residence_card_period' => '在留ｶｰﾄﾞ期間',
        'remarks' => '備考',
        'transfer_date' => '振込日',
        'health_insurance' => '健康保険加入状況',
        'reason_health_insurance' => '健康保険未加入理由',
        'welfare_pension' => '厚生年金加入状況',
        'reason_welfare_pension' => '厚生年金未加入理由',
        'employment_insurance' => '雇用保険加入状況',
        'reason_employment_insurance' => '雇用保険未加入理由',
        'medical_checkup' => '健康診断',
        'education_training' => '教育訓練',
        'business_name' => 'ﾋﾞｼﾞﾈｽﾈｰﾑ',
        'web_statement_output_indicator' => 'Web明細書出力区分',
        'permanent_employee_classification' => '無期雇用者区分',
        'modified' => 'レコード更新日',
    ];

    public static $function_id = CustomList::STAFF2000_STAFFU;
    public static $simple_searchable_fields = [
        'code',
        'name',
        'phonetic',
        'maiden_name',
        'sex',
        'nationality',
        'age',
        'zip',
        'address_1',
        'address_2',
        'address_3',
        'email_1',
        'email_2',
        'tel',
        'tel_cell_phone',
        'paid_leave_this_year',
        'paid_leave_previous_year',
        'work_weekly',
        'paid_leave_start_date',
        'medical_checkup_date',
        'other_id',
        'st_id',
        'pg_id',
        'maternity_leave',
        'childcare_leave',
        'age_category',
        'residence_card_period',
        'remarks',
        'transfer_date',
        'health_insurance',
        'reason_health_insurance',
        'welfare_pension',
        'reason_welfare_pension',
        'employment_insurance',
        'reason_employment_insurance',
        'medical_checkup',
        'education_training',
        'business_name',
        'web_statement_output_indicator',
        'permanent_employee_classification',
        'modified',
    ];

    protected $validateFields = [
        'date_field' => ['date', 'datetime'],
        'num_field' => [],
        'bool_field' => [],
    ];

    // ソート不可フィールド
    public static $sort_exception_field = [
        'contract_status'
    ];

    const CONTRACT_STATUS = [
        1 => '契約中',
        2 => '契約期間外',
    ];

    public static function getSearchOptions()
    {
        $searchOptions = [];
        $searchOptions['select'] = [];
        $searchOptions['select']['contract_status'] = self::CONTRACT_STATUS;
        return $searchOptions;
    }

    public function staffu()
    {
        return $this->belongsTo(Staffu::class, 'st_Id', 'st_id');
    }

    public function staff2000_contracts()
    {
        return $this->hasMany(Staff2000Contract::class, '2st_code', 'code')
            ->orderBy('2or_code', 'desc');
    }

    public function valid_staff2000_contracts()
    {
        $now = Carbon::now()->toDateString();
        return $this->hasMany(Staff2000Contract::class, '2st_code', 'code')
            ->whereDate('contract_period_start', '<=', $now)
            ->whereDate('contract_period_end', '>=', $now)
            ->orderby('contract_period_end', 'ASC');
    }
    
    // 一覧画面向けアクセサ
    public function getIndexStIdAttribute()
    {
        $value = $this->st_id;
        if (empty($value)) return $value;
        return $this->getLinkHtml(url('staffu/view/'.$value), $value, true);
    }

    public function scopeModified($query, $condition, $searchMethod)
    {
        return $query->datetime($condition, $searchMethod);
    }

    public function getFullAddressAttribute()
    {
        return $this->address_1.$this->address_2.$this->address_3;
    }
    
    public function scopeContractStatus($query, $condition, $searchMethod)
    {
        $status = [
            'comparison_operator_id' => CustomListCondition::GREATER,
            'condition' => 0,
        ];
        if($condition['condition'] * $condition['comparison_operator_id'] === 2){
            $status['comparison_operator_id'] = CustomListCondition::EQUAL;
        }
        return $query->$searchMethod(function ($q) use ($status) {
            $q->searchCount('valid_staff2000_contracts', $status);
        });
    }

    public function getIndexContractStatusAttribute()
    {
        if($this->valid_staff2000_contracts->count() > 0) return self::CONTRACT_STATUS[1];
        return self::CONTRACT_STATUS[2];
    }

    public function getMailChimpLogsSortAttribute()
    {
        $contract_sorted = [];
        foreach ($this->staff2000_contracts as $contract){
            foreach ($contract->mail_chimp_logs as $log){
                $contract_sorted[] = $log;
            }
        }
        return collect($contract_sorted)->sortByDesc('schedule_time');
    }

    public function getMailLastScheduleTimeAttribute()
    {
        return $this->mail_chimp_logs_sort->first()->schedule_time ?? '';
    }

}
