<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class ReductionMaster extends Model
{
    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $table = 'reduction_confirm';
    protected $primaryKey = null;  // 複合キーを使用
    public $incrementing = false;

    protected $fillable = [
        'park_id',
        'user_categoryid',
        'reduction_check_type',
        'operator_id',
        'created_at',
        'updated_at',
    ];

    /**
     * 複合キー (park_id, user_categoryid) で既存レコードを検索または作成
     */
    public static function findOrCreateByKeys($parkId, $userCategoryId)
    {
        return self::where('park_id', $parkId)
            ->where('user_categoryid', $userCategoryId)
            ->first();
    }

    /**
     * レコード保存時に operator_id を自動設定
     */
    public static function boot()
    {
        parent::boot();
        self::saving(function (ReductionMaster $model) {
            if (!isset($model->operator_id) || $model->operator_id === null) {
                $model->operator_id = Auth::user()->ope_id ?? null;
            }
        });
    }
}
