<?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
    {
        // Create currencies table
        Schema::create('currencies', function (Blueprint $table) {
            $table->id();
            $table->string('code', 255)->nullable();
            $table->string('symbol', 255)->nullable();
            $table->string('name', 255)->nullable();
            $table->decimal('rate', 15, 6)->nullable(); // Exchange rate
            $table->boolean('is_default')->default(false); // Default currency flag
            $table->timestamps();
        });

        // Create company settings table
        Schema::create('company_settings', function (Blueprint $table) {
            $table->id();
            $table->string('company_name');
            $table->string('company_code');
            $table->string('logo_path')->nullable();
            $table->text('address');
            $table->string('phone', 20);
            $table->string('email', 100)->nullable();
            $table->string('website', 100)->nullable();
            $table->string('tax_id', 100)->nullable();
            $table->foreignId('currency_id')->constrained('currencies');
            $table->json('bank_details')->nullable();
            $table->timestamps();
        });

        // Create payment providers table
        Schema::create('payment_providers', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('code')->unique()->comment('A short, unique identifier like MPESA, AIRTELMONEY');
            $table->text('api_key')->nullable()->comment('Should be encrypted in the application layer');
            $table->text('api_secret')->nullable()->comment('Should be encrypted in the application layer');
            $table->string('base_url')->nullable();
            $table->json('configuration')->nullable()->comment('For storing other provider-specific settings');
            $table->enum('status', ['active', 'inactive'])->default('active');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamps();
            $table->softDeletes();
        });

        // Create compliance reports table
        Schema::create('compliance_reports', function (Blueprint $table) {
            $table->id();
            $table->string('report_type'); // cbk, sasra, aml, cft, etc.
            $table->string('report_code')->unique(); // Unique identifier for the report
            $table->string('title');
            $table->text('description')->nullable();

            // Report period
            $table->date('report_date');
            $table->date('period_start');
            $table->date('period_end');

            // Report data and metadata
            $table->json('report_data'); // Store the actual report data
            $table->json('metadata')->nullable(); // Additional metadata
            $table->json('filters_applied')->nullable(); // Filters used to generate report

            // Status and approval
            $table->enum('status', ['draft', 'pending_review', 'approved', 'submitted', 'rejected'])->default('draft');
            $table->text('review_notes')->nullable();
            $table->timestamp('submitted_at')->nullable();
            $table->timestamp('approved_at')->nullable();

            // Regulatory requirements
            $table->boolean('is_regulatory_required')->default(false);
            $table->date('due_date')->nullable();
            $table->string('regulatory_body')->nullable(); // CBK, SASRA, etc.
            $table->string('submission_reference')->nullable();

            // File attachments (if report is exported)
            $table->string('file_path')->nullable();
            $table->string('file_name')->nullable();
            $table->string('file_mime_type')->nullable();
            $table->integer('file_size')->nullable();

            // Audit fields
            $table->foreignId('created_by')->constrained('users');
            $table->foreignId('reviewed_by')->nullable()->constrained('users');
            $table->foreignId('approved_by')->nullable()->constrained('users');
            $table->timestamps();

            // Indexes
            $table->index(['report_type', 'report_date']);
            $table->index(['status', 'due_date']);
            $table->index('regulatory_body');
            $table->index('period_start');
            $table->index('period_end');
        });

        // Create audit logs table
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->id();
            $table->string('event_type'); // login, logout, create, update, delete, view, export, etc.
            $table->string('model_type')->nullable(); // App\Models\User, App\Models\Loan, etc.
            $table->unsignedBigInteger('model_id')->nullable();

            // User information
            $table->foreignId('user_id')->nullable()->constrained('users')->onDelete('set null');
            $table->string('user_name')->nullable();
            $table->string('user_email')->nullable();
            $table->string('user_role')->nullable();

            // Event details
            $table->string('action'); // What was done
            $table->text('description')->nullable(); // Human readable description
            $table->json('old_values')->nullable(); // Previous state
            $table->json('new_values')->nullable(); // New state
            $table->json('metadata')->nullable(); // Additional context

            // Request information
            $table->string('ip_address')->nullable();
            $table->string('user_agent')->nullable();
            $table->string('session_id')->nullable();

            // Business context
            $table->string('entity_type')->nullable(); // loan, client, savings, payment, etc.
            $table->unsignedBigInteger('entity_id')->nullable();
            $table->decimal('amount_involved', 12, 2)->nullable(); // For financial transactions

            // Risk assessment
            $table->enum('risk_level', ['low', 'medium', 'high', 'critical'])->default('low');
            $table->text('risk_reason')->nullable();

            // Compliance flags
            $table->boolean('requires_review')->default(false);
            $table->boolean('is_suspicious')->default(false);
            $table->text('review_notes')->nullable();

            // Location and device info
            $table->string('location')->nullable();
            $table->string('device_type')->nullable();
            $table->string('browser')->nullable();
            $table->timestamp('event_timestamp');

            // Indexes for performance
            $table->index(['event_type', 'event_timestamp']);
            $table->index(['user_id', 'event_timestamp']);
            $table->index(['model_type', 'model_id']);
            $table->index(['entity_type', 'entity_id']);
            $table->index(['risk_level', 'requires_review']);
            $table->index('event_timestamp');
            $table->index('ip_address');
            $table->timestamps();
        });

        // Create notifications table
        Schema::create('notifications', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('loan_id')->nullable();
            $table->unsignedBigInteger('client_id')->nullable();
            $table->enum('type', ['reminder', 'overdue', 'penalty', 'payment_confirmation']);
            $table->enum('channel', ['sms', 'email', 'both']);
            $table->text('message');
            $table->boolean('sent')->default(false);
            $table->timestamp('sent_at')->nullable();
            $table->string('message_sid')->nullable();
            $table->string('delivery_status')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('notifications');
        Schema::dropIfExists('audit_logs');
        Schema::dropIfExists('compliance_reports');
        Schema::dropIfExists('payment_providers');
        Schema::dropIfExists('company_settings');
        Schema::dropIfExists('currencies');
    }
};
