<?php

require_once __DIR__ . '/../../core/format.php';
require_once __DIR__ . '/../../core/location.php';

if (!function_exists('icylab_customer_form_safe')) {
    function icylab_customer_form_safe($value)
    {
        return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('icylab_customer_form_value')) {
    function icylab_customer_form_value(array $values, $name, $default = '')
    {
        return array_key_exists($name, $values) ? $values[$name] : $default;
    }
}

if (!function_exists('icylab_customer_form_error')) {
    function icylab_customer_form_error(array $errors, $name)
    {
        return isset($errors[$name]) ? trim((string)$errors[$name]) : '';
    }
}

if (!function_exists('icylab_render_country_select')) {
    function icylab_render_country_select($name, $selected = 'Chile', $required = true)
    {
        $selected = trim((string)($selected ?: 'Chile'));
        $selectedCode = icylab_country_code_from_value($selected);
        $requiredAttr = $required ? ' required' : '';
        echo '<select class="select" name="' . icylab_customer_form_safe($name) . '" data-location-country="true"' . $requiredAttr . '>';
        foreach (icylab_country_options() as $country) {
            $isSelected = ($country['code'] !== '' && $country['code'] === $selectedCode) || mb_strtolower($country['name'], 'UTF-8') === mb_strtolower($selected, 'UTF-8');
            echo '<option value="' . icylab_customer_form_safe($country['name']) . '" data-country-code="' . icylab_customer_form_safe($country['code']) . '" data-phone-prefix="' . icylab_customer_form_safe($country['phone_prefix']) . '"' . ($isSelected ? ' selected' : '') . '>' . icylab_customer_form_safe($country['flag'] . ' ' . $country['name']) . '</option>';
        }
        echo '</select>';
    }
}

if (!function_exists('icylab_render_phone_prefix_select')) {
    function icylab_render_phone_prefix_select($id, $selectedPrefix = '+56')
    {
        $selectedPrefix = trim((string)($selectedPrefix ?: '+56'));
        echo '<select id="' . icylab_customer_form_safe($id) . '" class="input customer-phone-prefix" data-phone-prefix-select="true">';
        $seen = array();
        foreach (icylab_country_options() as $country) {
            $prefix = $country['phone_prefix'];
            if ($prefix === '' || isset($seen[$prefix])) continue;
            $seen[$prefix] = true;
            echo '<option value="' . icylab_customer_form_safe($prefix) . '"' . ($prefix === $selectedPrefix ? ' selected' : '') . '>' . icylab_customer_form_safe($country['flag'] . ' ' . $prefix) . '</option>';
        }
        echo '</select>';
    }
}


if (!function_exists('icylab_render_payment_terms_select')) {
    function icylab_render_payment_terms_select($name = 'payment_terms', $selected = 'contado', $required = false, $class = 'select')
    {
        $selected = icylab_normalize_payment_terms($selected);
        $requiredAttr = $required ? ' required' : '';
        echo '<select class="' . icylab_customer_form_safe($class) . '" name="' . icylab_customer_form_safe($name) . '"' . $requiredAttr . '>';
        foreach (icylab_payment_terms_options() as $value => $label) {
            echo '<option value="' . icylab_customer_form_safe($value) . '"' . ($value === $selected ? ' selected' : '') . '>' . icylab_customer_form_safe($label) . '</option>';
        }
        echo '</select>';
    }
}

if (!function_exists('icylab_render_customer_quick_fields')) {
    function icylab_render_customer_quick_fields(array $options = array())
    {
        $values = isset($options['values']) && is_array($options['values']) ? $options['values'] : array();
        $errors = isset($options['errors']) && is_array($options['errors']) ? $options['errors'] : array();
        $nameField = $options['name_field'] ?? 'customer_name';
        $taxField = $options['tax_field'] ?? 'customer_tax_id';
        $taxId = $options['tax_id'] ?? '';
        $phonePrefixId = $options['phone_prefix_id'] ?? 'customer_phone_prefix';
        $phoneNumberId = $options['phone_number_id'] ?? 'customer_phone_number';
        $phoneHiddenId = $options['phone_hidden_id'] ?? 'customer_real_phone_input';
        $phoneValue = trim((string)icylab_customer_form_value($values, 'phone', ''));
        $selectedCountry = icylab_customer_form_value($values, 'country', 'Chile') ?: 'Chile';
        $phonePrefix = '+56';
        $phoneNumber = $phoneValue;
        if (preg_match('/^(\+\d{1,4})\s*(.*)$/', $phoneValue, $m)) {
            $phonePrefix = $m[1];
            $phoneNumber = $m[2];
        } else {
            $countryCode = icylab_country_code_from_value($selectedCountry);
            foreach (icylab_country_options() as $country) {
                if ($country['code'] === $countryCode && $country['phone_prefix'] !== '') {
                    $phonePrefix = $country['phone_prefix'];
                    break;
                }
            }
        }

        $required = isset($options['required']) && is_array($options['required']) ? $options['required'] : array($nameField, 'country', 'address', 'district', 'city', 'region');
        $htmlRequired = array_key_exists('html_required', $options) ? (bool)$options['html_required'] : true;
        $isRequired = function ($field) use ($required) { return in_array($field, $required, true); };
        $fieldClass = function ($field, $span, $extra = '') use ($errors, $isRequired) {
            $classes = trim('form-field ' . $span . ' ' . $extra . ($isRequired($field) ? ' is-required' : '') . (icylab_customer_form_error($errors, $field) !== '' ? ' has-error' : ''));
            return $classes;
        };
        $errorHtml = function ($field) use ($errors) {
            $error = icylab_customer_form_error($errors, $field);
            return $error !== '' ? '<small class="field-error">' . icylab_customer_form_safe($error) . '</small>' : '';
        };
        $requiredAttr = function ($field) use ($isRequired, $htmlRequired) { return ($htmlRequired && $isRequired($field)) ? ' required' : ''; };

        $nameValue = icylab_customer_form_value($values, $nameField, '');
        if ($nameValue === 'force_open') $nameValue = '';
        ?>
        <div class="form-grid customer-quick-grid">
            <div class="<?php echo $fieldClass($nameField, 'span-5'); ?>">
                <label class="label">Razón social / Cliente</label>
                <input class="input" type="text" name="<?php echo icylab_customer_form_safe($nameField); ?>" value="<?php echo icylab_customer_form_safe($nameValue); ?>" placeholder="Ej: ICYLAB SpA"<?php echo $requiredAttr($nameField); ?>>
                <?php echo $errorHtml($nameField); ?>
            </div>

            <div class="<?php echo $fieldClass($taxField, 'span-3'); ?>">
                <label class="label">RUT / ID fiscal</label>
                <input class="input rut-formatter" type="text" <?php echo $taxId !== '' ? 'id="' . icylab_customer_form_safe($taxId) . '"' : ''; ?> name="<?php echo icylab_customer_form_safe($taxField); ?>" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, $taxField, '')); ?>" placeholder="Ej: 76.123.456-7" maxlength="20">
                <?php echo $errorHtml($taxField); ?>
            </div>

            <div class="<?php echo $fieldClass('country', 'span-4'); ?>">
                <label class="label">País</label>
                <?php icylab_render_country_select('country', $selectedCountry, $htmlRequired && $isRequired('country')); ?>
                <?php echo $errorHtml('country'); ?>
            </div>

            <div class="<?php echo $fieldClass('contact_name', 'span-4'); ?>">
                <label class="label">Contacto principal</label>
                <input class="input" type="text" name="contact_name" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'contact_name', '')); ?>" placeholder="Nombre del contacto principal"<?php echo $requiredAttr('contact_name'); ?>>
                <?php echo $errorHtml('contact_name'); ?>
            </div>

            <div class="<?php echo $fieldClass('email', 'span-4'); ?>">
                <label class="label">Email</label>
                <input class="input" type="email" name="email" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'email', '')); ?>" placeholder="Ej: contacto@empresa.cl"<?php echo $requiredAttr('email'); ?>>
                <?php echo $errorHtml('email'); ?>
            </div>

            <div class="<?php echo $fieldClass('phone', 'span-4', 'customer-phone-field'); ?>">
                <label class="label">Teléfono</label>
                <div class="customer-phone-control">
                    <?php icylab_render_phone_prefix_select($phonePrefixId, $phonePrefix); ?>
                    <input class="input" type="text" id="<?php echo icylab_customer_form_safe($phoneNumberId); ?>" data-phone-number-input="true" placeholder="9 1234 5678" value="<?php echo icylab_customer_form_safe($phoneNumber); ?>">
                    <input type="hidden" name="phone" id="<?php echo icylab_customer_form_safe($phoneHiddenId); ?>" value="<?php echo icylab_customer_form_safe($phoneValue); ?>"<?php echo $requiredAttr('phone'); ?>>
                </div>
                <?php echo $errorHtml('phone'); ?>
            </div>

            <div class="<?php echo $fieldClass('address', 'span-6 location-autocomplete-wrap'); ?>">
                <label class="label">Dirección / ubicación</label>
                <input class="input" type="text" name="address" data-location-autocomplete="true" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'address', '')); ?>" placeholder="Ej: Pasaje Lovera s/n"<?php echo $requiredAttr('address'); ?>>
                <input type="hidden" name="latitude" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'latitude', '')); ?>">
                <input type="hidden" name="longitude" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'longitude', '')); ?>">
                <input type="hidden" name="geocode_status" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'geocode_status', 'pending')); ?>">
                <input type="hidden" name="geocode_source" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'geocode_source', '')); ?>">
                <input type="hidden" name="geocode_query" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'geocode_query', '')); ?>">
                <?php echo $errorHtml('address'); ?>
            </div>

            <div class="<?php echo $fieldClass('district', 'span-3'); ?>">
                <label class="label">Comuna</label>
                <input class="input" type="text" name="district" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'district', '')); ?>" placeholder="Ej: Viña del Mar"<?php echo $requiredAttr('district'); ?>>
                <?php echo $errorHtml('district'); ?>
            </div>

            <div class="<?php echo $fieldClass('city', 'span-3'); ?>">
                <label class="label">Ciudad</label>
                <input class="input" type="text" name="city" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'city', '')); ?>" placeholder="Ej: Valparaíso"<?php echo $requiredAttr('city'); ?>>
                <?php echo $errorHtml('city'); ?>
            </div>

            <div class="<?php echo $fieldClass('region', 'span-4'); ?>">
                <label class="label">Región / Estado</label>
                <input class="input" type="text" name="region" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'region', '')); ?>" placeholder="Ej: Valparaíso"<?php echo $requiredAttr('region'); ?>>
                <?php echo $errorHtml('region'); ?>
            </div>

            <div class="<?php echo $fieldClass('payment_terms', 'span-4'); ?>">
                <label class="label">Condición de pago</label>
                <?php icylab_render_payment_terms_select('payment_terms', icylab_customer_form_value($values, 'payment_terms', icylab_customer_form_value($values, 'facto_payment_term', 'contado')), false); ?>
                <?php echo $errorHtml('payment_terms'); ?>
            </div>

            <div class="<?php echo $fieldClass('restock_days', 'span-4'); ?>">
                <label class="label">Ciclo reposición</label>
                <input class="input" type="number" name="restock_days" min="0" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'restock_days', '')); ?>" placeholder="Ej: 30">
                <?php echo $errorHtml('restock_days'); ?>
            </div>

            <div class="<?php echo $fieldClass('website', 'span-12'); ?>">
                <label class="label">Web</label>
                <input class="input" type="text" name="website" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'website', '')); ?>" placeholder="Ej: https://www.empresa.cl">
                <?php echo $errorHtml('website'); ?>
            </div>
        </div>
        <?php
    }
}
