<?php

namespace EstatebudConnect\Models;

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

class Field
{
    public $id;
    public $name;
    public $type;
    public $label;
    public $placeholder;
    public $value;
    public $options;
    public $required;
    public $advanced;
    public $multiple;
    public $range;
    public $conditional_field;
    public $conditional_value;
    public $width;
    public $minvalue;
    public $maxvalue;
    public $regex;
    public $crm_field;

    public function __construct(array $field = [])
    {
        $this->id = $field['id'] ?? '';
        $this->name = $field['name'] ?? '';
        $this->type = $field['type'] ?? '';
        $this->label = isset($field['label']) ? trim($field['label']) : '';
        $this->placeholder = isset($field['placeholder']) ? trim($field['placeholder']) : '';
        $this->value = $field['value'] ?? null;
        $this->options = $field['options'] ?? null;
        $this->required = $field['required'] ?? null;
        $this->advanced = $field['advanced'] ?? null;
        $this->multiple = $field['multiple'] ?? null;
        $this->range = $field['range'] ?? null;
        $this->conditional_field = $field['conditional_field'] ?? '';
        $this->conditional_value = $field['conditional_value'] ?? '';
        $this->width = $field['width'] ?? null;
        $this->minvalue = $field['minvalue'] ?? '';
        $this->maxvalue = $field['maxvalue'] ?? '';
        $this->regex = $field['regex'] ?? '';
        $this->crm_field = $field['crm_field'] ?? '';
    }

    public function get_id()
    {
        return $this->id;
    }

    public function get_name()
    {
        return $this->name;
    }

    public function get_type()
    {
        return $this->type;
    }

    public function get_label()
    {
        return $this->label;
    }

    public function get_placeholder()
    {
        return $this->placeholder;
    }

    public function get_value()
    {
        return $this->value;
    }

    public function get_normalized_type()
    {
        $type = strtolower(trim($this->get_type()));
        
        switch ($type) {
            case 'heading':
                return 'heading';
            case 'select':
                return 'select';
            case 'checkbox':
                return 'checkbox';
            case 'radio':
                return 'radio';
            case 'textarea':
                return 'textarea';
            case 'number':
            case 'integer':
            case 'decimal':
            case 'float':
            case 'text':
            case 'string':
                return 'text';
            default:
                return $type ?: 'text';
        }
    }

    public function is_type($type)
    {
        return strtolower(trim($this->get_type())) === strtolower(trim($type));
    }

    public function get_options()
    {
        if (!isset($this->options)) {
            return [];
        }

        return $this->parse_options_string($this->options);
    }

    private function parse_options_string($optionsString)
    {
        if (!is_string($optionsString)) {
            return [];
        }

        $normalized = str_replace(["\r\n", "\r"], "\n", $optionsString);
        $lines = array_map('trim', explode("\n", $normalized));
        $lines = array_filter($lines, fn($line) => $line !== '');

        if (count($lines) <= 1 && !str_contains($optionsString, "\n")) {
            $singleLine = trim($optionsString);
            if ($singleLine !== '' && strpos($singleLine, ',') !== false && strpos($singleLine, '|') === false) {
                $lines = array_map('trim', explode(',', $singleLine));
                $lines = array_filter($lines, fn($line) => $line !== '');
            }
        }

        $options = [];

        foreach ($lines as $line) {
            if ($line === '') {
                continue;
            }

            if (strpos($line, '|') !== false) {
                [$label, $value] = explode('|', $line, 2);
                $label = trim($label);
                $value = trim($value);
                if ($label === '') {
                    $label = $value;
                }
                if ($value === '') {
                    $value = $label;
                }
            } else {
                $label = $line;
                $value = $line;
            }

            if ($label === null || $label === '') {
                continue;
            }

            $options[] = [
                'label' => $label,
                'value' => $value ?? $label,
            ];
        }

        return $options;
    }

    public function get_raw_options()
    {
        return $this->options;
    }

    public function is_required()
    {
        return $this->required ?? false;
    }

    public function is_advanced()
    {
        return $this->advanced ?? false;
    }

    public function is_multiple()
    {
        return $this->multiple ?? false;
    }

    public function is_range()
    {
        return $this->range ?? false;
    }

    public function is_conditional()
    {
        return !empty($this->conditional_field) && !empty($this->conditional_value);
    }

    public function get_conditional_field()
    {
        return $this->conditional_field;
    }

    public function get_conditional_value()
    {
        return $this->conditional_value;
    }

    public function get_conditional_values()
    {
        $raw_value = $this->get_conditional_value();
        return $this->split_serialized_values($raw_value);
    }

    private function split_serialized_values($raw_value, $delimiter = '**')
    {
        if (!is_string($raw_value)) {
            return [];
        }

        $trimmed = trim($raw_value);
        if ($trimmed === '') {
            return [];
        }

        if (strpos($trimmed, $delimiter) !== false) {
            $parts = explode($delimiter, $trimmed);
            $parts = array_map('trim', $parts);
            $parts = array_filter($parts, fn($part) => $part !== '');
            return array_values($parts);
        }

        return [$trimmed];
    }

    public function get_width()
    {
        if (!isset($this->width)) {
            return null;
        }

        $width_int = intval($this->width);
        if ($width_int > 0 && $width_int <= 100) {
            return $width_int;
        }

        return null;
    }

    public function get_width_class()
    {
        $width = $this->get_width();
        if ($width === null) {
            return '';
        }

        return ' estatebud-form-field-w' . $width;
    }

    public function get_display_style()
    {
        if ($this->is_conditional()) {
            return 'display: none;';
        }

        return '';
    }

    public function get_shortcode()
    {
        $id = $this->get_id();
        if (empty($id)) {
            return '';
        }

        return '{{ field.' . $id . ' }}';
    }

    public function get_display_name()
    {
        $label = $this->get_label();
        if (!empty($label)) {
            return $label;
        }

        $placeholder = $this->get_placeholder();
        if (!empty($placeholder)) {
            return $placeholder;
        }

        return $this->get_id();
    }

    public function get_min_value()
    {
        return $this->minvalue;
    }

    public function get_max_value()
    {
        return $this->maxvalue;
    }

    public function validate_value($value)
    {
        if ($this->is_required() && empty($value)) {
            return 'empty';
        }
        
        $regex = $this->get_regex();
        if (!empty($regex) && !is_array($value) && !preg_match($regex, $value)) {
            return 'invalid';
        }

        if ($this->is_type('email') && !is_email($value)) {
            return 'invalid';
        }

        return true;
    }

    public function sanitize_value($value)
    {
        if ($value === null) {
            return null;
        }

        if (is_array($value)) {
            $value = array_map('sanitize_text_field', $value);
        } else if ($this->is_type('textarea')) {
            $value = sanitize_textarea_field($value);
        } else {
            $value = sanitize_text_field($value);
        }

        if ($this->is_type('email')) {
            $value = sanitize_email($value);
        }

        return $value;
    }

    public function get_regex()
    {
        return $this->regex;
    }

    public function get_crm_field()
    {
        return $this->crm_field;
    }


    public function to_array()
    {
        return get_object_vars($this);
    }
}

