<?php

namespace Mtc\Plugins\Wisebee\Classes\Models;

use App\Casts\OptionalEncrypted;
use App\Casts\OptionalEncryptedArray;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Accessors
 *
 * @property int $id
 * @property int $wisebee_id
 * @property int $wisebee_consultation_id
 * @property string $status
 * @property string|null $transcript_text
 * @property string|null $transcript_edited
 * @property array|null $transcript_comments
 * @property string|null $notes
 * @property Carbon|null $completed_at
 * @property Carbon|null $edited_at
 * @property int|null $edited_by
 * @property Carbon|null $approved_at
 * @property int|null $approved_by
 * @property Carbon|null $wisebee_created_at
 * @property Carbon $created_at
 * @property Carbon $updated_at
 *
 * @property WisebeeConsultation|null $consultation
 */
class WisebeeTranscript extends Model
{
    protected $table = 'wisebee_transcripts';

    protected $fillable = [
        'wisebee_id',
        'wisebee_consultation_id',
        'status',
        'transcript_text',
        'transcript_edited',
        'transcript_comments',
        'notes',
        'completed_at',
        'edited_at',
        'edited_by',
        'approved_at',
        'approved_by',
        'wisebee_created_at',
    ];

    protected $casts = [
        'transcript_text' => OptionalEncrypted::class,
        'transcript_edited' => OptionalEncrypted::class,
        'transcript_comments' => OptionalEncryptedArray::class,
        'notes' => OptionalEncrypted::class,
        'completed_at' => 'datetime',
        'edited_at' => 'datetime',
        'approved_at' => 'datetime',
        'wisebee_created_at' => 'datetime',
    ];

    public function consultation(): BelongsTo
    {
        return $this->belongsTo(WisebeeConsultation::class, 'wisebee_consultation_id', 'wisebee_id');
    }

    /**
     * Display text: edited version when present, else raw transcript.
     */
    public function getDisplayTextAttribute(): ?string
    {
        return $this->transcript_edited ?? $this->transcript_text;
    }

    /**
     * Whether the transcript has been approved upstream.
     */
    public function getIsApprovedAttribute(): bool
    {
        return !is_null($this->approved_at);
    }

    /**
     * Returns the modal-ready HTML body: status row, optional notes block, then
     * each transcript turn with the speaker bolded, with per-line comments
     * interleaved under the line they belong to. Reused by the admin
     * consultations list and any other server-rendered modal.
     */
    public function getFormattedContentAttribute(): string
    {
        $out = '<div class="transcriptModal__status">';
        if ($this->is_approved) {
            $approvedAt = $this->approved_at ? $this->approved_at->format('d/m/Y H:i') : '';
            $out .= '<i class="fa fa-check"></i> Approved ' . htmlspecialchars($approvedAt);
        } else {
            $out .= '<i class="fa fa-hourglass-half"></i> Not yet approved';
        }
        $out .= '</div>';

        if (!empty($this->notes)) {
            $out .= '<div class="transcriptModal__notes">'
                . '<strong>Prescriber notes:</strong> '
                . nl2br(htmlspecialchars((string) $this->notes))
                . '</div>';
        }

        $out .= '<div class="transcriptModal__transcript">';
        $comments = is_array($this->transcript_comments) ? $this->transcript_comments : [];
        $lines = preg_split("/\r?\n/", (string) $this->display_text);
        $visibleIndex = 0;
        foreach ($lines as $line) {
            if (trim($line) === '') {
                continue;
            }
            if (preg_match('/^([^:]{1,40}):\s*(.*)$/u', $line, $m)) {
                $out .= '<p class="transcriptModal__line"><strong>'
                    . htmlspecialchars($m[1]) . ':</strong> ' . htmlspecialchars($m[2]) . '</p>';
            } else {
                $out .= '<p class="transcriptModal__line">' . htmlspecialchars($line) . '</p>';
            }
            $lineComments = $comments[$visibleIndex] ?? $comments[(string) $visibleIndex] ?? null;
            if (is_array($lineComments)) {
                foreach ($lineComments as $c) {
                    if (!is_array($c)) {
                        continue;
                    }
                    $author = !empty($c['author']) ? htmlspecialchars($c['author']) : 'Comment';
                    $body = !empty($c['text']) ? htmlspecialchars($c['text']) : '';
                    $out .= '<div class="transcriptModal__comment"><strong>'
                        . $author . ':</strong> ' . $body . '</div>';
                }
            }
            $visibleIndex++;
        }
        $out .= '</div>';

        return $out;
    }
}
