<?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
    {
        // Reusable message bodies with {{placeholders}}, one body per language.
        Schema::create('message_templates', function (Blueprint $table) {
            $table->id();
            $table->string('key')->nullable()->unique(); // system templates (fee_before_due, …)
            $table->string('name');
            $table->string('category')->default('custom'); // fee|attendance|exam|evaluation|event|general|custom
            $table->text('body_en')->nullable();
            $table->text('body_fa')->nullable();
            $table->text('body_ps')->nullable();
            $table->boolean('active')->default(true);
            $table->timestamps();
        });

        // One broadcast to a resolved audience.
        Schema::create('message_campaigns', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->foreignId('template_id')->nullable()->constrained('message_templates')->nullOnDelete();
            $table->text('body')->nullable(); // custom body (overrides template)
            $table->json('audience'); // {type, class_ids, student_ids, staff_ids}
            $table->string('language')->default('fa');
            $table->string('status')->default('draft'); // draft|queued|sent
            $table->unsignedInteger('total')->default(0);
            $table->unsignedInteger('sent_count')->default(0);
            $table->unsignedInteger('failed_count')->default(0);
            $table->string('created_by')->nullable();
            $table->timestamp('sent_at')->nullable();
            $table->timestamps();
        });

        // One WhatsApp message to one recipient.
        Schema::create('crm_messages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('campaign_id')->nullable()->constrained('message_campaigns')->cascadeOnDelete();
            $table->string('rule_key')->nullable(); // set when queued by an automation rule
            $table->string('recipient_type'); // parent|staff
            $table->unsignedBigInteger('recipient_id')->nullable(); // student id (parent) or staff id
            $table->string('recipient_name');
            $table->string('phone')->nullable();
            $table->text('body');
            $table->string('channel')->default('whatsapp');
            $table->string('status')->default('queued'); // queued|ready|sent|failed|skipped
            $table->string('dedupe_key')->nullable()->unique(); // stops automations double-sending
            $table->string('error')->nullable();
            $table->timestamp('sent_at')->nullable();
            $table->timestamps();
            $table->index(['status']);
            $table->index(['recipient_type', 'recipient_id']);
        });

        // Automatic triggers (fee reminders, monthly report, …).
        Schema::create('automation_rules', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->string('name');
            $table->boolean('enabled')->default(false);
            $table->foreignId('template_id')->nullable()->constrained('message_templates')->nullOnDelete();
            $table->json('params')->nullable(); // {days_before:3, repeat_every:7, day_of_month:1}
            $table->timestamp('last_run_at')->nullable();
            $table->timestamps();
        });

        // Gateway configuration (single row).
        Schema::create('crm_settings', function (Blueprint $table) {
            $table->id();
            $table->string('mode')->default('manual'); // manual (wa.me links) | cloud_api (Meta)
            $table->string('phone_number_id')->nullable();
            $table->text('access_token')->nullable();
            $table->string('country_code')->default('93');
            $table->string('sender_name')->nullable();
            $table->string('default_language')->default('fa');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('crm_settings');
        Schema::dropIfExists('automation_rules');
        Schema::dropIfExists('crm_messages');
        Schema::dropIfExists('message_campaigns');
        Schema::dropIfExists('message_templates');
    }
};
