<?php

namespace PloverCRM\Modules\NativeCRM\Tabs;

use PloverCRM\Modules\NativeCRM\CustomFieldsManager;

/**
 * Native CRM Settings Tab
 * 
 * Handles built-in CRM settings including custom fields management
 */
class NativeCRMSettingsTab
{
    /**
     * @var CustomFieldsManager
     */
    private $customFieldsManager;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->customFieldsManager = new CustomFieldsManager();
    }

    /**
     * Register settings
     */
    public function register(): void
    {
        add_action('admin_init', [$this, 'registerSettings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueScripts']);

        // AJAX handlers
        add_action('wp_ajax_plover_crm_get_field', [$this, 'ajaxGetField']);
        add_action('wp_ajax_plover_crm_add_field', [$this, 'ajaxAddField']);
        add_action('wp_ajax_plover_crm_update_field', [$this, 'ajaxUpdateField']);
        add_action('wp_ajax_plover_crm_delete_field', [$this, 'ajaxDeleteField']);
        add_action('wp_ajax_plover_crm_reorder_fields', [$this, 'ajaxReorderFields']);
    }

    /**
     * Register settings
     */
    public function registerSettings(): void
    {
        // Register settings section
        add_settings_section(
            'plover_crm_settings_section',
            'Built-in CRM Settings',
            [$this, 'renderSectionDescription'],
            'plover_crm_settings'
        );

        // Custom Fields Manager
        add_settings_field(
            'plover_crm_custom_fields',
            'Custom Fields',
            [$this, 'renderCustomFieldsManager'],
            'plover_crm_settings',
            'plover_crm_settings_section'
        );

        // Unique Field
        add_settings_field(
            'plover_crm_unique_field',
            'Unique Field',
            [$this, 'renderUniqueField'],
            'plover_crm_settings',
            'plover_crm_settings_section'
        );

        // Logs
        add_settings_field(
            'plover_crm_logs',
            'Recent Logs',
            [$this, 'renderLogs'],
            'plover_crm_settings',
            'plover_crm_settings_section'
        );

        register_setting('plover_crm_settings', 'plover_crm_unique_field');
    }

    /**
     * Render section description
     */
    public function renderSectionDescription(): void
    {
        echo '<p>Configure your built-in CRM settings and manage custom fields.</p>';
    }

    /**
     * Render custom fields manager
     */
    public function renderCustomFieldsManager(): void
    {
        $fields = $this->customFieldsManager->getAllFields();

        // Sort by order
        usort($fields, function ($a, $b) {
            return ($a['order'] ?? 0) - ($b['order'] ?? 0);
        });
?>
        <div id="plvcrm-custom-fields-manager">
            <div id="plvcrm-fields-list">
                <?php if (empty($fields)): ?>
                    <p class="plvcrm-no-fields">No custom fields defined yet.</p>
                <?php else: ?>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th width="30">Order</th>
                                <th>Label</th>
                                <th>Slug</th>
                                <th>Type</th>
                                <th>Group</th>
                                <th width="150">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="plvcrm-fields-sortable">
                            <?php foreach ($fields as $field): ?>
                                <tr data-slug="<?php echo esc_attr($field['slug']); ?>">
                                    <td class="drag-handle" style="cursor: move;">☰</td>
                                    <td><?php echo esc_html($field['label']); ?></td>
                                    <td><code><?php echo esc_html($field['slug']); ?></code></td>
                                    <td><?php echo esc_html($field['type']); ?></td>
                                    <td><?php echo esc_html($field['group'] ?? '-'); ?></td>
                                    <td>
                                        <button type="button" class="button button-small plvcrm-edit-field" data-slug="<?php echo esc_attr($field['slug']); ?>">Edit</button>
                                        <button type="button" class="button button-small plvcrm-delete-field" data-slug="<?php echo esc_attr($field['slug']); ?>">Delete</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>

            <p>
                <button type="button" class="button button-primary" id="plvcrm-add-field-btn">Add Custom Field</button>
            </p>
        </div>

        <!-- Add/Edit Field Modal -->
        <div id="plvcrm-field-modal" style="display: none;">
            <div class="plvcrm-modal-overlay"></div>
            <div class="plvcrm-modal-content">
                <h2 id="plvcrm-modal-title">Add Custom Field</h2>
                <div id="plvcrm-field-form">
                    <input type="hidden" id="plvcrm-field-slug-original" value="" />

                    <table class="form-table">
                        <tr>
                            <th><label for="plvcrm-field-label">Label *</label></th>
                            <td><input type="text" id="plvcrm-field-label" class="regular-text" /></td>
                        </tr>
                        <tr>
                            <th><label for="plvcrm-field-slug">Slug *</label></th>
                            <td>
                                <input type="text" id="plvcrm-field-slug" class="regular-text" />
                                <p class="description">Unique identifier (lowercase, no spaces)</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="plvcrm-field-type">Type *</label></th>
                            <td>
                                <select id="plvcrm-field-type">
                                    <option value="text">Text</option>
                                    <option value="textarea">Textarea</option>
                                    <option value="email">Email</option>
                                    <option value="url">URL</option>
                                    <option value="number">Number</option>
                                    <option value="date">Date</option>
                                    <option value="date_time">Date Time</option>
                                    <option value="select">Select Dropdown</option>
                                    <option value="radio">Radio Buttons</option>
                                    <option value="checkbox">Checkbox</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="plvcrm-field-group">Group</label></th>
                            <td>
                                <input type="text" id="plvcrm-field-group" class="regular-text" />
                                <p class="description">Optional group name to organize fields (e.g., "Contact Info", "UTM Tracking")</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="plvcrm-field-readonly">Read Only</label></th>
                            <td>
                                <label>
                                    <input type="checkbox" id="plvcrm-field-readonly" value="1" />
                                    Make this field read-only (users can view but not edit)
                                </label>
                                <p class="description">Useful for system-generated fields like UTM tracking data</p>
                            </td>
                        </tr>
                        <tr id="plvcrm-field-options-row" style="display: none;">
                            <th><label for="plvcrm-field-options">Options</label></th>
                            <td>
                                <textarea id="plvcrm-field-options" class="large-text" rows="4"></textarea>
                                <p class="description">One option per line (for select/radio/checkbox fields)</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="plvcrm-field-help-text">Help Text</label></th>
                            <td><input type="text" id="plvcrm-field-help-text" class="regular-text" /></td>
                        </tr>
                    </table>

                    <p>
                        <button type="button" class="button button-primary">Save Field</button>
                        <button type="button" class="button plvcrm-modal-close">Cancel</button>
                    </p>
                </div>
            </div>
        </div>

        <style>
            .plvcrm-modal-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.7);
                z-index: 100000;
            }

            .plvcrm-modal-content {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: #fff;
                padding: 20px;
                border-radius: 4px;
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
                z-index: 100001;
                max-width: 600px;
                width: 90%;
                max-height: 90vh;
                overflow-y: auto;
            }

            #plvcrm-fields-sortable tr {
                cursor: move;
            }

            .plvcrm-no-fields {
                font-style: italic;
                color: #666;
            }
        </style>
    <?php
    }

    /**
     * Render unique field setting
     */
    public function renderUniqueField(): void
    {
        $unique_field = get_option('plover_crm_unique_field', 'email');
        $custom_fields = $this->customFieldsManager->getAllFields();

        // Only allow text-based fields as unique
        $allowed_types = ['text', 'email', 'url', 'number'];
    ?>
        <select name="plover_crm_unique_field">
            <option value="email" <?php selected($unique_field, 'email'); ?>>Email (default)</option>
            <option value="phone" <?php selected($unique_field, 'phone'); ?>>Phone</option>
            <?php foreach ($custom_fields as $field): ?>
                <?php if (in_array($field['type'], $allowed_types)): ?>
                    <option value="plover_crm_cf_<?php echo esc_attr($field['slug']); ?>" <?php selected($unique_field, 'plover_crm_cf_' . $field['slug']); ?>>
                        <?php echo esc_html($field['label']); ?> (<?php echo esc_html(ucfirst($field['type'])); ?>)
                    </option>
                <?php endif; ?>
            <?php endforeach; ?>
        </select>
        <p class="description">This field will be required and must be unique across all contacts. Only text-based fields can be unique.</p>
    <?php
    }

    /**
     * Render logs section
     */
    public function renderLogs(): void
    {
        \PloverCRM\Modules\NativeCRM\Helpers\LogViewer::render();
    }

    /**
     * Enqueue scripts
     */
    public function enqueueScripts($hook): void
    {
        // Check if we're on the built-in CRM settings page
        if (strpos($hook, 'plover-crm') === false) {
            return;
        }

        wp_enqueue_script('jquery');
        wp_enqueue_script('jquery-ui-sortable');

        // Add inline script after jQuery is loaded
        wp_add_inline_script('jquery-ui-sortable', $this->getInlineScript());
    }

    /**
     * Get inline script
     */
    private function getInlineScript(): string
    {
        $nonce = wp_create_nonce('plover_crm_fields');
        ob_start();
    ?>
        jQuery(document).ready(function($) {
        // Show/hide options field based on type
        $('#plvcrm-field-type').on('change', function() {
        var type = $(this).val();
        if (type === 'select' || type === 'radio' || type === 'checkbox') {
        $('#plvcrm-field-options-row').show();
        } else {
        $('#plvcrm-field-options-row').hide();
        }
        });

        // Auto-generate slug from label
        $('#plvcrm-field-label').on('input', function() {
        if (!$('#plvcrm-field-slug-original').val()) {
        var slug = $(this).val().toLowerCase()
        .replace(/[^a-z0-9]+/g, '_')
        .replace(/^_+|_+$/g, '');
        $('#plvcrm-field-slug').val(slug);
        }
        });

        // Open add field modal
        $('#plvcrm-add-field-btn').on('click', function() {
        $('#plvcrm-modal-title').text('Add Custom Field');
        // Clear form fields
        $('#plvcrm-field-label').val('');
        $('#plvcrm-field-slug').val('');
        $('#plvcrm-field-type').val('text');
        $('#plvcrm-field-group').val('');
        $('#plvcrm-field-readonly').prop('checked', false);
        $('#plvcrm-field-options').val('');
        $('#plvcrm-field-help-text').val('');
        $('#plvcrm-field-slug-original').val('');
        $('#plvcrm-field-slug').prop('readonly', false);
        $('#plvcrm-field-options-row').hide();
        $('#plvcrm-field-modal').show();
        });

        // Open edit field modal
        $(document).on('click', '.plvcrm-edit-field', function() {
        var slug = $(this).data('slug');

        $.post(ajaxurl, {
        action: 'plover_crm_get_field',
        slug: slug,
        nonce: '<?php echo $nonce; ?>'
        }, function(response) {
        if (response.success) {
        var field = response.data;
        $('#plvcrm-modal-title').text('Edit Custom Field');
        $('#plvcrm-field-slug-original').val(field.slug);
        $('#plvcrm-field-label').val(field.label);
        $('#plvcrm-field-slug').val(field.slug).prop('readonly', true);
        $('#plvcrm-field-type').val(field.type).trigger('change');
        $('#plvcrm-field-group').val(field.group || '');
        $('#plvcrm-field-readonly').prop('checked', field.readonly || false);
        $('#plvcrm-field-options').val((field.options || []).join('\n'));
        $('#plvcrm-field-help-text').val(field.help_text || '');
        $('#plvcrm-field-modal').show();
        }
        });
        });

        // Close modal
        $('.plvcrm-modal-close').on('click', function() {
        $('#plvcrm-field-modal').hide();
        });

        // Submit field form
        $(document).on('click', '#plvcrm-field-form .button-primary', function(e) {
        e.preventDefault();

        // Validate required fields
        var label = $('#plvcrm-field-label').val();
        var slug = $('#plvcrm-field-slug').val();

        if (!label || !slug) {
        alert('Label and Slug are required');
        return;
        }

        var originalSlug = $('#plvcrm-field-slug-original').val();
        var isEdit = originalSlug !== '';

        var fieldData = {
        label: label,
        slug: slug,
        type: $('#plvcrm-field-type').val(),
        group: $('#plvcrm-field-group').val(),
        readonly: $('#plvcrm-field-readonly').is(':checked'),
        help_text: $('#plvcrm-field-help-text').val()
        };

        var type = $('#plvcrm-field-type').val();
        if (type === 'select' || type === 'radio' || type === 'checkbox') {
        var options = $('#plvcrm-field-options').val().split('\n').filter(function(o) {
        return o.trim() !== '';
        });
        fieldData.options = options;
        }

        $.post(ajaxurl, {
        action: isEdit ? 'plover_crm_update_field' : 'plover_crm_add_field',
        original_slug: originalSlug,
        field: fieldData,
        nonce: '<?php echo $nonce; ?>'
        }, function(response) {
        if (response.success) {
        location.reload();
        } else {
        alert(response.data || 'Failed to save field');
        }
        });
        });

        // Delete field
        $(document).on('click', '.plvcrm-delete-field', function() {
        if (!confirm('Are you sure you want to delete this field?')) {
        return;
        }

        var slug = $(this).data('slug');

        $.post(ajaxurl, {
        action: 'plover_crm_delete_field',
        slug: slug,
        nonce: '<?php echo $nonce; ?>'
        }, function(response) {
        if (response.success) {
        location.reload();
        } else {
        alert(response.data || 'Failed to delete field');
        }
        });
        });

        // Sortable fields
        $('#plvcrm-fields-sortable').sortable({
        handle: '.drag-handle',
        update: function() {
        var order = [];
        $('#plvcrm-fields-sortable tr').each(function() {
        order.push($(this).data('slug'));
        });

        $.post(ajaxurl, {
        action: 'plover_crm_reorder_fields',
        order: order,
        nonce: '<?php echo $nonce; ?>'
        });
        }
        });
        });
<?php
        return ob_get_clean();
    }

    /**
     * AJAX: Get field
     */
    public function ajaxGetField(): void
    {
        check_ajax_referer('plover_crm_fields', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        $slug = $_POST['slug'] ?? '';

        if (empty($slug)) {
            wp_send_json_error('Slug is required');
        }

        $fields = $this->customFieldsManager->getAllFields();

        foreach ($fields as $field) {
            if ($field['slug'] === $slug) {
                wp_send_json_success($field);
            }
        }

        wp_send_json_error('Field not found');
    }

    /**
     * AJAX: Add field
     */
    public function ajaxAddField(): void
    {

        check_ajax_referer('plover_crm_fields', 'nonce');

        if (!current_user_can('manage_options')) {

            wp_send_json_error('Permission denied');
        }

        $field = $_POST['field'] ?? [];

        if (empty($field['label']) || empty($field['slug'])) {

            wp_send_json_error('Label and slug are required');
        }

        $result = $this->customFieldsManager->addField($field);

        if ($result) {
            wp_send_json_success();
        } else {
            wp_send_json_error('Field with this slug already exists');
        }
    }

    /**
     * AJAX: Update field
     */
    public function ajaxUpdateField(): void
    {
        check_ajax_referer('plover_crm_fields', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        $originalSlug = $_POST['original_slug'] ?? '';
        $field = $_POST['field'] ?? [];

        if (empty($originalSlug)) {
            wp_send_json_error('Original slug is required');
        }

        $result = $this->customFieldsManager->updateField($originalSlug, $field);

        if ($result) {
            wp_send_json_success();
        } else {
            wp_send_json_error('Failed to update field');
        }
    }

    /**
     * AJAX: Delete field
     */
    public function ajaxDeleteField(): void
    {
        check_ajax_referer('plover_crm_fields', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        $slug = $_POST['slug'] ?? '';

        if (empty($slug)) {
            wp_send_json_error('Slug is required');
        }

        $result = $this->customFieldsManager->deleteField($slug);

        if ($result) {
            wp_send_json_success();
        } else {
            wp_send_json_error('Failed to delete field');
        }
    }

    /**
     * AJAX: Reorder fields
     */
    public function ajaxReorderFields(): void
    {
        check_ajax_referer('plover_crm_fields', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        $order = $_POST['order'] ?? [];

        if (empty($order)) {
            wp_send_json_error('Order is required');
        }

        $result = $this->customFieldsManager->reorderFields($order);

        if ($result) {
            wp_send_json_success();
        } else {
            wp_send_json_error('Failed to reorder fields');
        }
    }
}
