<?php

namespace GriffinForms\Includes\Onboarding;

use GriffinForms\Traits\Singleton;

class Eligibility extends \GriffinForms\Format
{
    use Singleton;

    protected $feature_flags;
    protected $user_state_repository;
    protected $admin_sql;

    protected function setFeatureFlags()
    {
        $this->feature_flags = FeatureFlags::getInstance();
    }

    protected function setUserStateRepository()
    {
        $this->user_state_repository = UserStateRepository::getInstance();
    }

    protected function setAdminSql()
    {
        $this->admin_sql = \GriffinForms\Admin\Sql\Format::getInstance();
    }

    public function canAccessOnboardingPage(int $user_id = 0): bool
    {
        return $this->canManageOptions($user_id)
            && $this->feature_flags->isEnabled('enabled')
            && $this->feature_flags->isEnabled('page_access')
            && !empty($this->feature_flags->getFirstEnabledStep());
    }

    public function shouldRedirectToOnboarding(int $user_id = 0): bool
    {
        if (!$this->canManageOptions($user_id)) {
            return false;
        }

        if (!$this->feature_flags->isEnabled('enabled')
            || !$this->feature_flags->isEnabled('page_access')
            || !$this->feature_flags->isEnabled('activation_redirect')
            || !$this->hasZeroForms()
        ) {
            return false;
        }

        $state = $this->user_state_repository->getState($user_id);
        if ($state['experience_version'] !== $this->feature_flags->getExperienceVersion()) {
            return true;
        }

        return empty($state['dismissed']) && empty($state['completed']);
    }

    public function shouldShowFormsEmptyStateCta(int $user_id = 0): bool
    {
        return $this->canManageOptions($user_id)
            && $this->feature_flags->isEnabled('enabled')
            && $this->feature_flags->isEnabled('page_access')
            && $this->feature_flags->isEnabled('forms_empty_state_cta')
            && $this->hasZeroForms();
    }

    public function hasZeroForms(): bool
    {
        return $this->getFormCount() < 1;
    }

    public function getFormCount(): int
    {
        return (int) $this->admin_sql->getItemCount('form');
    }

    protected function canManageOptions(int $user_id = 0): bool
    {
        if ($user_id > 0) {
            $user = get_user_by('id', $user_id);
            return $user ? user_can($user, 'manage_options') : false;
        }

        return current_user_can('manage_options');
    }
}
