<?php

require_once __DIR__ . '/../../core/format.php';
require_once __DIR__ . '/../../core/location.php';
require_once __DIR__ . '/../../core/database.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_finance_center_options')) {
    function icylab_finance_center_options($type = 'both')
    {
        static $cache = array();
        $type = in_array($type, array('cost', 'income', 'both'), true) ? $type : 'both';
        if (isset($cache[$type])) return $cache[$type];
        try {
            $sql = "SELECT id, center_code, center_name, center_type, is_default
                    FROM finance_centers
                    WHERE is_active = 1";
            if ($type === 'income') $sql .= " AND center_type IN ('income','both')";
            elseif ($type === 'cost') $sql .= " AND center_type IN ('cost','both')";
            $sql .= " ORDER BY is_default DESC, center_name ASC";
            $cache[$type] = db()->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        } catch (Throwable $e) {
            $cache[$type] = array();
        }
        return $cache[$type];
    }
}

if (!function_exists('icylab_render_finance_center_select')) {
    function icylab_render_finance_center_select($name, $selected, $type, $placeholder)
    {
        echo '<select class="select" name="' . icylab_customer_form_safe($name) . '">';
        echo '<option value="">' . icylab_customer_form_safe($placeholder) . '</option>';
        foreach (icylab_finance_center_options($type) as $center) {
            $isSelected = (string)$selected !== '' && (string)$selected === (string)$center['id'];
            $suffix = !empty($center['is_default']) ? ' · Predeterminado' : '';
            echo '<option value="' . (int)$center['id'] . '"' . ($isSelected ? ' selected' : '') . '>' . icylab_customer_form_safe($center['center_name'] . $suffix) . '</option>';
        }
        echo '</select>';
    }
}

if (!function_exists('icylab_supplier_payment_term_options')) {
    function icylab_supplier_payment_term_options()
    {
        static $options = null;
        if ($options !== null) return $options;
        try {
            $options = db()->query("SELECT id, term_key, term_label, days, is_default FROM billing_payment_terms WHERE is_active = 1 ORDER BY is_default DESC, days ASC, term_label ASC")->fetchAll(PDO::FETCH_ASSOC);
        } catch (Throwable $e) {
            $options = array();
        }
        return $options;
    }
}

if (!function_exists('icylab_render_supplier_payment_terms_select')) {
    function icylab_render_supplier_payment_terms_select($name, $selectedId = null)
    {
        $options = icylab_supplier_payment_term_options();
        echo '<select class="select" name="' . icylab_customer_form_safe($name) . '">';
        foreach ($options as $term) {
            $isSelected = (string)$selectedId !== '' && (string)$selectedId === (string)$term['id'];
            if (($selectedId === null || $selectedId === '') && !empty($term['is_default'])) $isSelected = true;
            echo '<option value="' . (int)$term['id'] . '"' . ($isSelected ? ' selected' : '') . '>' . icylab_customer_form_safe($term['term_label']) . '</option>';
        }
        if (!$options) echo '<option value="">Contado</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';
        $entityMode = $options['entity_mode'] ?? 'customer';
        $entityLabel = $options['entity_label'] ?? ($entityMode === 'supplier' ? 'Proveedor' : 'Cliente');
        $showCommercialName = !empty($options['show_commercial_name']);
        $restockRecalculateCustomerId = isset($options['restock_recalculate_customer_id']) ? (int)$options['restock_recalculate_customer_id'] : 0;
        $restockInputId = trim((string)($options['restock_input_id'] ?? ''));
        $showFinanceCenters = !array_key_exists('show_finance_centers', $options) || (bool)$options['show_finance_centers'];
        $costCenterField = $options['cost_center_field'] ?? ($entityMode === 'supplier' ? 'supplier_default_cost_center_id' : 'default_cost_center_id');
        $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');
        $requireBusinessActivity = !array_key_exists('require_business_activity', $options) || (bool)$options['require_business_activity'];
        if ($requireBusinessActivity && !in_array('business_activity', $required, true)) {
            $required[] = 'business_activity';
        }
        $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 customer-quick-grid--polished">
            <?php if ($entityMode === 'supplier'): ?>
                <?php $supplierCounterpartyType = icylab_customer_form_value($values, 'counterparty_type', 'supplier') === 'both' ? 'both' : 'supplier'; ?>
                <input type="hidden" name="is_supplier" value="1">
                <input type="hidden" name="counterparty_type" value="<?php echo icylab_customer_form_safe($supplierCounterpartyType); ?>">
                <input type="hidden" name="supplier_status" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'supplier_status', 'active')); ?>">
            <?php endif; ?>
            <div class="<?php echo $fieldClass($nameField, 'span-5'); ?>">
                <label class="label"><?php echo $showCommercialName ? 'Razón social' : 'Razón social / ' . icylab_customer_form_safe($entityLabel); ?></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>

            <?php if ($showCommercialName): ?>
                <div class="<?php echo $fieldClass('commercial_name', 'span-4'); ?>">
                    <label class="label">Nombre comercial</label>
                    <input class="input" type="text" name="commercial_name" maxlength="255" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'commercial_name', '')); ?>" placeholder="Ej: ICYLAB">
                    <?php echo $errorHtml('commercial_name'); ?>
                </div>
            <?php endif; ?>

            <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('business_activity', $showCommercialName ? 'span-8' : 'span-12', 'customer-business-activity-field'); ?>">
                <label class="label">Actividad comercial / Giro</label>
                <input class="input" type="text" name="business_activity" maxlength="500" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'business_activity', '')); ?>" placeholder="Ej: Elaboración y comercialización de cerveza e insumos para bebidas"<?php echo $requiredAttr('business_activity'); ?>>
                <?php echo $errorHtml('business_activity'); ?>
            </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($entityMode === 'supplier' ? 'supplier_payment_terms_id' : 'payment_terms', 'span-4'); ?>">
                <label class="label">Condición de pago</label>
                <?php if ($entityMode === 'supplier'): ?>
                    <?php icylab_render_supplier_payment_terms_select('supplier_payment_terms_id', icylab_customer_form_value($values, 'supplier_payment_terms_id', '')); ?>
                    <small class="field-help">Define el vencimiento predeterminado de los DTE recibidos.</small>
                <?php else: ?>
                    <?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 endif; ?>
                <?php echo $errorHtml($entityMode === 'supplier' ? 'supplier_payment_terms_id' : 'payment_terms'); ?>
            </div>

            <?php if ($showFinanceCenters): ?>
                <div class="form-field span-4">
                    <label class="label">Centro de ingreso predeterminado</label>
                    <?php icylab_render_finance_center_select('default_income_center_id', icylab_customer_form_value($values, 'default_income_center_id', ''), 'income', 'Sin centro de ingreso'); ?>
                    <small class="field-help">Se heredará en facturas y cuentas por cobrar.</small>
                </div>
                <div class="form-field span-4">
                    <label class="label">Centro de costo predeterminado</label>
                    <?php
                    $selectedCostCenter = icylab_customer_form_value($values, $costCenterField, icylab_customer_form_value($values, 'default_cost_center_id', ''));
                    icylab_render_finance_center_select($costCenterField, $selectedCostCenter, 'cost', 'Sin centro de costo');
                    ?>
                    <?php if ($costCenterField !== 'default_cost_center_id'): ?>
                        <input type="hidden" name="default_cost_center_id" value="<?php echo icylab_customer_form_safe($selectedCostCenter); ?>">
                    <?php endif; ?>
                    <small class="field-help">Se heredará en DTE recibidos y cuentas por pagar.</small>
                </div>
            <?php endif; ?>

            <div class="<?php echo $fieldClass('restock_days', 'span-4'); ?>">
                <label class="label">Ciclo de recompra (días)</label>
                <div class="customer-restock-control">
                    <input class="input" type="number"<?php echo $restockInputId !== '' ? ' id="' . icylab_customer_form_safe($restockInputId) . '"' : ''; ?> name="restock_days" min="0" max="3650" step="1" value="<?php echo icylab_customer_form_safe(icylab_customer_form_value($values, 'restock_days', '')); ?>" placeholder="Ej: 30">
                    <?php if ($restockRecalculateCustomerId > 0): ?>
                        <button type="button" class="icon-btn customer-restock-refresh" data-customer-restock-recalculate data-customer-id="<?php echo $restockRecalculateCustomerId; ?>" data-endpoint="/modules/customers/customer_restock_recalculate.php" title="Recalcular ciclo desde FACTO" aria-label="Recalcular ciclo desde FACTO">
                            <i data-lucide="refresh-cw"></i>
                        </button>
                    <?php endif; ?>
                </div>
                <small class="field-help" data-customer-restock-status>El ciclo manual o calculado se proyecta desde la última compra válida. Sin compras no se genera fecha ni oportunidad.</small>
                <?php echo $errorHtml('restock_days'); ?>
            </div>

            <div class="<?php echo $fieldClass('website', 'span-4'); ?>">
                <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
    }
}
