<?php

namespace App;

use App\Laravue\Models\User;
use Illuminate\Database\Eloquent\Model;

class StorageContract extends Model
{
    protected $table = 'storage_contracts';

    const STATUS_ACTIVE = 0;
    const STATUS_CANCELLED = 2;

    const DEFAULT_AMOUNT = 6600;

    protected $fillable = [
        'user_id', 'product_id', 'storage_start_date', 'next_renewal_date',
        'amount', 'status', 'auto_renew', 'payjp_charge_id', 'initial_charge_skipped',
        'renewal_notified_at', 'admin_note', 'cancelled_at',
    ];

    protected $casts = [
        'storage_start_date' => 'date',
        'next_renewal_date' => 'date',
        'auto_renew' => 'boolean',
        'initial_charge_skipped' => 'boolean',
        'renewal_notified_at' => 'datetime',
        'cancelled_at' => 'datetime',
    ];

    /**
     * JSON出力時に日付フォーマットを制御
     */
    public function toArray()
    {
        $array = parent::toArray();
        if (isset($array['storage_start_date'])) {
            $array['storage_start_date'] = $this->storage_start_date ? $this->storage_start_date->format('Y-m-d') : null;
        }
        if (isset($array['next_renewal_date'])) {
            $array['next_renewal_date'] = $this->next_renewal_date ? $this->next_renewal_date->format('Y-m-d') : null;
        }
        return $array;
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }

    public function isActive()
    {
        return $this->status === self::STATUS_ACTIVE;
    }

    public function isCancelled()
    {
        return $this->status === self::STATUS_CANCELLED;
    }

    /**
     * 更新対象の契約を取得（次回更新日が指定日以前 & 有効 & 自動更新ON）
     */
    public function scopeDueForRenewal($query, $date = null)
    {
        $date = $date ?: now()->toDateString();
        return $query->where('status', self::STATUS_ACTIVE)
            ->where('auto_renew', true)
            ->where('next_renewal_date', '<=', $date);
    }

    /**
     * 更新案内メール対象（更新1ヶ月前 & 未通知）
     */
    public function scopeDueForRenewalNotice($query, $date = null)
    {
        $date = $date ?: now()->addMonth()->toDateString();
        return $query->where('status', self::STATUS_ACTIVE)
            ->where('auto_renew', true)
            ->whereNull('renewal_notified_at')
            ->where('next_renewal_date', '<=', $date);
    }
}
