<?php
declare(strict_types=1);

namespace App\Modules\Forms\Services;

use App\Core\Validator;
use App\Modules\Forms\Models\FormSchema;

final class FormValidator
{
    public static function validate(FormSchema $schema, array $submittedData): array
    {
        $sections = $schema->getSections();
        $rules = [];
        $allErrors = [];

        foreach ($sections as $section) {
            $visibleWhen = $section['visible_when'] ?? null;
            if ($visibleWhen && !self::evaluateCondition($visibleWhen, $submittedData)) {
                continue;
            }

            foreach ($section['fields'] ?? [] as $field) {
                $key = $field['key'] ?? '';
                $fieldVisible = true;

                $fieldVisibleWhen = $field['visible_when'] ?? null;
                if ($fieldVisibleWhen && !self::evaluateCondition($fieldVisibleWhen, $submittedData)) {
                    $fieldVisible = false;
                }

                if (!$fieldVisible) {
                    continue;
                }

                $validation = $field['validation'] ?? '';
                $required = $field['required'] ?? false;
                $editable = $field['editable'] ?? true;
                $type = $field['type'] ?? 'text';

                if (!$editable || $type === 'computed' || $type === 'currency' || $type === 'static_text' || $type === 'auto_increment') {
                    continue;
                }

                if ($validation !== '') {
                    $rules[$key] = $validation;
                } elseif ($required) {
                    $rules[$key] = 'required|string';
                } else {
                    $rules[$key] = 'nullable';
                }
            }
        }

        if (empty($rules)) {
            return ['errors' => [], 'validated' => $submittedData];
        }

        $validator = new Validator();
        $result = $validator->validate($submittedData, $rules);

        return [
            'errors'    => $result->errors(),
            'validated' => $result->validated(),
            'passes'    => $result->passes(),
        ];
    }

    private static function evaluateCondition(array $condition, array $data): bool
    {
        $field = $condition['field'] ?? '';
        $operator = $condition['operator'] ?? 'eq';
        $value = $condition['value'] ?? '';
        $actual = $data[$field] ?? '';

        return match ($operator) {
            'eq'  => (string) $actual === (string) $value,
            'neq' => (string) $actual !== (string) $value,
            'in'  => in_array((string) $actual, (array) $value, true),
            'gt'  => (float) $actual > (float) $value,
            'lt'  => (float) $actual < (float) $value,
            'gte' => (float) $actual >= (float) $value,
            'lte' => (float) $actual <= (float) $value,
            'not_empty' => $actual !== '' && $actual !== null,
            'empty'     => $actual === '' || $actual === null,
            default     => true,
        };
    }
}