<?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('developers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->decimal('company_commission_rate', 6, 4)->default(0.06);
            $table->decimal('sales_incentive_rate', 6, 4)->default(0.02); // off-treasury
            $table->json('defaults')->nullable(); // manager incentive modes, backoffice rules, etc.
            $table->timestamps();
        });

        Schema::create('treasuries', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->enum('type', ['bank', 'cash', 'tax', 'other'])->default('other');
            $table->decimal('balance', 18, 2)->default(0);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('deals', function (Blueprint $table) {
            $table->id();
            $table->foreignId('developer_id')->constrained('developers');
            $table->string('unit_ref')->nullable();
            $table->enum('unit_type', ['residential', 'commercial', 'admin'])->default('residential');
            $table->string('area')->nullable();
            $table->decimal('unit_price', 18, 2);

            // Locked assumption: gross commission is inclusive of VAT + withholding.
            $table->decimal('gross_commission', 18, 2);
            $table->decimal('vat_rate', 6, 4)->default(0.14);
            $table->decimal('withholding_rate', 6, 4)->default(0.05);
            $table->string('withholding_name')->default('ضريبة المنبع');

            // Cashback per deal (optional)
            $table->boolean('has_cashback')->default(false);
            $table->enum('cashback_type', ['fixed', 'percent'])->nullable();
            $table->decimal('cashback_value', 18, 6)->nullable();
            $table->enum('cashback_timing', ['pre_tax', 'post_tax'])->nullable();

            // Status
            $table->enum('status', ['draft', 'claimed', 'collected', 'closed'])->default('draft');

            // Sales split references (the actual split lines are in deal_splits)
            $table->json('sales_assignment')->nullable(); // {sales:[{user_id,mode,value}], manager:{...}, off_treasury:{...}}

            $table->timestamps();
        });

        Schema::create('claims', function (Blueprint $table) {
            $table->id();
            $table->foreignId('deal_id')->constrained('deals')->cascadeOnDelete();
            $table->decimal('claimed_amount', 18, 2);
            $table->enum('status', ['open', 'collected', 'cancelled'])->default('open');
            $table->timestamps();
        });

        Schema::create('collections', function (Blueprint $table) {
            $table->id();
            $table->foreignId('deal_id')->constrained('deals')->cascadeOnDelete();
            $table->foreignId('claim_id')->nullable()->constrained('claims');
            $table->decimal('cheque_net_received', 18, 2);
            $table->decimal('vat_amount', 18, 2);
            $table->decimal('withholding_amount', 18, 2);
            $table->decimal('operating_net', 18, 2);
            $table->enum('status', ['pending', 'approved', 'posted'])->default('pending');
            $table->timestamps();
        });

        Schema::create('transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('treasury_id')->constrained('treasuries');
            $table->enum('direction', ['in', 'out', 'transfer_in', 'transfer_out']);
            $table->decimal('amount', 18, 2);
            $table->string('ref_type')->nullable();
            $table->unsignedBigInteger('ref_id')->nullable();
            $table->string('notes')->nullable();
            $table->timestamps();
        });

        Schema::create('expenses', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->enum('category', ['tax', 'payroll', 'marketing', 'operations', 'other'])->default('other');
            $table->string('sub_category')->nullable();
            $table->decimal('total_amount', 18, 2);
            $table->enum('status', ['draft', 'pending', 'approved', 'posted'])->default('draft');
            $table->timestamps();
        });

        Schema::create('payment_splits', function (Blueprint $table) {
            $table->id();
            $table->string('payable_type');
            $table->unsignedBigInteger('payable_id');
            $table->decimal('total_amount', 18, 2);
            $table->timestamps();
        });

        Schema::create('payment_split_lines', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payment_split_id')->constrained('payment_splits')->cascadeOnDelete();
            $table->foreignId('treasury_id')->constrained('treasuries');
            $table->enum('mode', ['fixed', 'percent']);
            $table->decimal('value', 18, 6);
            $table->decimal('computed_amount', 18, 2)->default(0);
            $table->timestamps();
        });

        Schema::create('approvals', function (Blueprint $table) {
            $table->id();
            $table->string('approvable_type');
            $table->unsignedBigInteger('approvable_id');
            $table->enum('status', ['pending', 'finance_approved', 'owner_approved', 'rejected'])->default('pending');
            $table->unsignedBigInteger('finance_user_id')->nullable();
            $table->unsignedBigInteger('owner_user_id')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        Schema::create('kpi_targets', function (Blueprint $table) {
            $table->id();
            $table->date('target_date');
            $table->enum('scope', ['daily', 'weekly', 'monthly'])->default('daily');
            $table->enum('role_type', ['sales', 'telesales'])->default('sales');
            $table->json('metrics'); // {calls:50, meetings:10, sales_count:2, sales_value:1000000}
            $table->timestamps();
        });

        Schema::create('kpi_entries', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->date('entry_date');
            $table->json('metrics');
            $table->enum('status', ['draft', 'submitted', 'ops_approved', 'manager_approved', 'rejected'])->default('draft');
            $table->unsignedBigInteger('ops_user_id')->nullable();
            $table->unsignedBigInteger('manager_user_id')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('kpi_entries');
        Schema::dropIfExists('kpi_targets');
        Schema::dropIfExists('approvals');
        Schema::dropIfExists('payment_split_lines');
        Schema::dropIfExists('payment_splits');
        Schema::dropIfExists('expenses');
        Schema::dropIfExists('transactions');
        Schema::dropIfExists('collections');
        Schema::dropIfExists('claims');
        Schema::dropIfExists('deals');
        Schema::dropIfExists('treasuries');
        Schema::dropIfExists('developers');
    }
};
