<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStorageContractsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('storage_contracts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->comment('保管ユーザーID');
            $table->unsignedBigInteger('product_id')->comment('対象商品ID');
            $table->date('storage_start_date')->comment('保管開始日（課金起算日）');
            $table->date('next_renewal_date')->comment('次回更新日');
            $table->integer('amount')->default(6600)->comment('課金額（税込）');
            $table->unsignedSmallInteger('status')->default(0)->comment('0=有効, 1=停止, 2=解約');
            $table->boolean('auto_renew')->default(true)->comment('自動更新フラグ');
            $table->string('payjp_charge_id')->nullable()->comment('最新のPAY.JP課金ID');
            $table->timestamp('renewal_notified_at')->nullable()->comment('更新案内メール送信日時');
            $table->timestamp('cancelled_at')->nullable()->comment('解約日時');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->index(['user_id', 'status']);
            $table->index('next_renewal_date');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::dropIfExists('storage_contracts');
    }
}
