<?php

namespace GriffinForms\Includes\MailTemplates;

class Format extends \GriffinForms\Format
{
    protected $data;

    // Get the subject of the admin alert
    public function getSubject()
    {
        return $this->subject;
    }

    // Get the content of the admin alert
    public function getContent()
    {
        return $this->content;
    }

    protected function getFormName()
    {
        if (!empty($this->data['form'])) {
            // Get form name or heading
            if (!empty($this->data['form']->getProp('name'))) {
                $form_name = $this->data['form']->getProp('name');
            } else if (!empty($this->data['form']->getProp('heading'))) {
                $form_name = $this->data['form']->getProp('heading');
            } else {
                $form_id = $this->data['form']->getProp('id');
                /* translators: %d is the numeric ID of the form used as fallback when name and heading are unavailable */
                $form_name = sprintf(__('Form ID %d', 'griffinforms-form-builder'), $form_id);
            }
    
            // Truncate the form name if it exceeds 50 characters
            if (mb_strlen($form_name) > 50) {
                $form_name = mb_strimwidth($form_name, 0, 47, '...');
            }

            return $form_name;
        }
    }

    protected function getSubmissionTime()
    {
        // Attempt to get the submission time
        try {
            if (!empty($this->data['submission']['created'])) {
                $submission_time = strtotime($this->data['submission']['created']);
                if ($submission_time === false || $submission_time == -1) {
                    // If strtotime fails, fallback to the current time
                    throw new \Exception('Invalid submission time.');
                }
            } else {
                // If the 'created' key is empty, fallback to the current time
                throw new \Exception('Missing submission time.');
            }
        } catch (\Exception $e) {
            $submission_time = current_time('timestamp');
        }

        // Format the time (either submission time or current time)
        return wp_date(get_option('date_format') . ' ' . get_option('time_format'), $submission_time);
    }

    public function __construct($data = [])
    {
        $this->data = $data;
        $this->processSubject();
        $this->processContent();
    }
}