<?php

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

return new class extends Migration
{
    /**
     * 영업수수료 정산 테이블
     */
    public function up(): void
    {
        Schema::create('sales_commissions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');
            $table->unsignedBigInteger('management_id')->comment('영업 관리 ID (sales_tenant_managements)');

            // 입금 정보
            $table->enum('payment_type', ['deposit', 'balance'])->comment('입금 구분 (deposit:계약금, balance:잔금)');
            $table->decimal('payment_amount', 14, 2)->comment('입금액');
            $table->date('payment_date')->comment('입금일');

            // 수당 계산 기준
            $table->decimal('base_amount', 14, 2)->comment('수당 계산 기준액 (가입비의 50%)');
            $table->decimal('partner_rate', 5, 2)->default(20.00)->comment('영업파트너 수당률 (%)');
            $table->decimal('manager_rate', 5, 2)->default(5.00)->comment('매니저 수당률 (%)');
            $table->decimal('partner_commission', 14, 2)->comment('영업파트너 수당액');
            $table->decimal('manager_commission', 14, 2)->comment('매니저 수당액');

            // 지급 정보
            $table->date('scheduled_payment_date')->comment('지급예정일 (익월 10일)');
            $table->enum('status', ['pending', 'approved', 'paid', 'cancelled'])
                ->default('pending')
                ->comment('상태 (pending:대기, approved:승인, paid:지급완료, cancelled:취소)');
            $table->date('actual_payment_date')->nullable()->comment('실제 지급일');

            // 대상자 정보
            $table->unsignedBigInteger('partner_id')->comment('영업파트너 ID (sales_partners)');
            $table->unsignedBigInteger('manager_user_id')->nullable()->comment('매니저 사용자 ID');

            // 부가 정보
            $table->text('notes')->nullable()->comment('메모');
            $table->string('bank_reference', 100)->nullable()->comment('이체 참조번호');

            // 승인 정보
            $table->unsignedBigInteger('approved_by')->nullable()->comment('승인자 ID');
            $table->timestamp('approved_at')->nullable()->comment('승인일시');

            $table->timestamps();
            $table->softDeletes();

            // 인덱스
            $table->index('tenant_id');
            $table->index('management_id');
            $table->index('partner_id');
            $table->index('manager_user_id');
            $table->index('payment_type');
            $table->index('payment_date');
            $table->index('scheduled_payment_date');
            $table->index('status');
        });
    }

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