<?php

namespace Espo\Modules\SmartAssistant\Hooks\Meeting;

use Espo\ORM\Entity;
use Espo\Core\InjectableFactory;
use Espo\Core\Utils\Log;
use Espo\Modules\SmartAssistant\Services\CaseMemoryService;

class HearingScheduledMemory
{
    private InjectableFactory $injectableFactory;
    private Log $log;

    public function __construct(InjectableFactory $injectableFactory, Log $log)
    {
        $this->injectableFactory = $injectableFactory;
        $this->log = $log;
    }

    public function afterSave(Entity $entity, array $options): void
    {
        if (!$entity->isNew()) return;
        if ($entity->get('parentType') !== 'Case' || !$entity->get('parentId')) return;

        $name = $entity->get('name') ?? '';
        $isHearing = mb_stripos($name, 'דיון') !== false || mb_stripos($name, 'hearing') !== false;
        if (!$isHearing) return;

        try {
            $service = $this->injectableFactory->create(CaseMemoryService::class);
            $service->createMemory(
                $entity->get('parentId'),
                'timeline',
                "דיון: " . $name,
                "נקבע דיון: {$name}\nתאריך: " . ($entity->get('dateStart') ?? 'לא ידוע'),
                'high', 'auto',
                'Meeting', $entity->get('id')
            );
        } catch (\Exception $e) {
            $this->log->warning("SmartAssistant: Failed to create hearing memory: " . $e->getMessage());
        }
    }
}
