<?php

namespace EstatebudConnect\Models;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Configs\Defaults;
use EstatebudConnect\Core\OptionsAPI;
use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Utilities\Helper;

class Forms
{
    private const OPTIONS_KEY = 'forms';

    use Singleton;

    public function __construct() {}

    public function get_all_forms()
    {
        $data = OptionsAPI::instance()->get(self::OPTIONS_KEY, []);
        return $data ?? [];
    }

    public function get_form($id)
    {
        $forms = $this->get_all_forms();
        foreach ($forms as $form) {
            if ($form['id'] === $id) {
                return array_merge(Defaults::FORM, $form);
            }
        }
        return null;
    }

    public function add_form($form_data)
    {
        $parsed_data = $this->parse_input_data($form_data);

        $forms = $this->get_all_forms();
        $id = Helper::get_random_string();
        $parsed_data['id'] = $id;
        foreach ($forms as $form) {
            if (isset($parsed_data['id']) && $form['id'] === $parsed_data['id']) {
                return false;
            }
        }

        $forms[] = $parsed_data;
        return OptionsAPI::instance()->update(self::OPTIONS_KEY, $forms, true);
    }

    public function update_form($id, $new_data)
    {
        $parsed_data = $this->parse_input_data($new_data);

        $forms = $this->get_all_forms();
        foreach ($forms as &$form) {
            if ($form['id'] === $id) {
                $form = $parsed_data;
                OptionsAPI::instance()->update(self::OPTIONS_KEY, $forms, true);
                return true;
            }
        }
        return false;
    }

    public function delete_form($ids)
    {
        if (!is_array($ids) || empty($ids)) {
            return false;
        }

        $forms = $this->get_all_forms();

        $new_forms = array_values(
            array_filter($forms, function ($form) use ($ids) {
                return !in_array($form['id'], $ids);
            }),
        );

        $result = OptionsAPI::instance()->update(self::OPTIONS_KEY, array_values($new_forms), true);
        return $result;
    }

    public function clone_form($id)
    {
        $forms = $this->get_all_forms();
        $form_to_clone = null;

        foreach ($forms as $form) {
            if ($form['id'] === $id) {
                $form_to_clone = $form;
                break;
            }
        }

        if (!$form_to_clone) {
            return false;
        }

        $cloned_form = $form_to_clone;
        $cloned_form['id'] = Helper::get_random_string();
        $cloned_form['name'] = $form_to_clone['name'] . ' (Copy)';

        $forms[] = $cloned_form;

        $result = OptionsAPI::instance()->update(self::OPTIONS_KEY, $forms, true);
        return $result ? $forms : false;
    }

    protected function parse_input_data($form_data)
    {
        $defaults = Defaults::FORM;
        $parsed_form_data = [];

        foreach ($form_data as $index_1 => $data_1) {
            $index_1 = sanitize_text_field(wp_unslash($index_1));
            $data_1 = wp_unslash($data_1);

            if (!isset($defaults[$index_1])) {
                continue;
            }

            if (is_array($data_1)) {
                $textareas = [];
                $booleans = [];

                if (!isset($parsed_form_data[$index_1])) {
                    $parsed_form_data[$index_1] = [];
                }

                foreach ($data_1 as $index_2 => $data_2) {
                    $index_2 = sanitize_text_field(wp_unslash($index_2));
                    $data_2 = wp_unslash($data_2);

                    if (is_array($data_2)) {
                        $textareas = ['options'];
                        $booleans = ['advanced', 'multiple', 'range', 'required'];

                        if (!isset($parsed_form_data[$index_1][$index_2])) {
                            $parsed_form_data[$index_1][$index_2] = [];
                        }

                        foreach ($data_2 as $index_3 => $data_3) {
                            $index_3 = sanitize_text_field(wp_unslash($index_3));
                            $data_3 = wp_unslash($data_3);
                        
                            if (is_array($data_3)) {
                                $value = array_map('sanitize_text_field', $data_3);
                                $value = array_filter($value, fn($v) => $v !== '');
                                $value = empty($value) ? null : array_values($value);
                            } else if (in_array($index_3, $booleans)) {
                                $value = filter_var($data_3, FILTER_VALIDATE_BOOLEAN);
                            } else if (in_array($index_3, $textareas)) {
                                $value = sanitize_textarea_field($data_3);
                            } else {
                                $value = sanitize_text_field($data_3);
                            }
                            $parsed_form_data[$index_1][$index_2][$index_3] = $value;
                        }

                        if ($index_1 === 'fields' && empty($parsed_form_data[$index_1][$index_2]['name'])) {
                            $parsed_form_data[$index_1][$index_2]['name'] = Helper::generate_field_name($parsed_form_data[$index_1][$index_2]);
                        }
                    } else {
                        if (in_array($index_2, $booleans)) {
                            $value = filter_var($data_2, FILTER_VALIDATE_BOOLEAN);
                        } else if (in_array($index_2, $textareas)) {
                            $value = sanitize_textarea_field($data_2);
                        } else {
                            $value = sanitize_text_field($data_2);
                        }

                        $parsed_form_data[$index_1][$index_2] = $value;
                    }
                }
            } else {
                $textareas = ['email_message', 'confirmation_email_message'];
                $booleans = ['is_button_available'];

                if (in_array($index_1, $booleans)) {
                    $value = filter_var($data_1, FILTER_VALIDATE_BOOLEAN);
                } else if (in_array($index_1, $textareas)) {
                    $value = sanitize_textarea_field($data_1);
                } else {
                    $value = sanitize_text_field($data_1);
                }

                $parsed_form_data[$index_1] = $value;
            }
        }
        
        return $parsed_form_data;
    }
}
