<?php
/**
 * Frontend contact form template
 *
 * @package SPAI_Contact_Form
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get form data
$form_fields = json_decode($form->form_fields, true);
$form_settings = json_decode($form->form_settings, true);

// Process GET parameters for field prefilling
foreach ($form_fields as $index => $field) {
    $get_param = 'spai_' . $field['name'];
    if (isset($_GET[$get_param])) {
        if ($field['type'] === 'multichoice') {
            // Handle multichoice fields that use default_values array
            $values = is_array($_GET[$get_param]) ? $_GET[$get_param] : explode(',', $_GET[$get_param]);
            $form_fields[$index]['default_values'] = array_map('sanitize_text_field', $values);
        } else {
            // Handle regular fields that use default_value string
            $form_fields[$index]['default_value'] = sanitize_text_field($_GET[$get_param]);
        }
    }
}

// Get global settings
$global_settings = get_option('spai_contact_form_settings', array(
    'max_file_size' => 10,
    'max_attachments' => 2,
    'allowed_file_types' => array('pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png')
));

// Get PHP upload limits and calculate effective limits
$php_limits = spai_get_php_upload_limits();
$effective_max_size = min($global_settings['max_file_size'], $php_limits['max_file_size_mb']);
$effective_max_attachments = min(
    isset($global_settings['max_attachments']) ? $global_settings['max_attachments'] : 2,
    $php_limits['max_file_uploads']
);

// Generate unique form ID
$form_id = 'spai-form-' . $form->id;
?>

<div class="spai-form-container">
    <form id="<?php echo esc_attr($form_id); ?>" class="spai-form <?php echo esc_attr($atts['class']); ?>" method="post" enctype="multipart/form-data">
        
        <!-- Security -->
        <?php echo SPAI_Security::create_nonce(); ?>
        <input type="hidden" name="spai_form_id" value="<?php echo esc_attr($form->id); ?>">
        
        <!-- Honeypot -->
        <?php if (!empty($form_settings['enable_honeypot'])): ?>
            <?php echo SPAI_Security::honeypot_field(); ?>
        <?php endif; ?>
        
        <!-- Form Fields -->
        <?php foreach ($form_fields as $field): ?>
            <?php
            // Skip section fields - render as section divider
            if ($field['type'] === 'section') {
                ?>
                <div class="spai-form-section">
                    <?php if (!empty($field['heading'])): ?>
                        <h3><?php echo esc_html($field['heading']); ?></h3>
                    <?php elseif (!empty($field['label'])): ?>
                        <h3><?php echo esc_html($field['label']); ?></h3>
                    <?php endif; ?>
                    <?php if (!empty($field['description'])): ?>
                        <p><?php echo esc_html($field['description']); ?></p>
                    <?php endif; ?>
                </div>
                <?php
                continue;
            }
            
            // Regular fields
            $field_name = 'spai_field_' . $field['name'];
            $field_id = $field_name . '_' . uniqid();
            // Check if label should be hidden - handle both boolean and string values
            $hide_label_check = isset($field['hide_label']) && ($field['hide_label'] === true || $field['hide_label'] === 'true');
            $aria_label = $hide_label_check ? 'aria-label="' . esc_attr($field['label']) . '"' : '';
            ?>
            
            <div class="spai-form-group spai-<?php echo esc_attr($field['type']); ?> <?php echo esc_attr($field['css_class'] ?? ''); ?> <?php echo !empty($field['width']) && $field['width'] === 'half' ? 'spai-half-width' : ''; ?>">
                <?php 
                // Check if label should be hidden - handle both boolean and string values
                $hide_label = isset($field['hide_label']) && ($field['hide_label'] === true || $field['hide_label'] === 'true');
                if ($field['type'] !== 'hidden' && !$hide_label): 
                ?>
                    <label for="<?php echo esc_attr($field_id); ?>" class="spai-label-<?php echo esc_attr($field['type']); ?>">
                        <?php echo esc_html($field['label']); ?>
                        <?php if (spai_is_field_required($field)): ?>
                            <span class="required">*</span>
                        <?php endif; ?>
                    </label>
                <?php endif; ?>
                
                <?php
                // Render field based on type
                switch ($field['type']) {
                    case 'text':
                    case 'email':
                        ?>
                        <input type="<?php echo esc_attr($field['type']); ?>"
                               id="<?php echo esc_attr($field_id); ?>"
                               name="<?php echo esc_attr($field_name); ?>"
                               <?php echo $aria_label; ?>
                               <?php if (!empty($field['placeholder'])): ?>
                                   placeholder="<?php echo esc_attr($field['placeholder']); ?>"
                               <?php endif; ?>
                               <?php if (!empty($field['default_value'])): ?>
                                   value="<?php echo esc_attr($field['default_value']); ?>"
                               <?php endif; ?>
                               <?php if (spai_is_field_required($field)): ?>
                                   required
                               <?php endif; ?>
                        >
                        <?php
                        break;
                        
                    case 'phone':
                        ?>
                        <input type="tel"
                               id="<?php echo esc_attr($field_id); ?>"
                               name="<?php echo esc_attr($field_name); ?>"
                               <?php echo $aria_label; ?>
                               <?php if (!empty($field['placeholder'])): ?>
                                   placeholder="<?php echo esc_attr($field['placeholder']); ?>"
                               <?php endif; ?>
                               <?php if (!empty($field['default_value'])): ?>
                                   value="<?php echo esc_attr($field['default_value']); ?>"
                               <?php endif; ?>
                               <?php if (spai_is_field_required($field)): ?>
                                   required
                               <?php endif; ?>
                               <?php if (!empty($field['phoneSettings'])): ?>
                                   data-phone-settings='<?php echo esc_attr(json_encode($field['phoneSettings'])); ?>'
                               <?php endif; ?>
                        >
                        <?php
                        break;
                        
                    case 'number':
                    case 'date':
                    case 'hidden':
                        ?>
                        <input type="<?php echo esc_attr($field['type']); ?>"
                               id="<?php echo esc_attr($field_id); ?>"
                               name="<?php echo esc_attr($field_name); ?>"
                               <?php echo $aria_label; ?>
                               <?php if (!empty($field['placeholder'])): ?>
                                   placeholder="<?php echo esc_attr($field['placeholder']); ?>"
                               <?php endif; ?>
                               <?php if (!empty($field['default_value'])): ?>
                                   value="<?php echo esc_attr($field['default_value']); ?>"
                               <?php endif; ?>
                               <?php if (spai_is_field_required($field)): ?>
                                   required
                               <?php endif; ?>
                               <?php if ($field['type'] === 'number' && isset($field['min'])): ?>
                                   min="<?php echo esc_attr($field['min']); ?>"
                               <?php endif; ?>
                               <?php if ($field['type'] === 'number' && isset($field['max'])): ?>
                                   max="<?php echo esc_attr($field['max']); ?>"
                               <?php endif; ?>
                        >
                        <?php
                        break;
                        
                    case 'textarea':
                        ?>
                        <textarea id="<?php echo esc_attr($field_id); ?>"
                                  name="<?php echo esc_attr($field_name); ?>"
                                  <?php echo $aria_label; ?>
                                  <?php if (!empty($field['placeholder'])): ?>
                                      placeholder="<?php echo esc_attr($field['placeholder']); ?>"
                                  <?php endif; ?>
                                  <?php if (!empty($field['rows'])): ?>
                                      rows="<?php echo esc_attr($field['rows']); ?>"
                                  <?php endif; ?>
                                  <?php if (spai_is_field_required($field)): ?>
                                      required
                                  <?php endif; ?>
                        ><?php echo esc_textarea($field['default_value'] ?? ''); ?></textarea>
                        <?php
                        break;
                        
                    case 'select':
                        ?>
                        <div class="spai-select-wrapper">
                            <select id="<?php echo esc_attr($field_id); ?>"
                                    name="<?php echo esc_attr($field_name); ?><?php echo !empty($field['multiple']) ? '[]' : ''; ?>"
                                    <?php echo $aria_label; ?>
                                    <?php if (!empty($field['multiple'])): ?>multiple<?php endif; ?>
                                    <?php if (spai_is_field_required($field)): ?>
                                        required
                                    <?php endif; ?>
                            >
                                <?php if (!empty($field['placeholder'])): ?>
                                    <option value=""><?php echo esc_html($field['placeholder']); ?></option>
                                <?php endif; ?>
                                <?php foreach ($field['options'] as $option): ?>
                                    <option value="<?php echo esc_attr($option); ?>"
                                            <?php 
                                            if (!empty($field['multiple']) && is_array($field['default_value'] ?? [])) {
                                                echo in_array($option, $field['default_value']) ? 'selected' : '';
                                            } else {
                                                selected($option, $field['default_value'] ?? '');
                                            }
                                            ?>>
                                        <?php echo esc_html($option); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="spai-select-arrow">
                                <svg width="12" height="8" viewBox="0 0 12 8" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M1 1.5L6 6.5L11 1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                            </div>
                        </div>
                        <?php
                        break;
                        
                    case 'radio':
                        ?>
                        <div class="radio-group <?php echo !empty($field['inline']) ? 'inline' : ''; ?>">
                            <?php foreach ($field['options'] as $i => $option): ?>
                                <label>
                                    <input type="radio"
                                           name="<?php echo esc_attr($field_name); ?>"
                                           value="<?php echo esc_attr($option); ?>"
                                           <?php checked($option, $field['default_value'] ?? ''); ?>
                                           <?php if (spai_is_field_required($field) && $i === 0): ?>
                                               required
                                           <?php endif; ?>
                                    >
                                    <?php echo esc_html($option); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <?php
                        break;
                        
                    case 'checkbox':
                        if (!empty($field['options'])) {
                            // Multiple checkboxes
                            ?>
                            <div class="checkbox-group <?php echo !empty($field['inline']) ? 'inline' : ''; ?>">
                                <?php foreach ($field['options'] as $option): ?>
                                    <label>
                                        <input type="checkbox"
                                               name="<?php echo esc_attr($field_name); ?>[]"
                                               value="<?php echo esc_attr($option); ?>"
                                               <?php if (is_array($field['default_values'] ?? []) && in_array($option, $field['default_values'])): ?>
                                                   checked
                                               <?php endif; ?>
                                        >
                                        <?php echo esc_html($option); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <?php
                        } else {
                            // Single checkbox
                            ?>
                            <label>
                                <input type="checkbox"
                                       id="<?php echo esc_attr($field_id); ?>"
                                       name="<?php echo esc_attr($field_name); ?>"
                                       value="1"
                                       <?php checked($field['default_value'] ?? false); ?>
                                       <?php if (spai_is_field_required($field)): ?>
                                           required
                                       <?php endif; ?>
                                >
                                <?php echo esc_html($field['text'] ?? $field['label']); ?>
                            </label>
                            <?php
                        }
                        break;
                        
                    case 'multichoice':
                        ?>
                        <div class="spai-multichoice-container" 
                             data-field-name="<?php echo esc_attr($field_name); ?>"
                             data-options="<?php echo esc_attr(json_encode($field['options'] ?? [])); ?>">
                            <div class="spai-multichoice-input-wrapper">
                                <div class="spai-multichoice-input-area">
                                    <div class="spai-multichoice-selected-inline">
                                        <?php if (!empty($field['default_values']) && is_array($field['default_values'])): ?>
                                            <?php foreach ($field['default_values'] as $value): ?>
                                                <span class="spai-multichoice-tag">
                                                    <?php echo esc_html($value); ?>
                                                    <span class="spai-multichoice-remove">×</span>
                                                    <input type="hidden" name="<?php echo esc_attr($field_name); ?>[]" value="<?php echo esc_attr($value); ?>">
                                                </span>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                    <input type="text" 
                                           class="spai-multichoice-input" 
                                           placeholder="<?php echo esc_attr($field['placeholder'] ?? 'Type to search options...'); ?>"
                                           autocomplete="off">
                                    <div class="spai-multichoice-arrow">
                                        <svg width="12" height="8" viewBox="0 0 12 8" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M1 1.5L6 6.5L11 1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                    </div>
                                </div>
                                <div class="spai-multichoice-dropdown" style="display: none;">
                                    <?php foreach ($field['options'] as $option): ?>
                                        <div class="spai-multichoice-option" data-value="<?php echo esc_attr($option); ?>">
                                            <?php echo esc_html($option); ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        <?php
                        break;
                        
                    case 'consent_checkbox':
                        ?>
                        <div class="spai-form-field consent-checkbox">
                            <label>
                                <input type="checkbox"
                                       id="<?php echo esc_attr($field_id); ?>"
                                       name="<?php echo esc_attr($field_name); ?>"
                                       value="1"
                                       <?php if (!empty($field['default_checked']) && $field['default_checked'] !== 'false'): ?>
                                           checked
                                       <?php endif; ?>
                                       <?php if (spai_is_field_required($field)): ?>
                                           required
                                       <?php endif; ?>
                                >
                                <?php echo esc_html($field['label_text'] ?? 'By checking this box, you agree to receive text messages. Standard message and data rates may apply. Reply STOP to opt out at any time.'); ?>
                            </label>
                        </div>
                        <?php
                        break;
                        
                    case 'file':
                        ?>
                        <div class="spai-file-upload"
                             data-max-size="<?php echo esc_attr($effective_max_size); ?>"
                             data-max-attachments="<?php echo esc_attr($effective_max_attachments); ?>"
                             data-allowed-types="<?php echo esc_attr(implode(',', $global_settings['allowed_file_types'])); ?>">
                            <input type="file"
                                   id="<?php echo esc_attr($field_id); ?>"
                                   name="<?php echo esc_attr($field_name); ?><?php echo !empty($field['multiple']) ? '[]' : ''; ?>"
                                   <?php echo $aria_label; ?>
                                   <?php if (!empty($field['multiple'])): ?>
                                       multiple
                                   <?php endif; ?>
                                   <?php if (spai_is_field_required($field)): ?>
                                       required
                                   <?php endif; ?>
                                   accept=".<?php echo implode(',.', $global_settings['allowed_file_types']); ?>"
                            >
                            <p class="spai-upload-text">Drag and drop files here or click to browse</p>
                            <div class="spai-upload-limits">
                                <small>
                                    <?php printf(__('Max file size: %dMB', 'spai-contact-form'), $effective_max_size); ?> | 
                                    <?php printf(__('Max files: %d', 'spai-contact-form'), $effective_max_attachments); ?> | 
                                    <?php printf(__('Allowed types: %s', 'spai-contact-form'), implode(', ', $global_settings['allowed_file_types'])); ?>
                                </small>
                            </div>
                            <div class="spai-file-list"></div>
                        </div>
                        <?php
                        break;
                }
                ?>
                
                <?php if (!empty($field['help_text'])): ?>
                    <div class="spai-help-text"><?php echo esc_html($field['help_text']); ?></div>
                <?php endif; ?>
            </div>
            
        <?php endforeach; ?>
        
        <!-- Message Above Submit -->
        <div class="spai-message spai-message-bottom spai-full-width" style="display: none;"></div>
        
        <!-- Submit Button -->
        <div class="spai-form-submit spai-full-width">
            <button type="submit" class="spai-submit-button" data-text="<?php echo esc_attr($form_settings['submit_text'] ?? 'Submit'); ?>">
                <?php echo esc_html($form_settings['submit_text'] ?? 'Submit'); ?>
            </button>
        </div>
    </form>
</div>
