<?php

namespace GriffinForms\Includes\Onboarding;

use GriffinForms\Traits\Singleton;

class StarterCatalog extends \GriffinForms\Format
{
    use Singleton;

    public function getGoals(): array
    {
        $goals = [
            'collect_enquiries' => [
                'label' => __('Collect enquiries', 'griffinforms-form-builder'),
                'description' => __('Use this when you want visitors to contact you, ask questions, or send a general enquiry.', 'griffinforms-form-builder'),
                'form_name' => __('Contact Enquiry Form', 'griffinforms-form-builder'),
                'page_title' => __('Contact Us', 'griffinforms-form-builder'),
                'form_heading' => __('Get in touch', 'griffinforms-form-builder'),
                'form_description' => __('Use this form to collect enquiries, contact requests, and general questions.', 'griffinforms-form-builder'),
                'default_fields' => ['full_name', 'email_address', 'subject', 'message', 'consent'],
                'optional_fields' => ['phone', 'company'],
                'icon' => 'collect-enquiries.svg',
            ],
            'capture_leads' => [
                'label' => __('Capture leads', 'griffinforms-form-builder'),
                'description' => __('Use this when you want potential customers to share their details and tell you what they need.', 'griffinforms-form-builder'),
                'form_name' => __('Lead Capture Form', 'griffinforms-form-builder'),
                'page_title' => __('Request Information', 'griffinforms-form-builder'),
                'form_heading' => __('Tell us about your project', 'griffinforms-form-builder'),
                'form_description' => __('Use this form to capture lead details and follow up with interested customers.', 'griffinforms-form-builder'),
                'default_fields' => ['full_name', 'email_address', 'phone', 'company', 'project_brief', 'consent'],
                'optional_fields' => ['subject'],
                'icon' => 'capture-leads.svg',
            ],
            'handle_support_requests' => [
                'label' => __('Handle support requests', 'griffinforms-form-builder'),
                'description' => __('Use this when customers need help and you want the right details up front to respond faster.', 'griffinforms-form-builder'),
                'form_name' => __('Support Request Form', 'griffinforms-form-builder'),
                'page_title' => __('Support', 'griffinforms-form-builder'),
                'form_heading' => __('Support request', 'griffinforms-form-builder'),
                'form_description' => __('Use this form to collect support requests, issue details, and any files that help explain the problem.', 'griffinforms-form-builder'),
                'default_fields' => ['full_name', 'email_address', 'subject', 'priority', 'message', 'attachment', 'consent'],
                'optional_fields' => ['phone'],
                'icon' => 'handle-support-requests.svg',
            ],
            'general_purpose' => [
                'label' => __('General purpose', 'griffinforms-form-builder'),
                'description' => __('Use this when none of the other options fit and you want a flexible form for general use.', 'griffinforms-form-builder'),
                'form_name' => __('General Purpose Form', 'griffinforms-form-builder'),
                'page_title' => __('Contact', 'griffinforms-form-builder'),
                'form_heading' => __('General enquiry', 'griffinforms-form-builder'),
                'form_description' => __('Use this form when you need a flexible setup that can be adapted for many different purposes.', 'griffinforms-form-builder'),
                'default_fields' => ['full_name', 'email_address', 'message'],
                'optional_fields' => ['phone', 'company', 'subject', 'attachment', 'consent'],
                'icon' => 'general-purpose.svg',
            ],
            'user_registration' => [
                'label' => __('User registration', 'griffinforms-form-builder'),
                'description' => __('Use this when you want to collect signups and create WordPress user accounts from the submitted form.', 'griffinforms-form-builder'),
                'form_name' => __('User Registration Form', 'griffinforms-form-builder'),
                'page_title' => __('Register', 'griffinforms-form-builder'),
                'form_heading' => __('Create your account', 'griffinforms-form-builder'),
                'form_description' => __('Sign up to create your account.', 'griffinforms-form-builder'),
                'default_fields' => ['email_address'],
                'optional_fields' => ['first_name', 'last_name', 'username', 'password'],
                'icon' => 'user-registration.svg',
            ],
        ];

        $goals = apply_filters('griffinforms_onboarding_goals', $goals);

        if (!is_array($goals)) {
            return [];
        }

        $normalized_goals = [];
        foreach ($goals as $goal_key => $goal) {
            $goal_key = sanitize_key((string) $goal_key);
            if ($goal_key === '' || !is_array($goal)) {
                continue;
            }

            $normalized_goal = $this->normalizeGoalDefinition($goal);
            if ($normalized_goal === null) {
                continue;
            }

            $normalized_goal['starter_goal_key'] = $goal_key;
            $normalized_goals[$goal_key] = $normalized_goal;
        }

        return $normalized_goals;
    }

    public function getGoal(string $goal_key): ?array
    {
        $goal_key = sanitize_key($goal_key);
        $goals = $this->getGoals();

        return $goals[$goal_key] ?? null;
    }

    public function getFieldLibrary(): array
    {
        return [
            'full_name' => [
                'field_type' => 'inputtext',
                'name' => __('Full Name', 'griffinforms-form-builder'),
                'heading' => __('Full Name', 'griffinforms-form-builder'),
                'description' => __('Enter your full name.', 'griffinforms-form-builder'),
                'is_required' => 1,
                'placeholder' => __('John Doe', 'griffinforms-form-builder'),
            ],
            'email_address' => [
                'field_type' => 'inputemail',
                'name' => __('Email Address', 'griffinforms-form-builder'),
                'heading' => __('Email Address', 'griffinforms-form-builder'),
                'description' => __('Use an email address you can access.', 'griffinforms-form-builder'),
                'is_required' => 1,
                'placeholder' => __('you@example.com', 'griffinforms-form-builder'),
            ],
            'phone' => [
                'field_type' => 'inputphone',
                'name' => __('Phone Number', 'griffinforms-form-builder'),
                'heading' => __('Phone Number', 'griffinforms-form-builder'),
                'description' => __('Optional, include country code.', 'griffinforms-form-builder'),
                'is_required' => 0,
                'placeholder' => __('+1 (555) 987-6543', 'griffinforms-form-builder'),
            ],
            'company' => [
                'field_type' => 'inputtext',
                'name' => __('Company', 'griffinforms-form-builder'),
                'heading' => __('Company', 'griffinforms-form-builder'),
                'description' => __('Enter your company or organization name.', 'griffinforms-form-builder'),
                'is_required' => 0,
                'placeholder' => __('Acme Inc.', 'griffinforms-form-builder'),
            ],
            'first_name' => [
                'field_type' => 'inputtext',
                'name' => __('First Name', 'griffinforms-form-builder'),
                'heading' => __('First Name', 'griffinforms-form-builder'),
                'description' => '',
                'is_required' => 0,
                'placeholder' => __('John', 'griffinforms-form-builder'),
            ],
            'last_name' => [
                'field_type' => 'inputtext',
                'name' => __('Last Name', 'griffinforms-form-builder'),
                'heading' => __('Last Name', 'griffinforms-form-builder'),
                'description' => '',
                'is_required' => 0,
                'placeholder' => __('Doe', 'griffinforms-form-builder'),
            ],
            'username' => [
                'field_type' => 'inputtext',
                'name' => __('Username', 'griffinforms-form-builder'),
                'heading' => __('Username', 'griffinforms-form-builder'),
                'description' => __('Choose a username for your account.', 'griffinforms-form-builder'),
                'is_required' => 0,
                'placeholder' => __('johndoe', 'griffinforms-form-builder'),
            ],
            'password' => [
                'field_type' => 'inputpassword',
                'name' => __('Password', 'griffinforms-form-builder'),
                'heading' => __('Password', 'griffinforms-form-builder'),
                'description' => __('Create a password for your account.', 'griffinforms-form-builder'),
                'is_required' => 1,
                'placeholder' => '',
                'validations' => [
                    'field_type' => 'inputpassword',
                    'type' => 'custom-parameters',
                    'min_strength' => 'strong',
                ],
                'field_settings' => [
                    'display_strength_meter' => 1,
                    'show_password_toggle' => 1,
                    'autocomplete_mode' => 'new-password',
                    'require_confirmation' => 1,
                    'confirmation_label' => __('Confirm Password', 'griffinforms-form-builder'),
                    'confirmation_message' => __('Please confirm your password.', 'griffinforms-form-builder'),
                    'encrypt_passwords' => 0,
                    'encryption_key' => '',
                ],
            ],
            'subject' => [
                'field_type' => 'inputtext',
                'name' => __('Subject', 'griffinforms-form-builder'),
                'heading' => __('Subject', 'griffinforms-form-builder'),
                'description' => __('Add a short summary for this request.', 'griffinforms-form-builder'),
                'is_required' => 1,
                'placeholder' => __('How can we help?', 'griffinforms-form-builder'),
            ],
            'message' => [
                'field_type' => 'textarea',
                'name' => __('Message', 'griffinforms-form-builder'),
                'heading' => __('Message', 'griffinforms-form-builder'),
                'description' => __('Share the details of your request.', 'griffinforms-form-builder'),
                'is_required' => 1,
                'placeholder' => __('Type your message here...', 'griffinforms-form-builder'),
            ],
            'project_brief' => [
                'field_type' => 'textarea',
                'name' => __('Project Brief', 'griffinforms-form-builder'),
                'heading' => __('Project Brief', 'griffinforms-form-builder'),
                'description' => __('Share what you need and any useful background details.', 'griffinforms-form-builder'),
                'is_required' => 1,
                'placeholder' => __('Tell us what you are looking for...', 'griffinforms-form-builder'),
            ],
            'priority' => [
                'field_type' => 'selectfield',
                'name' => __('Priority', 'griffinforms-form-builder'),
                'heading' => __('Priority', 'griffinforms-form-builder'),
                'description' => __('Choose the urgency of this request.', 'griffinforms-form-builder'),
                'is_required' => 1,
                'field_options' => [
                    '' => [
                        __('Low', 'griffinforms-form-builder') => 'low',
                        __('Normal', 'griffinforms-form-builder') => 'normal',
                        __('High', 'griffinforms-form-builder') => 'high',
                        __('Urgent', 'griffinforms-form-builder') => 'urgent',
                    ],
                ],
            ],
            'attachment' => [
                'field_type' => 'fileupload',
                'name' => __('Attachment', 'griffinforms-form-builder'),
                'heading' => __('Attachment', 'griffinforms-form-builder'),
                'description' => __('Upload a file if it helps explain the request.', 'griffinforms-form-builder'),
                'is_required' => 0,
            ],
            'consent' => [
                'field_type' => 'inputcheckbox',
                'name' => __('Permission to Contact', 'griffinforms-form-builder'),
                'heading' => __('I agree to be contacted about this request', 'griffinforms-form-builder'),
                'description' => __('Tick to allow follow-up about your submission.', 'griffinforms-form-builder'),
                'is_required' => 0,
                'field_options' => [
                    [
                        __('Yes', 'griffinforms-form-builder') => 'yes',
                    ],
                ],
            ],
        ];
    }

    public function getBlankFormStarterFieldOptions(): array
    {
        $options = [
            'full_name' => [
                'label' => __('Name', 'griffinforms-form-builder'),
                'description' => __('Add a starter name field.', 'griffinforms-form-builder'),
            ],
            'email_address' => [
                'label' => __('Email', 'griffinforms-form-builder'),
                'description' => __('Collect an email address.', 'griffinforms-form-builder'),
            ],
            'phone' => [
                'label' => __('Phone', 'griffinforms-form-builder'),
                'description' => __('Collect a phone number.', 'griffinforms-form-builder'),
            ],
            'subject' => [
                'label' => __('Subject', 'griffinforms-form-builder'),
                'description' => __('Add a short subject line.', 'griffinforms-form-builder'),
            ],
            'message' => [
                'label' => __('Message', 'griffinforms-form-builder'),
                'description' => __('Add a longer message field.', 'griffinforms-form-builder'),
            ],
        ];

        $options = apply_filters('griffinforms_blank_form_starter_field_options', $options);

        return is_array($options) ? $options : [];
    }

    public function getFieldDefinition(string $field_key): ?array
    {
        $field_key = sanitize_key($field_key);
        $fields = $this->getFieldLibrary();

        return $fields[$field_key] ?? null;
    }

    public function getFieldLabel(string $field_key): string
    {
        $field_definition = $this->getFieldDefinition($field_key);
        if (!$field_definition) {
            return '';
        }

        return (string) ($field_definition['heading'] ?? $field_definition['name'] ?? $field_key);
    }

    public function getStarterFieldKeys(string $goal_key, array $toggle_keys = []): array
    {
        $goal = $this->getGoal($goal_key);
        if (!$goal) {
            return [];
        }

        $field_keys = $goal['default_fields'];
        foreach ($this->sanitizeToggleKeys($goal_key, $toggle_keys) as $toggle_key) {
            if (!in_array($toggle_key, $field_keys, true)) {
                $field_keys[] = $toggle_key;
            }
        }

        return array_values($field_keys);
    }

    public function sanitizeToggleKeys(string $goal_key, array $toggle_keys): array
    {
        $goal = $this->getGoal($goal_key);
        if (!$goal) {
            return [];
        }

        $allowed_toggle_keys = $goal['optional_fields'] ?? [];
        $sanitized_toggle_keys = array_values(array_unique(array_filter(array_map('sanitize_key', $toggle_keys))));

        return array_values(array_intersect($sanitized_toggle_keys, $allowed_toggle_keys));
    }

    public function getToggleDefinitions(string $goal_key): array
    {
        $goal = $this->getGoal($goal_key);
        if (!$goal) {
            return [];
        }

        $definitions = [];
        foreach ($goal['optional_fields'] as $field_key) {
            $field_definition = $this->getFieldDefinition($field_key);
            if (!$field_definition) {
                continue;
            }

            $definitions[$field_key] = [
                'label' => $this->getFieldLabel($field_key),
                'description' => (string) ($field_definition['description'] ?? ''),
            ];
        }

        return $definitions;
    }

    protected function normalizeGoalDefinition(array $goal): ?array
    {
        $required_keys = ['label', 'description', 'form_name', 'page_title', 'form_heading', 'form_description', 'default_fields', 'optional_fields', 'icon'];
        foreach ($required_keys as $required_key) {
            if (!array_key_exists($required_key, $goal)) {
                return null;
            }
        }

        $default_fields = is_array($goal['default_fields']) ? array_values(array_unique(array_filter(array_map('sanitize_key', $goal['default_fields'])))) : [];
        $optional_fields = is_array($goal['optional_fields']) ? array_values(array_unique(array_filter(array_map('sanitize_key', $goal['optional_fields'])))) : [];

        if (empty($default_fields)) {
            return null;
        }

        return [
            'starter_goal_key' => sanitize_key((string) ($goal['starter_goal_key'] ?? '')),
            'label' => sanitize_text_field((string) $goal['label']),
            'description' => sanitize_text_field((string) $goal['description']),
            'form_name' => sanitize_text_field((string) $goal['form_name']),
            'page_title' => sanitize_text_field((string) $goal['page_title']),
            'form_heading' => sanitize_text_field((string) $goal['form_heading']),
            'form_description' => sanitize_text_field((string) $goal['form_description']),
            'default_fields' => $default_fields,
            'optional_fields' => $optional_fields,
            'icon' => sanitize_file_name((string) $goal['icon']),
        ];
    }
}
