<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('products', function (Blueprint $table) {
            if (! Schema::hasColumn('products', 'bonus_base')) {
                $table->string('bonus_base')->default('sales')->after('bonus_type')->index();
            }
        });

        Schema::create('bonus_disbursements', function (Blueprint $table) {
            $table->id();
            $table->foreignId('branch_id')->constrained()->restrictOnDelete();
            $table->foreignId('staff_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('disbursed_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('operational_expense_id')->nullable()->constrained()->nullOnDelete();
            $table->string('disbursement_no')->unique();
            $table->date('period_start');
            $table->date('period_end');
            $table->date('disbursed_at');
            $table->decimal('total_amount', 14, 2)->default(0);
            $table->text('note')->nullable();
            $table->timestamps();
        });

        Schema::create('bonus_disbursement_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('bonus_disbursement_id')->constrained()->cascadeOnDelete();
            $table->foreignId('order_detail_id')->constrained()->restrictOnDelete();
            $table->decimal('bonus_amount', 14, 2);
            $table->timestamps();
            $table->unique('order_detail_id');
        });

        $now = now();
        foreach (['owner', 'admin_cabang', 'manager', 'kasir'] as $role) {
            DB::table('role_permissions')->updateOrInsert(
                ['role' => $role, 'permission' => 'bonuses'],
                ['allowed' => true, 'created_at' => $now, 'updated_at' => $now],
            );
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('bonus_disbursement_items');
        Schema::dropIfExists('bonus_disbursements');

        Schema::table('products', function (Blueprint $table) {
            if (Schema::hasColumn('products', 'bonus_base')) {
                $table->dropColumn('bonus_base');
            }
        });
    }
};
