<?php

namespace GriffinForms\Frontend\Security\Guards;

class AvailabilityWindowGuard implements GuardInterface
{
    public function getKey(): string
    {
        return 'availability_window';
    }

    public function getPriority(): int
    {
        return 10;
    }

    public function check(int $form_id, array $context = []): array
    {
        if ($form_id <= 0) {
            return ['blocked' => false];
        }

        $form = new \GriffinForms\Items\Form();
        if (!$form->loadItem($form_id)) {
            return ['blocked' => false];
        }

        $window = $form->getProp('availability_window');
        if (!is_array($window) || empty($window['toggle'])) {
            return ['blocked' => false];
        }

        $start_utc = isset($window['start_utc']) ? $window['start_utc'] : '';
        $end_utc = isset($window['end_utc']) ? $window['end_utc'] : '';
        $pre_message = isset($window['pre_message']) ? $window['pre_message'] : '';
        $post_message = isset($window['post_message']) ? $window['post_message'] : '';

        $default_pre = __('This form is not accepting submissions yet. Please check back later.', 'griffinforms-form-builder');
        $default_post = __('This form is no longer accepting submissions.', 'griffinforms-form-builder');

        $now = current_time('timestamp', true);

        if (!empty($start_utc)) {
            try {
                $start_ts = (new \DateTimeImmutable($start_utc, new \DateTimeZone('UTC')))->getTimestamp();
                if ($now < $start_ts) {
                    return [
                        'blocked' => true,
                        'message' => $pre_message !== '' ? $pre_message : $default_pre
                    ];
                }
            } catch (\Exception $e) {
                // Ignore malformed datetime and allow submission
            }
        }

        if (!empty($end_utc)) {
            try {
                $end_ts = (new \DateTimeImmutable($end_utc, new \DateTimeZone('UTC')))->getTimestamp();
                if ($now > $end_ts) {
                    return [
                        'blocked' => true,
                        'message' => $post_message !== '' ? $post_message : $default_post
                    ];
                }
            } catch (\Exception $e) {
                // Ignore malformed datetime and allow submission
            }
        }

        return ['blocked' => false];
    }
}
