<?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
    {
        // 1. WhatsApp / SMS / Email Communication (Requirements 42-46)
        Schema::create('communication_templates', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->nullable()->constrained('tenants')->cascadeOnDelete();
            $table->string('channel'); // whatsapp, sms, email
            $table->string('template_code');
            $table->string('name_en');
            $table->text('content_en');
            $table->text('content_ar')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // The customer master migration owns the shared communication_logs table.
        // Extend it here once applications and provider infrastructure exist.
        Schema::table('communication_logs', function (Blueprint $table) {
            $table->string('recipient')->nullable()->after('channel');
            $table->string('template_code')->nullable();
            $table->text('message')->nullable();
            $table->foreignId('application_id')->nullable()->constrained('applications')->nullOnDelete();
            $table->string('status')->default('sent'); // sent, delivered, read, failed
            $table->string('provider_message_id')->nullable();
            $table->text('failure_reason')->nullable();
            $table->timestamp('sent_at')->nullable();
        });

        // 2. PRO Operations & Document Custody (Requirements 76-79)
        Schema::create('pro_jobs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('job_number');
            $table->foreignId('application_id')->constrained('applications')->cascadeOnDelete();
            $table->foreignId('pro_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('destination'); // GDRFA, MOHRE, Medical Center, Tasheel, Amer
            $table->string('purpose');
            $table->string('status')->default('assigned'); // assigned, in_progress, completed, cancelled
            $table->text('remarks')->nullable();
            $table->timestamps();
        });

        Schema::create('pro_document_custodies', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('qr_code')->unique();
            $table->foreignId('customer_id')->nullable()->constrained('customers')->nullOnDelete();
            $table->foreignId('application_id')->nullable()->constrained('applications')->nullOnDelete();
            $table->string('document_name'); // Original Passport, EID Physical, Trade License Original
            $table->string('status')->default('received'); // received, stored, with_pro, submitted_externally, returned, delivered
            $table->string('storage_location')->nullable(); // Locker A-12
            $table->foreignId('current_holder_id')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        // 3. Queue Tokens & Appointments (Requirements 80-82)
        Schema::create('queue_tokens', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained('branches')->cascadeOnDelete();
            $table->foreignId('counter_id')->nullable()->constrained('counters')->nullOnDelete();
            $table->string('token_number'); // A001, V025
            $table->foreignId('customer_id')->nullable()->constrained('customers')->nullOnDelete();
            $table->string('service_type')->default('general');
            $table->string('status')->default('waiting'); // waiting, called, at_counter, completed, no_show
            $table->timestamp('called_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();
        });

        Schema::create('appointments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained('branches')->cascadeOnDelete();
            $table->foreignId('customer_id')->constrained('customers')->cascadeOnDelete();
            $table->foreignId('service_id')->nullable()->constrained('services')->nullOnDelete();
            $table->date('appointment_date');
            $table->string('appointment_time');
            $table->string('status')->default('booked'); // booked, confirmed, checked_in, completed, cancelled
            $table->timestamps();
        });

        // 4. AI Usage Logs & Outbound Webhooks (Requirements 83-89)
        Schema::create('ai_usage_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->string('feature_name'); // ocr_extraction, document_assistant, operations_query
            $table->integer('credits_used')->default(1);
            $table->timestamps();
        });

        Schema::create('webhook_endpoints', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('url');
            $table->string('secret');
            $table->json('events'); // ['application.completed', 'payment.received']
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('webhook_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('webhook_endpoint_id')->constrained('webhook_endpoints')->cascadeOnDelete();
            $table->string('event');
            $table->integer('response_code')->nullable();
            $table->string('status')->default('success'); // success, failed
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('webhook_logs');
        Schema::dropIfExists('webhook_endpoints');
        Schema::dropIfExists('ai_usage_logs');
        Schema::dropIfExists('appointments');
        Schema::dropIfExists('queue_tokens');
        Schema::dropIfExists('pro_document_custodies');
        Schema::dropIfExists('pro_jobs');
        Schema::table('communication_logs', function (Blueprint $table) {
            $table->dropForeign(['application_id']);
            $table->dropColumn([
                'recipient',
                'template_code',
                'message',
                'application_id',
                'status',
                'provider_message_id',
                'failure_reason',
                'sent_at',
            ]);
        });
        Schema::dropIfExists('communication_templates');
    }
};
