<?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('partner_team_members', function (Blueprint $table) {
            $table->id();
            $table->foreignId('partner_id')->constrained('partner_profiles')->cascadeOnDelete();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('name', 120);
            $table->string('phone', 20)->nullable();
            $table->string('email')->nullable();
            $table->string('role', 60)->default('Helper'); // Helper, Lead, etc
            $table->string('photo')->nullable();
            $table->boolean('is_active')->default(true);
            $table->boolean('aadhaar_verified')->default(false);
            $table->boolean('police_verified')->default(false);
            $table->string('aadhaar_doc_path')->nullable();
            $table->string('police_doc_path')->nullable();
            $table->timestamp('aadhaar_verified_at')->nullable();
            $table->timestamp('police_verified_at')->nullable();
            $table->timestamp('last_login_at')->nullable();
            $table->text('admin_notes')->nullable();
            $table->timestamps();

            $table->index(['partner_id', 'is_active']);
        });

        // Add team_member_id to subscription_visits so a partner can assign visits
        Schema::table('subscription_visits', function (Blueprint $table) {
            $table->foreignId('team_member_id')->nullable()->after('partner_id')
                ->constrained('partner_team_members')->nullOnDelete();
            $table->index('team_member_id');
        });
    }

    public function down(): void
    {
        Schema::table('subscription_visits', function (Blueprint $table) {
            $table->dropForeign(['team_member_id']);
            $table->dropIndex(['team_member_id']);
            $table->dropColumn('team_member_id');
        });
        Schema::dropIfExists('partner_team_members');
    }
};

