<?php

namespace PloverCRM\Modules\NativeCRM;

use PloverCRM\Core\AbstractModule;

/**
 * Native CRM Module
 * 
 * Built-in CRM system using WordPress Custom Post Types
 */
class NativeCRMModule extends AbstractModule
{
    protected $id = 'native_crm';
    protected $dependencies = [];

    /**
     * {@inheritdoc}
     */
    public function getMetadata(): array
    {
        return [
            'name' => 'Built-in CRM',
            'description' => 'Built-in CRM system using WordPress Custom Post Types, Taxonomies, and Custom Fields',
            'version' => '1.0.0',
            'author' => 'WebPlover',
            'icon' => '📊',
            'required' => false,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        // Register CPT and taxonomies
        add_action('init', [$this, 'registerPostType']);
        add_action('init', [$this, 'registerTaxonomies']);

        // Export file cleanup hook
        add_action('plover_crm_cleanup_export', [$this, 'cleanupExportFile']);

        // Customize featured image labels for contacts
        add_filter('post_type_labels_plover_crm_contact', [$this, 'customizeFeaturedImageLabels']);

        // Register meta boxes
        add_action('add_meta_boxes', [$this, 'addMetaBoxes']);
        add_action('save_post_plover_crm_contact', [$this, 'saveContactMeta'], 10, 2);

        // AJAX handler for uniqueness check
        add_action('wp_ajax_plover_crm_check_unique', [$this, 'ajaxCheckUnique']);

        // AJAX handlers for notes
        add_action('wp_ajax_plover_crm_add_note', [$this, 'ajaxAddNote']);
        add_action('wp_ajax_plover_crm_update_note', [$this, 'ajaxUpdateNote']);
        add_action('wp_ajax_plover_crm_delete_note', [$this, 'ajaxDeleteNote']);

        // Add custom columns to contacts list
        add_filter('manage_plover_crm_contact_posts_columns', [$this, 'addContactColumns']);
        add_action('manage_plover_crm_contact_posts_custom_column', [$this, 'renderContactColumn'], 10, 2);
        add_filter('default_hidden_columns', [$this, 'setDefaultHiddenColumns'], 10, 2);
        add_filter('hidden_columns', [$this, 'preventHidingColumns'], 10, 2);
        add_filter('manage_edit-plover_crm_contact_columns', [$this, 'addContactColumns']);
        add_action('admin_head-edit.php', [$this, 'hideAvatarFromScreenOptions']);
        add_filter('post_row_actions', [$this, 'removeQuickEdit'], 10, 2);
        add_filter('admin_title', [$this, 'customizeContactEditTitle'], 10, 2);

        // Hide parent dropdown for lists and tags
        add_action('admin_head-edit-tags.php', [$this, 'hideParentDropdown']);
        add_action('admin_head-term.php', [$this, 'hideParentDropdown']); // For edit screen
        add_action('admin_head-post.php', [$this, 'hideParentDropdown']);
        add_action('admin_head-post-new.php', [$this, 'hideParentDropdown']);

        // Extend search to include all fields
        add_filter('posts_search', [$this, 'extendContactSearch'], 10, 2);
        add_filter('posts_join', [$this, 'extendContactSearchJoin'], 10, 2);
        add_filter('posts_groupby', [$this, 'extendContactSearchGroupBy'], 10, 2);



        // Register settings tab
        $settingsTab = new Tabs\NativeCRMSettingsTab();
        $settingsTab->register();

        // Register CSV import/export
        $csvManager = new ImportExport\CSVManager();
        $csvManager->register();
    }

    /**
     * {@inheritdoc}
     */
    public function boot(): void
    {
        // Boot logic if needed
    }

    /**
     * Cleanup export file
     * 
     * @param string $filePath Path to the export file
     */
    public function cleanupExportFile(string $filePath): void
    {
        if (file_exists($filePath)) {
            unlink($filePath);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isEnabled(): bool
    {
        // Check if module is disabled
        $disabledModules = get_option('plover_crm_disabled_modules', []);
        return !in_array($this->id, $disabledModules);
    }

    /**
     * Register Contact Post Type
     */
    public function registerPostType(): void
    {
        register_post_type('plover_crm_contact', [
            'labels' => [
                'name' => 'Contacts',
                'singular_name' => 'Contact',
                'add_new' => 'Add New Contact',
                'add_new_item' => 'Add New Contact',
                'edit_item' => 'Edit Contact',
                'new_item' => 'New Contact',
                'view_item' => 'View Contact',
                'search_items' => 'Search Contacts',
                'not_found' => 'No contacts found',
                'not_found_in_trash' => 'No contacts found in trash',
                'all_items' => 'All Contacts',
            ],
            'public' => false,
            'show_ui' => true,
            'show_in_menu' => false,
            'show_in_rest' => true,
            'supports' => ['thumbnail'],
            'capability_type' => 'post',
            'map_meta_cap' => true,
            'has_archive' => false,
            'hierarchical' => false,
            'rewrite' => false,
            'query_var' => false,
        ]);

        // Remove comments metabox from edit screen
        add_action('admin_menu', function () {
            remove_meta_box('commentsdiv', 'plover_crm_contact', 'normal');
            remove_meta_box('commentstatusdiv', 'plover_crm_contact', 'normal');
        });
    }

    /**
     * Register Taxonomies
     */
    public function registerTaxonomies(): void
    {
        // Lists
        register_taxonomy('plover_crm_list', 'plover_crm_contact', [
            'labels' => [
                'name' => 'Lists',
                'singular_name' => 'List',
                'search_items' => 'Search Lists',
                'all_items' => 'All Lists',
                'edit_item' => 'Edit List',
                'update_item' => 'Update List',
                'add_new_item' => 'Add New List',
                'new_item_name' => 'New List Name',
                'menu_name' => 'Lists',
            ],
            'hierarchical' => true, // Changed to true for checkbox UI
            'show_ui' => true,
            'show_in_menu' => false,
            'show_admin_column' => false, // Manually control via columns
            'show_in_rest' => true,
            'query_var' => true,
            'rewrite' => false,
        ]);

        // Tags
        register_taxonomy('plover_crm_tag', 'plover_crm_contact', [
            'labels' => [
                'name' => 'Tags',
                'singular_name' => 'Tag',
                'search_items' => 'Search Tags',
                'all_items' => 'All Tags',
                'edit_item' => 'Edit Tag',
                'update_item' => 'Update Tag',
                'add_new_item' => 'Add New Tag',
                'new_item_name' => 'New Tag Name',
                'menu_name' => 'Tags',
            ],
            'hierarchical' => true, // Changed to true for checkbox UI
            'show_ui' => true,
            'show_in_menu' => false,
            'show_admin_column' => false, // Manually control via columns
            'show_in_rest' => true,
            'query_var' => true,
            'rewrite' => false,
        ]);
    }

    /**
     * Customize featured image labels for contact avatar
     */
    public function customizeFeaturedImageLabels($labels): object
    {
        $labels->featured_image = 'Contact Photo';
        $labels->set_featured_image = 'Set contact photo';
        $labels->remove_featured_image = 'Remove contact photo';
        $labels->use_featured_image = 'Use as contact photo';

        return $labels;
    }

    /**
     * Add meta boxes
     */
    public function addMetaBoxes(): void
    {
        add_meta_box(
            'plover_crm_contact_details',
            'Contact Information',
            [$this, 'renderContactDetailsMetaBox'],
            'plover_crm_contact',
            'normal',
            'high'
        );

        // Custom fields meta box
        add_meta_box(
            'plover_crm_custom_fields',
            'Custom Fields',
            [$this, 'renderCustomFieldsMetaBox'],
            'plover_crm_contact',
            'normal',
            'default'
        );

        // Notes meta box
        add_meta_box(
            'plover_crm_notes',
            'Notes',
            [$this, 'renderNotesMetaBox'],
            'plover_crm_contact',
            'normal',
            'default'
        );
    }

    /**
     * Render contact details meta box
     */
    public function renderContactDetailsMetaBox($post): void
    {
        wp_nonce_field('plover_crm_contact_meta', 'plover_crm_contact_meta_nonce');

        $unique_field = get_option('plover_crm_unique_field', 'email');

        $email = get_post_meta($post->ID, 'plover_crm_email', true);
        $first_name = get_post_meta($post->ID, 'plover_crm_first_name', true);
        $last_name = get_post_meta($post->ID, 'plover_crm_last_name', true);
        $phone = get_post_meta($post->ID, 'plover_crm_phone', true);
        $city = get_post_meta($post->ID, 'plover_crm_city', true);
        $state = get_post_meta($post->ID, 'plover_crm_state', true);
        $country = get_post_meta($post->ID, 'plover_crm_country', true);
        $postal_code = get_post_meta($post->ID, 'plover_crm_postal_code', true);
?>
        <style>
            .plvcrm-crm-field {
                margin-bottom: 15px;
                position: relative;
            }

            .plvcrm-crm-field label {
                display: inline-block;
                width: 150px;
                font-weight: 600;
            }

            .plvcrm-crm-field input {
                width: 300px;
            }

            .plvcrm-crm-field .plvcrm-crm-error {
                color: #dc3232;
                font-size: 12px;
                margin-left: 155px;
                display: none;
            }

            .plvcrm-crm-field .plvcrm-crm-checking {
                color: #666;
                font-size: 12px;
                margin-left: 155px;
                display: none;
            }

            .plvcrm-crm-custom-field .plvcrm-crm-error {
                color: #dc3232;
                font-size: 12px;
                margin-left: 0;
                display: none;
            }

            .plvcrm-crm-custom-field .plvcrm-crm-checking {
                color: #666;
                font-size: 12px;
                margin-left: 0;
                display: none;
            }
        </style>

        <script>
            jQuery(document).ready(function($) {
                var uniqueField = '<?php echo esc_js($unique_field); ?>';
                var postId = <?php echo intval($post->ID); ?>;
                var checkTimeout;
                var $publishBtn = $('#publish');

                // Get the input element based on unique field
                var fieldId = uniqueField;
                if (uniqueField === 'email') {
                    fieldId = 'plover_crm_email';
                } else if (uniqueField === 'phone') {
                    fieldId = 'plover_crm_phone';
                }

                var $uniqueInput = uniqueField.indexOf('plover_crm_cf_') === 0 ?
                    $('input[name="' + uniqueField + '"]') :
                    $('#' + fieldId);

                if ($uniqueInput.length) {
                    // Add error message container
                    $uniqueInput.closest('.plvcrm-crm-field, .plvcrm-crm-custom-field').append(
                        '<div class="plvcrm-crm-checking">Checking...</div>' +
                        '<div class="plvcrm-crm-error">This value already exists. Please use a unique value.</div>'
                    );

                    // Check on blur and input
                    $uniqueInput.on('blur input', function() {
                        clearTimeout(checkTimeout);

                        var value = $(this).val().trim();
                        var $error = $(this).closest('.plvcrm-crm-field, .plvcrm-crm-custom-field').find('.plvcrm-crm-error');
                        var $checking = $(this).closest('.plvcrm-crm-field, .plvcrm-crm-custom-field').find('.plvcrm-crm-checking');

                        if (!value) {
                            $error.hide();
                            $checking.hide();
                            $publishBtn.prop('disabled', false);
                            return;
                        }

                        $checking.show();
                        $error.hide();
                        $publishBtn.prop('disabled', true);

                        checkTimeout = setTimeout(function() {
                            $.post(ajaxurl, {
                                action: 'plover_crm_check_unique',
                                nonce: '<?php echo wp_create_nonce('plover_crm_unique_check'); ?>',
                                field_name: uniqueField === 'email' ? 'plover_crm_email' : (uniqueField === 'phone' ? 'plover_crm_phone' : uniqueField),
                                field_value: value,
                                post_id: postId
                            }, function(response) {
                                $checking.hide();
                                if (response.success && !response.data.unique) {
                                    $error.show();
                                    $uniqueInput.get(0).setCustomValidity('This value already exists');
                                    $publishBtn.prop('disabled', true);
                                } else {
                                    $error.hide();
                                    $uniqueInput.get(0).setCustomValidity('');
                                    $publishBtn.prop('disabled', false);
                                }
                            }).fail(function() {
                                $checking.hide();
                                $publishBtn.prop('disabled', false);
                            });
                        }, 500);
                    });
                }
            });
        </script>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_email">Email<?php echo $unique_field === 'email' ? ' *' : ''; ?></label>
            <input type="email" id="plover_crm_email" name="plover_crm_email" value="<?php echo esc_attr($email); ?>" <?php echo $unique_field === 'email' ? 'required' : ''; ?> />
        </div>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_first_name">First Name</label>
            <input type="text" id="plover_crm_first_name" name="plover_crm_first_name" value="<?php echo esc_attr($first_name); ?>" />
        </div>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_last_name">Last Name</label>
            <input type="text" id="plover_crm_last_name" name="plover_crm_last_name" value="<?php echo esc_attr($last_name); ?>" />
        </div>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_phone">Phone<?php echo $unique_field === 'phone' ? ' *' : ''; ?></label>
            <input type="text" id="plover_crm_phone" name="plover_crm_phone" value="<?php echo esc_attr($phone); ?>" <?php echo $unique_field === 'phone' ? 'required' : ''; ?> />
        </div>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_city">City</label>
            <input type="text" id="plover_crm_city" name="plover_crm_city" value="<?php echo esc_attr($city); ?>" />
        </div>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_state">State</label>
            <input type="text" id="plover_crm_state" name="plover_crm_state" value="<?php echo esc_attr($state); ?>" />
        </div>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_country">Country</label>
            <input type="text" id="plover_crm_country" name="plover_crm_country" value="<?php echo esc_attr($country); ?>" />
        </div>

        <div class="plvcrm-crm-field">
            <label for="plover_crm_postal_code">Postal Code</label>
            <input type="text" id="plover_crm_postal_code" name="plover_crm_postal_code" value="<?php echo esc_attr($postal_code); ?>" />
        </div>
    <?php
    }

    /**
     * Render custom fields meta box
     */
    public function renderCustomFieldsMetaBox($post): void
    {
        $customFieldsManager = new CustomFieldsManager();
        $customFieldsRenderer = new CustomFieldsRenderer($customFieldsManager);
        $customFieldsRenderer->render($post->ID);
    }

    /**
     * Render notes meta box
     */
    public function renderNotesMetaBox($post): void
    {
        $notesManager = new NotesManager();
        $result = $notesManager->getContactNotes($post->ID, 1, 999); // Get all notes for metabox
        $notes = $result['notes'] ?? [];
        $noteTypes = NotesManager::getNoteTypes();
    ?>
        <div id="plvcrm-crm-notes-container">
            <?php if (!empty($notes)): ?>
                <div class="plvcrm-crm-notes-list">
                    <?php foreach ($notes as $note): ?>
                        <div class="plvcrm-crm-note" data-note-id="<?php echo esc_attr($note['id']); ?>">
                            <div class="plvcrm-crm-note-header">
                                <span class="plvcrm-crm-note-type plover-crm-note-type-<?php echo esc_attr($note['type']); ?>">
                                    <?php echo esc_html($noteTypes[$note['type']] ?? 'Note'); ?>
                                </span>
                                <strong><?php echo esc_html($note['title']); ?></strong>
                                <span class="plvcrm-crm-note-meta">
                                    by <?php echo esc_html($note['created_by'] ?? 'Unknown'); ?> on <?php echo esc_html(date('M j, Y g:i A', strtotime($note['created_at']))); ?>
                                </span>
                                <button type="button" class="button button-small plover-crm-edit-note"
                                    data-note-id="<?php echo esc_attr($note['id']); ?>"
                                    data-note-type="<?php echo esc_attr($note['type']); ?>"
                                    data-note-title="<?php echo esc_attr($note['title']); ?>"
                                    data-note-description="<?php echo esc_attr($note['description']); ?>"
                                    data-note-created-at="<?php echo esc_attr($note['created_at']); ?>">Edit</button>
                                <button type="button" class="button button-small plover-crm-delete-note" data-note-id="<?php echo esc_attr($note['id']); ?>">Delete</button>
                            </div>
                            <div class="plvcrm-crm-note-content">
                                <?php echo nl2br(esc_html($note['description'])); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="plvcrm-crm-no-notes">No notes yet.</p>
            <?php endif; ?>

            <div class="plvcrm-crm-add-note-form" style="margin-top: 20px; display: none;">
                <h4>Add New Note</h4>
                <table class="form-table">
                    <tr>
                        <th><label for="plover_crm_note_type">Type</label></th>
                        <td>
                            <select id="plover_crm_note_type" style="width: 200px;">
                                <?php foreach ($noteTypes as $type_key => $type_label): ?>
                                    <option value="<?php echo esc_attr($type_key); ?>"><?php echo esc_html($type_label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="plover_crm_note_title">Title</label></th>
                        <td><input type="text" id="plover_crm_note_title" class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th><label for="plover_crm_note_description">Description</label></th>
                        <td><textarea id="plover_crm_note_description" rows="4" class="large-text"></textarea></td>
                    </tr>
                </table>
                <p>
                    <button type="button" class="button button-primary" id="plvcrm-crm-save-note">Save Note</button>
                    <button type="button" class="button" id="plvcrm-crm-cancel-note">Cancel</button>
                </p>
            </div>

            <p>
                <button type="button" class="button" id="plvcrm-crm-add-note-btn">Add Note</button>
            </p>
        </div>

        <!-- Edit Note Modal -->
        <div id="plvcrm-crm-edit-note-modal" style="display: none;">
            <div class="plvcrm-crm-modal-overlay"></div>
            <div class="plvcrm-crm-modal-content">
                <div class="plvcrm-crm-modal-header">
                    <h2>Edit Note</h2>
                    <button type="button" class="plvcrm-crm-modal-close">&times;</button>
                </div>
                <div class="plvcrm-crm-modal-body">
                    <input type="hidden" id="plover_crm_edit_note_id" />
                    <table class="form-table">
                        <tr>
                            <th><label for="plover_crm_edit_note_type">Type</label></th>
                            <td>
                                <select id="plover_crm_edit_note_type" style="width: 100%;">
                                    <?php foreach ($noteTypes as $type_key => $type_label): ?>
                                        <option value="<?php echo esc_attr($type_key); ?>"><?php echo esc_html($type_label); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="plover_crm_edit_note_title">Title</label></th>
                            <td><input type="text" id="plover_crm_edit_note_title" class="regular-text" style="width: 100%;" /></td>
                        </tr>
                        <tr>
                            <th><label for="plover_crm_edit_note_description">Description</label></th>
                            <td><textarea id="plover_crm_edit_note_description" rows="6" style="width: 100%;"></textarea></td>
                        </tr>
                        <tr>
                            <th><label for="plover_crm_edit_note_date">Date</label></th>
                            <td>
                                <input type="datetime-local" id="plover_crm_edit_note_date" style="width: 100%;" />
                                <p class="description">Change the note creation date and time</p>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="plvcrm-crm-modal-footer">
                    <button type="button" class="button button-primary" id="plvcrm-crm-update-note">Update Note</button>
                    <button type="button" class="button plover-crm-modal-close">Cancel</button>
                </div>
            </div>
        </div>

        <style>
            .plvcrm-crm-note {
                border: 1px solid #ddd;
                padding: 15px;
                margin-bottom: 10px;
                background: #f9f9f9;
            }

            .plvcrm-crm-note-header {
                margin-bottom: 10px;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .plvcrm-crm-note-type {
                padding: 3px 8px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: 600;
                text-transform: uppercase;
            }

            .plvcrm-crm-note-type-call {
                background: #e3f2fd;
                color: #1976d2;
            }

            .plvcrm-crm-note-type-email {
                background: #f3e5f5;
                color: #7b1fa2;
            }

            .plvcrm-crm-note-type-meeting {
                background: #e8f5e9;
                color: #388e3c;
            }

            .plvcrm-crm-note-type-task {
                background: #fff3e0;
                color: #f57c00;
            }

            .plvcrm-crm-note-type-note {
                background: #e0e0e0;
                color: #424242;
            }

            .plvcrm-crm-note-meta {
                color: #666;
                font-size: 12px;
                margin-left: auto;
            }

            .plvcrm-crm-note-content {
                color: #333;
                line-height: 1.6;
            }

            .plvcrm-crm-no-notes {
                font-style: italic;
                color: #666;
            }

            .plvcrm-crm-edit-note,
            .plvcrm-crm-delete-note {
                margin-left: 5px;
            }

            /* Modal Styles */
            .plvcrm-crm-modal-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.7);
                z-index: 100000;
            }

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

            .plvcrm-crm-modal-header {
                padding: 20px;
                border-bottom: 1px solid #ddd;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .plvcrm-crm-modal-header h2 {
                margin: 0;
                font-size: 18px;
            }

            .plvcrm-crm-modal-close {
                background: none;
                border: none;
                font-size: 28px;
                line-height: 1;
                cursor: pointer;
                color: #666;
                padding: 0;
            }

            .plvcrm-crm-modal-close:hover {
                color: #000;
            }

            .plvcrm-crm-modal-body {
                padding: 20px;
            }

            .plvcrm-crm-modal-footer {
                padding: 15px 20px;
                border-top: 1px solid #ddd;
                text-align: right;
            }

            .plvcrm-crm-modal-footer .button {
                margin-left: 10px;
            }
        </style>

        <script>
            jQuery(document).ready(function($) {
                var postId = <?php echo intval($post->ID); ?>;

                // Show add note form
                $('#plvcrm-crm-add-note-btn').on('click', function() {
                    $('.plvcrm-crm-add-note-form').slideDown();
                    $(this).hide();
                });

                // Cancel add note
                $('#plvcrm-crm-cancel-note').on('click', function() {
                    $('.plvcrm-crm-add-note-form').slideUp();
                    $('#plvcrm-crm-add-note-btn').show();
                    $('#plover_crm_note_title').val('');
                    $('#plover_crm_note_description').val('');
                });

                // Save note
                $('#plvcrm-crm-save-note').on('click', function() {
                    var type = $('#plover_crm_note_type').val();
                    var title = $('#plover_crm_note_title').val();
                    var description = $('#plover_crm_note_description').val();

                    if (!title || !description) {
                        alert('Title and description are required');
                        return;
                    }

                    $.post(ajaxurl, {
                        action: 'plover_crm_add_note',
                        nonce: '<?php echo wp_create_nonce('plover_crm_notes'); ?>',
                        contact_id: postId,
                        type: type,
                        title: title,
                        description: description
                    }, function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert(response.data || 'Failed to add note');
                        }
                    });
                });

                // Show edit note modal
                $(document).on('click', '.plvcrm-crm-edit-note', function() {
                    var noteId = $(this).data('note-id');
                    var noteType = $(this).data('note-type');
                    var noteTitle = $(this).data('note-title');
                    var noteDescription = $(this).data('note-description');
                    var noteCreatedAt = $(this).data('note-created-at');

                    // Convert MySQL datetime to datetime-local format (YYYY-MM-DDTHH:MM)
                    var dateObj = new Date(noteCreatedAt);
                    var year = dateObj.getFullYear();
                    var month = String(dateObj.getMonth() + 1).padStart(2, '0');
                    var day = String(dateObj.getDate()).padStart(2, '0');
                    var hours = String(dateObj.getHours()).padStart(2, '0');
                    var minutes = String(dateObj.getMinutes()).padStart(2, '0');
                    var datetimeLocal = year + '-' + month + '-' + day + 'T' + hours + ':' + minutes;

                    $('#plover_crm_edit_note_id').val(noteId);
                    $('#plover_crm_edit_note_type').val(noteType);
                    $('#plover_crm_edit_note_title').val(noteTitle);
                    $('#plover_crm_edit_note_description').val(noteDescription);
                    $('#plover_crm_edit_note_date').val(datetimeLocal);

                    $('#plvcrm-crm-edit-note-modal').fadeIn(200);
                });

                // Close modal
                $(document).on('click', '.plvcrm-crm-modal-close, .plvcrm-crm-modal-overlay', function() {
                    $('#plvcrm-crm-edit-note-modal').fadeOut(200);
                });

                // Prevent modal content click from closing
                $(document).on('click', '.plvcrm-crm-modal-content', function(e) {
                    e.stopPropagation();
                });

                // Update note
                $('#plvcrm-crm-update-note').on('click', function() {
                    var noteId = $('#plover_crm_edit_note_id').val();
                    var type = $('#plover_crm_edit_note_type').val();
                    var title = $('#plover_crm_edit_note_title').val();
                    var description = $('#plover_crm_edit_note_description').val();
                    var createdAt = $('#plover_crm_edit_note_date').val();

                    if (!title || !description) {
                        alert('Title and description are required');
                        return;
                    }

                    // Convert datetime-local to MySQL datetime format
                    var mysqlDatetime = '';
                    if (createdAt) {
                        mysqlDatetime = createdAt.replace('T', ' ') + ':00';
                    }

                    $.post(ajaxurl, {
                        action: 'plover_crm_update_note',
                        nonce: '<?php echo wp_create_nonce('plover_crm_notes'); ?>',
                        note_id: noteId,
                        contact_id: postId,
                        type: type,
                        title: title,
                        description: description,
                        created_at: mysqlDatetime
                    }, function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert(response.data || 'Failed to update note');
                        }
                    });
                });

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

                    var noteId = $(this).data('note-id');

                    $.post(ajaxurl, {
                        action: 'plover_crm_delete_note',
                        nonce: '<?php echo wp_create_nonce('plover_crm_notes'); ?>',
                        note_id: noteId
                    }, function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert(response.data || 'Failed to delete note');
                        }
                    });
                });
            });
        </script>
<?php
    }



    /**
     * Save contact meta
     */
    public function saveContactMeta($post_id, $post): void
    {
        // Check nonce
        if (
            !isset($_POST['plover_crm_contact_meta_nonce']) ||
            !wp_verify_nonce($_POST['plover_crm_contact_meta_nonce'], 'plover_crm_contact_meta')
        ) {
            return;
        }

        // Check autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // Validate unique field
        $unique_field = get_option('plover_crm_unique_field', 'email');
        $unique_value = '';

        if ($unique_field === 'email' && isset($_POST['plover_crm_email'])) {
            $unique_value = sanitize_email($_POST['plover_crm_email']);
        } elseif ($unique_field === 'phone' && isset($_POST['plover_crm_phone'])) {
            $unique_value = sanitize_text_field($_POST['plover_crm_phone']);
        } elseif (strpos($unique_field, 'plover_crm_cf_') === 0 && isset($_POST[$unique_field])) {
            $unique_value = sanitize_text_field($_POST[$unique_field]);
        }

        // Check if unique value is provided
        if (empty($unique_value)) {
            wp_die('The unique field is required.');
        }

        // Check for duplicates
        $args = [
            'post_type' => 'plover_crm_contact',
            'posts_per_page' => 1,
            'post__not_in' => [$post_id],
            'meta_query' => [
                [
                    'key' => $unique_field === 'email' ? 'plover_crm_email' : ($unique_field === 'phone' ? 'plover_crm_phone' : $unique_field),
                    'value' => $unique_value,
                    'compare' => '='
                ]
            ]
        ];

        $duplicate = new \WP_Query($args);

        if ($duplicate->have_posts()) {
            wp_die('A contact with this ' . str_replace(['plover_crm_', 'plover_crm_cf_', '_'], ['', '', ' '], $unique_field) . ' already exists.');
        }

        $crm = $this->container->get('crm');
        $previousContact = $crm->getContact($post_id);
        $previousStage = self::extractStageValue($previousContact);

        // Save standard fields
        $fields = [
            'plover_crm_email',
            'plover_crm_first_name',
            'plover_crm_last_name',
            'plover_crm_phone',
            'plover_crm_city',
            'plover_crm_state',
            'plover_crm_country',
            'plover_crm_postal_code',
        ];

        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                $value = sanitize_text_field($_POST[$field]);
                update_post_meta($post_id, $field, $value);
            }
        }

        // Generate hash for email
        if (isset($_POST['plover_crm_email'])) {
            $email = sanitize_email($_POST['plover_crm_email']);
            update_post_meta($post_id, 'plover_crm_hash', md5($email));
        }

        // Save custom fields
        $customFieldsManager = new CustomFieldsManager();
        $customFieldsManager->saveContactCustomFields($post_id, $_POST);

        // Fire contact updated hook (skip during bulk import)
        if (!\PloverCRM\Common\Utils::isBulkImporting()) {
            $contact = $crm->getContact($post_id);
            $currentStage = self::extractStageValue($contact);
            $previousValues = [];
            $updatedValues = [];

            if ($previousStage !== $currentStage) {
                $previousValues['stage-plover-crm'] = $previousStage;
                $updatedValues['stage-plover-crm'] = $currentStage;
            }

            do_action('plover_crm/contact_updated', $post_id, $contact, $previousValues, $updatedValues);
        }
    }

    private static function extractStageValue(?array $contact): ?string
    {
        if (empty($contact)) {
            return null;
        }

        foreach ((array) ($contact['custom_fields'] ?? []) as $field) {
            if (!is_array($field) || ($field['key'] ?? '') !== 'stage-plover-crm') {
                continue;
            }

            $value = $field['value'] ?? null;
            if ($value === null || $value === '') {
                return null;
            }

            return (string) $value;
        }

        return null;
    }

    /**
     * Extend search to include all fields and custom fields
     */
    public function extendContactSearch($search, $query)
    {
        global $wpdb;

        if (!is_admin() || !$query->is_main_query() || $query->get('post_type') !== 'plover_crm_contact') {
            return $search;
        }

        $search_term = $query->get('s');
        if (empty($search_term)) {
            return $search;
        }

        // Search in post meta fields only
        $search = " AND {$wpdb->postmeta}.meta_value LIKE '%" . esc_sql($wpdb->esc_like($search_term)) . "%'";

        return $search;
    }

    /**
     * Join postmeta table for search
     */
    public function extendContactSearchJoin($join, $query)
    {
        global $wpdb;

        if (!is_admin() || !$query->is_main_query() || $query->get('post_type') !== 'plover_crm_contact') {
            return $join;
        }

        if (!empty($query->get('s'))) {
            $join .= " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id";
        }

        return $join;
    }

    /**
     * Group by post ID to avoid duplicates
     */
    public function extendContactSearchGroupBy($groupby, $query)
    {
        global $wpdb;

        if (!is_admin() || !$query->is_main_query() || $query->get('post_type') !== 'plover_crm_contact') {
            return $groupby;
        }

        if (!empty($query->get('s'))) {
            $groupby = "{$wpdb->posts}.ID";
        }

        return $groupby;
    }

    /**
     * Hide parent dropdown for lists and tags
     */
    public function hideParentDropdown(): void
    {
        global $current_screen;

        if ($current_screen && ($current_screen->taxonomy === 'plover_crm_list' || $current_screen->taxonomy === 'plover_crm_tag')) {
            echo '<style>
                .form-field.term-parent-wrap { display: none !important; }
            </style>';
        }

        // Also hide on post edit screen
        if ($current_screen && $current_screen->post_type === 'plover_crm_contact') {
            echo '<style>
                #newplover_crm_list_parent, #newplover_crm_tag_parent { display: none !important; }
            </style>';
        }
    }

    /**
     * Hide avatar checkbox from Screen Options
     */
    public function hideAvatarFromScreenOptions(): void
    {
        global $current_screen;

        if ($current_screen && $current_screen->post_type === 'plover_crm_contact') {
            echo '<style>
                label:has(input#avatar-hide) { display: none !important; }
                .column-avatar { width: 50px; }
            </style>';
        }
    }

    /**
     * Remove quick edit and trash from row actions
     */
    public function removeQuickEdit($actions, $post)
    {
        if ($post->post_type === 'plover_crm_contact') {
            unset($actions['inline hide-if-no-js']);
            unset($actions['trash']);
        }
        return $actions;
    }

    /**
     * Customize admin title for contact edit screen
     */
    public function customizeContactEditTitle($admin_title, $title)
    {
        global $post, $pagenow;

        if (($pagenow === 'post.php' || $pagenow === 'post-new.php') &&
            isset($post) && $post->post_type === 'plover_crm_contact'
        ) {

            $unique_field = get_option('plover_crm_unique_field', 'email');
            $identifier = '';

            if ($post->ID) {
                if ($unique_field === 'email') {
                    $identifier = get_post_meta($post->ID, 'plover_crm_email', true);
                } elseif ($unique_field === 'phone') {
                    $identifier = get_post_meta($post->ID, 'plover_crm_phone', true);
                } elseif (strpos($unique_field, 'plover_crm_cf_') === 0) {
                    $identifier = get_post_meta($post->ID, $unique_field, true);
                }

                // Fallback to contact ID if no identifier found
                if (empty($identifier)) {
                    $identifier = '#' . $post->ID;
                }
            }

            $site_name = get_bloginfo('name');

            if ($pagenow === 'post-new.php') {
                return "New Contact — $site_name — WordPress";
            }

            return "Edit Contact: $identifier — $site_name — WordPress";
        }

        return $admin_title;
    }

    /**
     * Set default hidden columns
     */
    public function setDefaultHiddenColumns($hidden, $screen)
    {
        if ($screen->post_type === 'plover_crm_contact') {
            // Get unique field
            $unique_field = get_option('plover_crm_unique_field', 'email');

            // Hide these columns by default (users can show them via Screen Options)
            $hidden = ['taxonomy-plover_crm_list', 'taxonomy-plover_crm_tag'];

            // Hide phone and last_name if they're not the unique field
            if ($unique_field !== 'phone') {
                $hidden[] = 'phone';
            }
            $hidden[] = 'last_name';

            // Hide email if it's not the unique field
            if ($unique_field !== 'email') {
                $hidden[] = 'email';
            }

            // Hide all custom fields by default (except the unique field)
            $customFieldsManager = new CustomFieldsManager();
            $customFields = $customFieldsManager->getAllFields();

            foreach ($customFields as $field) {
                $cf_key = 'plover_crm_cf_' . $field['slug'];
                if ($cf_key !== $unique_field) {
                    $hidden[] = 'cf_' . $field['slug'];
                }
            }
        }

        return $hidden;
    }

    /**
     * Prevent hiding avatar and unique field columns
     */
    public function preventHidingColumns($hidden, $screen)
    {
        if ($screen->post_type === 'plover_crm_contact') {
            // Always show avatar
            $hidden = array_diff($hidden, ['avatar']);

            // Get unique field
            $unique_field = get_option('plover_crm_unique_field', 'email');

            // Determine the column key for the unique field
            $unique_column = '';
            if ($unique_field === 'email') {
                $unique_column = 'email';
            } elseif ($unique_field === 'phone') {
                $unique_column = 'phone';
            } elseif (strpos($unique_field, 'plover_crm_cf_') === 0) {
                $slug = str_replace('plover_crm_cf_', '', $unique_field);
                $unique_column = 'cf_' . $slug;
            }

            // Remove unique field from hidden columns
            if ($unique_column && in_array($unique_column, $hidden)) {
                $hidden = array_diff($hidden, [$unique_column]);
            }
        }

        return $hidden;
    }



    /**
     * Add custom columns to contacts list
     */
    public function addContactColumns($columns): array
    {
        // Remove default columns
        unset($columns['title']);
        unset($columns['date']);

        // Get unique field setting
        $unique_field = get_option('plover_crm_unique_field', 'email');

        // Build new columns array
        $new_columns = [];

        // Keep checkbox if it exists
        if (isset($columns['cb'])) {
            $new_columns['cb'] = $columns['cb'];
        }

        // Avatar as first column (optional)
        $new_columns['avatar'] = 'Avatar';

        // Add unique field as the next column (always visible)
        if ($unique_field === 'email') {
            $new_columns['email'] = 'Email *';
        } elseif ($unique_field === 'phone') {
            $new_columns['phone'] = 'Phone *';
        } elseif (strpos($unique_field, 'plover_crm_cf_') === 0) {
            // It's a custom field
            $customFieldsManager = new CustomFieldsManager();
            $customFields = $customFieldsManager->getAllFields();
            $slug = str_replace('plover_crm_cf_', '', $unique_field);

            foreach ($customFields as $field) {
                if ($field['slug'] === $slug) {
                    $new_columns['cf_' . $slug] = $field['label'] . ' *';
                    break;
                }
            }
        }

        // Add other standard field columns (excluding the unique field)
        if ($unique_field !== 'email') {
            $new_columns['email'] = 'Email';
        }

        $new_columns['first_name'] = 'First Name';
        $new_columns['last_name'] = 'Last Name';

        if ($unique_field !== 'phone') {
            $new_columns['phone'] = 'Phone';
        }

        // Add taxonomy columns
        $new_columns['taxonomy-plover_crm_list'] = 'Lists';
        $new_columns['taxonomy-plover_crm_tag'] = 'Tags';

        // Add custom field columns (excluding the unique field if it's a custom field)
        $customFieldsManager = new CustomFieldsManager();
        $customFields = $customFieldsManager->getAllFields();

        foreach ($customFields as $field) {
            $cf_key = 'plover_crm_cf_' . $field['slug'];
            if ($cf_key !== $unique_field) {
                $new_columns['cf_' . $field['slug']] = $field['label'];
            }
        }

        $new_columns['date'] = 'Created At';

        return $new_columns;
    }

    /**
     * Render custom column content
     */
    public function renderContactColumn($column, $post_id): void
    {
        // Get unique field to determine which column should be clickable
        $unique_field = get_option('plover_crm_unique_field', 'email');
        $edit_url = get_edit_post_link($post_id);

        switch ($column) {
            case 'avatar':
                if (has_post_thumbnail($post_id)) {
                    echo get_the_post_thumbnail($post_id, [40, 40], ['style' => 'border-radius: 50%; width: 40px; height: 40px; object-fit: cover;']);
                } else {
                    echo '<div style="width: 40px; height: 40px; border-radius: 50%; background: #f0f0f1; display: flex; align-items: center; justify-content: center;">';
                    echo '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width: 24px; height: 24px; fill: #a7aaad;">';
                    echo '<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>';
                    echo '</svg></div>';
                }
                break;

            case 'email':
                $email = get_post_meta($post_id, 'plover_crm_email', true);
                if ($unique_field === 'email') {
                    echo '<strong>' . esc_html($email) . '</strong>';
                } else {
                    echo esc_html($email);
                }
                break;

            case 'first_name':
                echo esc_html(get_post_meta($post_id, 'plover_crm_first_name', true));
                break;

            case 'last_name':
                echo esc_html(get_post_meta($post_id, 'plover_crm_last_name', true));
                break;

            case 'phone':
                $phone = get_post_meta($post_id, 'plover_crm_phone', true);
                if ($unique_field === 'phone') {
                    echo '<strong>' . esc_html($phone) . '</strong>';
                } else {
                    echo esc_html($phone);
                }
                break;

            case 'taxonomy-plover_crm_list':
                $terms = get_the_terms($post_id, 'plover_crm_list');
                if ($terms && !is_wp_error($terms)) {
                    $term_names = array_map(function ($term) {
                        return $term->name;
                    }, $terms);
                    echo esc_html(implode(', ', $term_names));
                }
                break;

            case 'taxonomy-plover_crm_tag':
                $terms = get_the_terms($post_id, 'plover_crm_tag');
                if ($terms && !is_wp_error($terms)) {
                    $term_names = array_map(function ($term) {
                        return $term->name;
                    }, $terms);
                    echo esc_html(implode(', ', $term_names));
                }
                break;

            default:
                // Check if it's a custom field
                if (strpos($column, 'cf_') === 0) {
                    $slug = substr($column, 3);
                    $value = get_post_meta($post_id, 'plover_crm_cf_' . $slug, true);

                    // Check if this custom field is the unique field
                    $cf_key = 'plover_crm_cf_' . $slug;
                    $is_unique = ($unique_field === $cf_key);

                    if (is_array($value)) {
                        $display_value = implode(', ', $value);
                    } else {
                        $display_value = $value;
                    }

                    if ($is_unique) {
                        echo '<strong>' . esc_html($display_value) . '</strong>';
                    } else {
                        echo esc_html($display_value);
                    }
                }
                break;
        }
    }

    /**
     * AJAX: Add note
     */
    public function ajaxAddNote(): void
    {
        check_ajax_referer('plover_crm_notes', 'nonce');

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

        $contact_id = intval($_POST['contact_id'] ?? 0);
        $data = [
            'type' => $_POST['type'] ?? 'note',
            'title' => $_POST['title'] ?? '',
            'description' => $_POST['description'] ?? '',
        ];

        if (empty($data['title']) || empty($data['description'])) {
            wp_send_json_error('Title and description are required');
        }

        $notesManager = new NotesManager();
        $note_id = $notesManager->addNote($contact_id, $data);

        if ($note_id) {
            wp_send_json_success();
        } else {
            wp_send_json_error('Failed to add note');
        }
    }

    /**
     * AJAX: Update note
     */
    public function ajaxUpdateNote(): void
    {
        check_ajax_referer('plover_crm_notes', 'nonce');

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

        $note_id = intval($_POST['note_id'] ?? 0);
        $contact_id = intval($_POST['contact_id'] ?? 0);
        $data = [
            'contact_id' => $contact_id,
            'type' => $_POST['type'] ?? 'note',
            'title' => $_POST['title'] ?? '',
            'description' => $_POST['description'] ?? '',
        ];

        // Add created_at if provided
        if (!empty($_POST['created_at'])) {
            $data['created_at'] = $_POST['created_at'];
        }

        if (empty($note_id)) {
            wp_send_json_error('Note ID is required');
        }

        if (empty($data['title']) || empty($data['description'])) {
            wp_send_json_error('Title and description are required');
        }

        $notesManager = new NotesManager();
        $result = $notesManager->updateNote($note_id, $data);

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

    /**
     * AJAX: Delete note
     */
    public function ajaxDeleteNote(): void
    {
        check_ajax_referer('plover_crm_notes', 'nonce');

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

        $note_id = intval($_POST['note_id'] ?? 0);

        if (empty($note_id)) {
            wp_send_json_error('Note ID is required');
        }

        $notesManager = new NotesManager();
        $result = $notesManager->deleteNote($note_id);

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

    /**
     * AJAX: Check if unique field value already exists
     */
    public function ajaxCheckUnique(): void
    {
        check_ajax_referer('plover_crm_unique_check', 'nonce');

        $field_name = $_POST['field_name'] ?? '';
        $field_value = $_POST['field_value'] ?? '';
        $post_id = intval($_POST['post_id'] ?? 0);

        if (empty($field_name) || empty($field_value)) {
            wp_send_json_success(['unique' => true]);
        }

        // Check for duplicates
        $args = [
            'post_type' => 'plover_crm_contact',
            'posts_per_page' => 1,
            'post__not_in' => $post_id ? [$post_id] : [],
            'meta_query' => [
                [
                    'key' => $field_name,
                    'value' => $field_value,
                    'compare' => '='
                ]
            ]
        ];

        $duplicate = new \WP_Query($args);

        wp_send_json_success(['unique' => !$duplicate->have_posts()]);
    }

    /**
     * Fix menu highlighting for taxonomy pages
     */
    public function fixTaxonomyMenuHighlight($parent_file)
    {
        global $current_screen;

        if (!$current_screen) {
            return $parent_file;
        }

        // Highlight parent menu for Lists and Tags taxonomy pages
        if ($current_screen->taxonomy === 'plover_crm_list' || $current_screen->taxonomy === 'plover_crm_tag') {
            $parent_file = 'edit.php?post_type=plover_crm_contact';
        }

        return $parent_file;
    }

    /**
     * Fix submenu highlighting for taxonomy pages
     */
    public function fixTaxonomySubmenuHighlight($submenu_file)
    {
        global $current_screen;

        if (!$current_screen) {
            return $submenu_file;
        }

        // Highlight correct submenu for Lists and Tags
        if ($current_screen->taxonomy === 'plover_crm_list') {
            $submenu_file = 'edit-tags.php?taxonomy=plover_crm_list&post_type=plover_crm_contact';
        } elseif ($current_screen->taxonomy === 'plover_crm_tag') {
            $submenu_file = 'edit-tags.php?taxonomy=plover_crm_tag&post_type=plover_crm_contact';
        }

        return $submenu_file;
    }

    /**
     * Rename the first submenu item to "Contacts"
     */
    public function renameContactsMenu(): void
    {
        global $submenu;

        if (isset($submenu['edit.php?post_type=plover_crm_contact'])) {
            // Find and rename the first item (usually index 5 or 10)
            foreach ($submenu['edit.php?post_type=plover_crm_contact'] as $key => $item) {
                if ($item[2] === 'edit.php?post_type=plover_crm_contact') {
                    $submenu['edit.php?post_type=plover_crm_contact'][$key][0] = 'Contacts';
                    break;
                }
            }
        }
    }
}
