<?php

namespace Signteer\Core\Helper;

use Signteer\Core\Criteria\TaskCriteria;
use Signteer\Core\Criteria\SignupCriteria;
use Signteer\Core\Finder\TaskFinder;
use Signteer\Core\Finder\SignupFinder;
use Signteer\Core\Finder\SheetFinder;

final class SignupNotificationHelper
{
    public $sheetFinder = SheetFinder::class;
    public $taskFinder = TaskFinder::class;
    public $signupFinder = SignupFinder::class;

    public function buildSubjectBody(int $signupId, string $subject, string $body): array
    {
        $data = $this->prepareData($signupId);

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

        return [$subject, $body];
    }

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

    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.__');
        }

        $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($signup->getTitle());
        $ret['volunteer_email'] = sanitize_email($signup->getEmail());
        $ret['volunteer_phone'] = esc_html($signup->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;
    }
}
