<?php

namespace Signteer\Core\Action\Signup;

use Signteer\Core\Action\ActionResult;
use Signteer\Core\Criteria\TaskCriteria;
use Signteer\Core\Criteria\SignupCriteria;
use Signteer\Core\Finder\TaskFinder;
use Signteer\Core\Finder\SignupFinder;
use Signteer\Core\Finder\VolunteerFinder;
use Signteer\Core\Finder\SheetFinder;
use Signteer\Core\Action\Email\SendEmail;

final class SendConfirmationEmailToVolunteer
{
    public $sendEmail = SendEmail::class;
    public $sheetFinder = SheetFinder::class;
    public $taskFinder = TaskFinder::class;
    public $signupFinder = SignupFinder::class;
    public $volunteerFinder = VolunteerFinder::class;
    // public $eventBus = EventBus::class;
    private bool $on = true;

    public function __invoke(int $signupId, ?string $subj = null, ?string $msg = null): ActionResult
    {
        $ret = new ActionResult();

        if (!$this->on) {
            return $ret;
        }

        $signup = $this->signupFinder->get($signupId);
        if (!$signup) {
            return $ret->addError('__Signup not found.__');
        }

        $volunteer = $this->volunteerFinder->get($signup->getVolunteerId());
        if (!$volunteer) {
            return $ret->addError('__Volunteer not found.__');
        }

        $to = $volunteer->getEmail();
        if (!strlen($to)) {
            return $ret->addError('__Volunteer email address unknown.__');
        }

        $taskId = $signup->getTaskId();
        $task = $this->taskFinder->get($taskId);
        if (!$task) {
            return $ret->addError('__Task not found.__');
        }

        $sheetId = $task->getSheetId();
        $sheet = $this->sheetFinder->get($sheetId);
        if (!$sheet) {
            return $ret->addError('__Sheet not found.__');
        }

        if (null === $subj) {
            list($subj, $msg) = $this->buildSubjectMessage($signupId);
        }

        $ret = ($this->sendEmail)($to, $subj, $msg);

        return $ret;
    }

    public function isEnabled(): bool
    {
        return $this->on;
    }

    public function disable(): self
    {
        $this->on = false;

        return $this;
    }

    public function enable(): self
    {
        $this->on = true;

        return $this;
    }

    public function buildSubjectMessage(int $signupId): array
    {
        $data = $this->prepareData($signupId);

        list($subj, $msg) = $this->getTemplate();

        foreach ($data as $k => $v) {
            $subj = str_replace('{' . $k . '}', $v, $subj);
            $msg = str_replace('{' . $k . '}', $v, $msg);
        }

        return [$subj, $msg];
    }

    public function getTemplate(): array
    {
        $ret = [];
        $ret[] = 'Thanks for signing up!';
        $ret[] = 'Dear {volunteer_name},' . PHP_EOL;
        $ret[] = 'thanks for signing up! Here are the sign-up details:' . PHP_EOL;
        $ret[] = '{sheet_title}';
        $ret[] = 'Date: {sheet_date}';
        $ret[] = 'Task: {task_title}';

        $subj = array_shift($ret);
        $msg = join(PHP_EOL, $ret);

        return [$subj, $msg];
    }

    public function getTemplateVariables(): array
    {
        return [
            'sheet_date',
            'sheet_title',
            'task_title',
            'volunteer_name',
            'volunteer_email',
            'volunteer_phone',
            'sheet_url',
            'sheet_title',
        ];
    }

    private function prepareData(int $signupId): ?array
    {
        $signup = $this->signupFinder->get($signupId);
        if (!$signup) {
            return null;
            return $ret->addError('__Signup not found.__');
        }

        $taskId = $signup->getTaskId();
        $task = $this->taskFinder->get($taskId);
        if (!$task) {
            return null;
            return $ret->addError('__Task not found.__');
        }

        $sheetId = $task->getSheetId();
        $sheet = $this->sheetFinder->get($sheetId);
        if (!$sheet) {
            return null;
            return $ret->addError('__Sheet not found.__');
        }

        $volunteer = $this->volunteerFinder->get($signup->getVolunteerId());
        if (!$volunteer) {
            return null;
        }

        $ret = [];

        $ret['sheet_date'] = esc_html($sheet->getTitle());
        $ret['sheet_title'] = esc_html($sheet->getTitle());
        $ret['task_title'] = esc_html($task->getTitle());

        $ret['volunteer_name'] = esc_html($volunteer->getTitle());
        $ret['volunteer_email'] = sanitize_email($volunteer->getEmail());
        $ret['volunteer_phone'] = esc_html($volunteer->getPhone());

        // $ret['site_url'] = get_bloginfo('url');
        $ret['sheet_url'] = esc_html(get_post_permalink($sheetId));
        $ret['sheet_title'] = esc_html($sheet->getTitle());

        return $ret;
    }
}
