<?php

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

class CreateTaskCallLogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('task_call_logs')) {
            Schema::create('task_call_logs', function (Blueprint $table) {
                $table->id();
                $table->unsignedInteger('task_id')->nullable();
                $table->unsignedInteger('user_id');
                $table->string('call_id')->nullable(); // 3CX call identifier
                $table->string('from_extension', 20);
                $table->string('to_number', 50);
                $table->timestamp('called_at');
                $table->timestamp('answered_at')->nullable();
                $table->timestamp('ended_at')->nullable();
                $table->integer('duration')->nullable(); // seconds
                $table->enum('status', ['initiated', 'ringing', 'answered', 'completed', 'failed', 'cancelled'])->default('initiated');
                $table->enum('direction', ['outbound', 'inbound'])->default('outbound');
                $table->string('recording_filename')->nullable();
                $table->text('notes')->nullable();
                $table->json('raw_cdr_data')->nullable(); // Store complete CDR record
                $table->timestamps();
                
                // Indexes
                $table->index('task_id');
                $table->index('user_id');
                $table->index('call_id');
                $table->index('called_at');
                $table->index(['task_id', 'called_at']);
                $table->index(['user_id', 'called_at']);
                
                // Foreign keys
                $table->foreign('task_id')->references('id')->on('tasks')->onDelete('set null');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('task_call_logs');
    }
}
