<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Client Portal Link
        Schema::table('clients', function (Blueprint $table) {
            $table->foreignId('client_user_id')->nullable()->after('user_id')->constrained('users')->onDelete('set null');
        });

        // 2. Referrals (Add to users table)
        Schema::table('users', function (Blueprint $table) {
            $table->string('referral_code')->nullable()->unique()->after('status');
            $table->string('referred_by')->nullable()->after('referral_code'); // Code of the referrer
            $table->integer('referral_count')->default(0)->after('referred_by');
        });

        // 3. Wallet System
        Schema::create('wallets', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->decimal('balance', 10, 2)->default(0.00);
            $table->string('currency', 3)->default('USD');
            $table->timestamps();
        });

        Schema::create('wallet_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('wallet_id')->constrained()->onDelete('cascade');
            $table->string('type'); // deposit, withdrawal, payment, referral_bonus, adjustment
            $table->decimal('amount', 10, 2);
            $table->string('description');
            $table->string('reference_id')->nullable(); // External ID (PayPal, etc) or Internal ID (Invoice ID)
            $table->string('status')->default('completed'); // pending, completed, failed
            $table->timestamps();
        });

        // 4. Communication (Chat)
        Schema::create('messages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sender_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('receiver_id')->constrained('users')->onDelete('cascade');
            $table->text('content');
            $table->timestamp('read_at')->nullable();
            $table->timestamps(); // created_at is sent_at
            
            $table->index(['sender_id', 'receiver_id']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('messages');
        Schema::dropIfExists('wallet_transactions');
        Schema::dropIfExists('wallets');
        
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['referral_code', 'referred_by', 'referral_count']);
        });

        Schema::table('clients', function (Blueprint $table) {
            $table->dropForeign(['client_user_id']);
            $table->dropColumn('client_user_id');
        });
    }
};
