<?php

namespace App\Modules\ThreeCX\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use App\Modules\Bookings\Task;

class TaskCallLog extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'task_call_logs';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'task_id',
        'user_id',
        'call_id',
        'from_extension',
        'to_number',
        'called_at',
        'answered_at',
        'ended_at',
        'duration',
        'status',
        'direction',
        'recording_filename',
        'notes',
        'raw_cdr_data',
        'metadata'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'called_at' => 'datetime',
        'answered_at' => 'datetime',
        'ended_at' => 'datetime',
        'duration' => 'integer',
        'raw_cdr_data' => 'array',
        'metadata' => 'array',
    ];

    /**
     * Get the task that this call log belongs to.
     */
    public function task()
    {
        return $this->belongsTo(Task::class);
    }

    /**
     * Get the user who made/received this call.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope a query to only include calls for a specific task.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int  $taskId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeForTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    /**
     * Scope a query to only include calls for a specific user.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int  $userId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope a query to only include completed calls.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

    /**
     * Scope a query to only include calls from a specific date range.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  string  $startDate
     * @param  string  $endDate
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('called_at', [$startDate, $endDate]);
    }

    /**
     * Get formatted duration as human readable string.
     *
     * @return string
     */
    public function getFormattedDurationAttribute()
    {
        if (!$this->duration) {
            return 'N/A';
        }

        $minutes = floor($this->duration / 60);
        $seconds = $this->duration % 60;

        return sprintf('%d:%02d', $minutes, $seconds);
    }

    /**
     * Get call status with icon.
     *
     * @return string
     */
    public function getStatusWithIconAttribute()
    {
        $icons = [
            'initiated' => '📞',
            'ringing' => '📲',
            'answered' => '✅',
            'completed' => '✅',
            'failed' => '❌',
            'cancelled' => '⏹️'
        ];

        $icon = $icons[$this->status] ?? '📞';
        return $icon . ' ' . ucfirst($this->status);
    }

    /**
     * Check if call has recording.
     *
     * @return bool
     */
    public function hasRecording()
    {
        return !empty($this->recording_filename);
    }

    /**
     * Get recording URL if available.
     *
     * @return string|null
     */
    public function getRecordingUrlAttribute()
    {
        if (!$this->hasRecording()) {
            return null;
        }

        // This would need to be configured based on your 3CX setup
        $recordingPath = config('threecx.cdr.recording_path', '/var/lib/3cx/Recordings/');
        return $recordingPath . $this->recording_filename;
    }
}
