<?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
    {
        // Tenant Contacts & Internal Notes
        Schema::create('tenant_contacts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('name');
            $table->string('designation')->nullable();
            $table->string('email')->nullable();
            $table->string('mobile')->nullable();
            $table->boolean('is_primary')->default(false);
            $table->timestamps();
        });

        Schema::create('tenant_notes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->text('note');
            $table->string('category')->default('general'); // general, billing, support, sales
            $table->timestamps();
        });

        Schema::create('tenant_account_managers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete(); // Platform staff user
            $table->string('role_type')->default('account_manager'); // account_manager, sales_manager, onboarding_manager, support_manager
            $table->timestamps();

            $table->unique(['tenant_id', 'user_id', 'role_type']);
        });

        Schema::create('tenant_onboarding_steps', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('step_key');
            $table->string('step_name');
            $table->boolean('is_completed')->default(false);
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();

            $table->unique(['tenant_id', 'step_key']);
        });

        // Tenant Feature Overrides (Requirement 19)
        Schema::create('tenant_feature_overrides', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('feature_id')->constrained('features')->cascadeOnDelete();
            $table->string('override_type')->default('allow'); // allow (force enable), deny (force disable), inherit
            $table->string('limit_value')->nullable();
            $table->timestamps();

            $table->unique(['tenant_id', 'feature_id']);
        });

        // Subscription History (Requirement 20)
        Schema::create('subscription_history', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('subscription_id')->nullable()->constrained('subscriptions')->nullOnDelete();
            $table->foreignId('previous_plan_id')->nullable()->constrained('plans')->nullOnDelete();
            $table->foreignId('new_plan_id')->nullable()->constrained('plans')->nullOnDelete();
            $table->string('event_type'); // created, upgraded, downgraded, extended, paused, resumed, cancelled, expired
            $table->decimal('prorated_amount', 10, 2)->default(0);
            $table->text('notes')->nullable();
            $table->foreignId('performed_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        // Add-ons & Tenant Add-ons (Requirement 25)
        Schema::create('addons', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('addon_type')->default('recurring'); // recurring, one_time, usage_pack, quantity_based
            $table->string('metric_key')->nullable(); // e.g. users, branches, storage_gb, ai_credits, whatsapp_messages
            $table->integer('unit_quantity')->default(1);
            $table->decimal('price_monthly', 10, 2)->default(0);
            $table->decimal('price_yearly', 10, 2)->default(0);
            $table->text('description')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('tenant_addons', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('addon_id')->constrained('addons')->cascadeOnDelete();
            $table->integer('quantity')->default(1);
            $table->decimal('price', 10, 2)->default(0);
            $table->string('billing_cycle')->default('monthly');
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->string('status')->default('active');
            $table->timestamps();
        });

        // Usage Aggregations & Credit Wallets (Requirement 38, 81, 82)
        Schema::create('usage_metrics', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('metric_key'); // users.count, branches.count, storage.bytes, whatsapp.messages, sms.messages, ai.tokens, ocr.pages, api.requests
            $table->bigInteger('metric_value')->default(0);
            $table->string('billing_period')->nullable(); // YYYY-MM
            $table->date('metric_date')->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'metric_key', 'billing_period']);
        });

        Schema::create('credit_wallets', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('wallet_type'); // ai, whatsapp, sms, api
            $table->bigInteger('balance')->default(0);
            $table->timestamps();

            $table->unique(['tenant_id', 'wallet_type']);
        });

        Schema::create('credit_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('wallet_id')->constrained('credit_wallets')->cascadeOnDelete();
            $table->string('transaction_type'); // credit, debit, adjustment, purchase, bonus, refund, expiry
            $table->bigInteger('amount');
            $table->bigInteger('balance_after');
            $table->string('reason')->nullable();
            $table->string('reference')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        // Coupons (Requirement 27)
        Schema::create('coupons', function (Blueprint $table) {
            $table->id();
            $table->string('code')->unique();
            $table->string('description')->nullable();
            $table->string('discount_type')->default('percentage'); // percentage, fixed
            $table->decimal('discount_amount', 10, 2)->default(0);
            $table->json('applicable_plans')->nullable();
            $table->decimal('min_purchase_amount', 10, 2)->default(0);
            $table->integer('max_redemptions')->nullable();
            $table->integer('redemption_count')->default(0);
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('coupon_redemptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('coupon_id')->constrained('coupons')->cascadeOnDelete();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->decimal('discount_applied', 10, 2);
            $table->timestamps();
        });

        // SaaS Invoices, Payments, Refunds, Credit Notes (Requirements 28-32)
        Schema::create('saas_invoices', function (Blueprint $table) {
            $table->id();
            $table->string('invoice_number')->unique();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('subscription_id')->nullable()->constrained('subscriptions')->nullOnDelete();
            $table->foreignId('plan_id')->nullable()->constrained('plans')->nullOnDelete();
            $table->date('invoice_date');
            $table->date('due_date');
            $table->decimal('subtotal', 10, 2)->default(0);
            $table->decimal('discount', 10, 2)->default(0);
            $table->decimal('tax_rate', 5, 2)->default(5.00); // 5% UAE VAT default
            $table->decimal('tax_amount', 10, 2)->default(0);
            $table->decimal('total', 10, 2)->default(0);
            $table->decimal('paid_amount', 10, 2)->default(0);
            $table->decimal('balance', 10, 2)->default(0);
            $table->string('status')->default('issued'); // draft, issued, partially_paid, paid, overdue, cancelled, refunded
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        Schema::create('saas_invoice_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('invoice_id')->constrained('saas_invoices')->cascadeOnDelete();
            $table->string('item_name');
            $table->integer('quantity')->default(1);
            $table->decimal('unit_price', 10, 2)->default(0);
            $table->decimal('total_price', 10, 2)->default(0);
            $table->timestamps();
        });

        Schema::create('saas_payments', function (Blueprint $table) {
            $table->id();
            $table->string('payment_number')->unique();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('invoice_id')->nullable()->constrained('saas_invoices')->nullOnDelete();
            $table->date('payment_date');
            $table->decimal('amount', 10, 2);
            $table->string('payment_method')->default('bank_transfer'); // cash, bank_transfer, card, online_gateway, manual_adjustment
            $table->string('transaction_reference')->nullable();
            $table->string('proof_attachment')->nullable();
            $table->string('status')->default('success'); // success, pending, failed, refunded
            $table->text('remarks')->nullable();
            $table->foreignId('received_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        Schema::create('saas_refunds', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('payment_id')->constrained('saas_payments')->cascadeOnDelete();
            $table->decimal('amount', 10, 2);
            $table->text('reason');
            $table->string('status')->default('processed'); // requested, approved, processed, rejected
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        Schema::create('saas_credit_notes', function (Blueprint $table) {
            $table->id();
            $table->string('credit_note_number')->unique();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('invoice_id')->nullable()->constrained('saas_invoices')->nullOnDelete();
            $table->decimal('amount', 10, 2);
            $table->text('reason');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('saas_credit_notes');
        Schema::dropIfExists('saas_refunds');
        Schema::dropIfExists('saas_payments');
        Schema::dropIfExists('saas_invoice_items');
        Schema::dropIfExists('saas_invoices');
        Schema::dropIfExists('coupon_redemptions');
        Schema::dropIfExists('coupons');
        Schema::dropIfExists('credit_transactions');
        Schema::dropIfExists('credit_wallets');
        Schema::dropIfExists('usage_metrics');
        Schema::dropIfExists('tenant_addons');
        Schema::dropIfExists('addons');
        Schema::dropIfExists('subscription_history');
        Schema::dropIfExists('tenant_feature_overrides');
        Schema::dropIfExists('tenant_onboarding_steps');
        Schema::dropIfExists('tenant_account_managers');
        Schema::dropIfExists('tenant_notes');
        Schema::dropIfExists('tenant_contacts');
    }
};
