<?php

namespace GriffinForms\Frontend\Security\Guards;

class LimitEntriesGuard implements GuardInterface
{
    public function getKey(): string
    {
        return 'limit_entries';
    }

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

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

        if (!empty($context['is_edit'])) {
            return ['blocked' => false];
        }

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

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

        $limit = isset($limit_entries['limit']) ? absint($limit_entries['limit']) : 0;
        if ($limit < 1) {
            return ['blocked' => false];
        }

        $count = 0;
        $form_lifetime = $form->getProp('lifetime_submission_count');
        if (is_numeric($form_lifetime)) {
            $count = absint($form_lifetime);
        }

        if ($count >= $limit) {
            $message = isset($limit_entries['message']) ? $limit_entries['message'] : '';
            if ($message === '') {
                $message = __('This form has reached the maximum number of submissions.', 'griffinforms-form-builder');
            }
            return [
                'blocked' => true,
                'message' => $message
            ];
        }

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