<?php

if (!defined('ABSPATH')) {
    exit;
}

class Kavehboardticketadmin {

    public function __construct() {
        // Ticket CPT Admin
        add_filter('manage_kaveh_ticket_posts_columns', array($this, 'set_ticket_columns'));
        add_action('manage_kaveh_ticket_posts_custom_column', array($this, 'custom_ticket_column'), 10, 2);
        add_filter('manage_edit-kaveh_ticket_sortable_columns', array($this, 'set_sortable_ticket_columns'));
        add_action('add_meta_boxes', array($this, 'add_ticket_meta_boxes'));
        add_action('save_post_kaveh_ticket', array($this, 'save_ticket_meta_data'));

        // Department Taxonomy Admin
        add_action('kaveh_department_add_form_fields', array($this, 'add_department_fields'), 10, 2);
        add_action('kaveh_department_edit_form_fields', array($this, 'edit_department_fields'), 10, 2);
        add_action('created_kaveh_department', array($this, 'save_department_meta_data'), 10, 2);
        add_action('edited_kaveh_department', array($this, 'save_department_meta_data'), 10, 2);

        // Ticket Message CPT Admin (optional, if needed for direct admin view)
        add_filter('manage_kaveh_ticket_message_posts_columns', array($this, 'set_ticket_message_columns'));
        add_action('manage_kaveh_ticket_message_posts_custom_column', array($this, 'custom_ticket_message_column'), 10, 2);

        // User Profile Fields for Agent Assignment
        add_action('show_user_profile', array($this, 'add_agent_department_field'));
        add_action('edit_user_profile', array($this, 'add_agent_department_field'));
        add_action('personal_options_update', array($this, 'save_agent_department_field'));
        add_action('edit_user_profile_update', array($this, 'save_agent_department_field'));

        // Admin notices for unassigned tickets
        add_action('admin_notices', array($this, 'unassigned_tickets_notice'));

        // AJAX for assigning agent
        add_action('wp_ajax_kavehboard_assign_agent', array($this, 'ajax_assign_agent'));
    }

    /**
     * Get all users who can act as support agents
     * (all users - no restrictions)
     */
    private function get_support_agents() {
        return get_users(array(
            'orderby' => 'display_name',
            'order' => 'ASC'
        ));
    }

    /**
     * Check if a user is a support agent (can be assigned to tickets)
     * Now returns true for any valid user
     */
    private function is_user_support_agent($user_id) {
        return $user_id > 0; // Any valid user can be a support agent
    }

    // --- Ticket CPT Admin Functions ---

    public function set_ticket_columns($columns) {
        $new_columns = array();
        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
            if ($key == 'title') {
                $new_columns['ticket_id'] = __('Ticket ID', 'kavehTheme');
                $new_columns['ticket_status'] = __('Status', 'kavehTheme');
                $new_columns['ticket_department'] = __('Department', 'kavehTheme');
                $new_columns['ticket_priority'] = __('Priority', 'kavehTheme');
                $new_columns['ticket_agent'] = __('Agent', 'kavehTheme');
            }
        }
        return $new_columns;
    }

    public function custom_ticket_column($column, $post_id) {
        switch ($column) {
            case 'ticket_id':
                echo '#' . $post_id;
                break;
            case 'ticket_status':
                $status = get_post_meta($post_id, '_kaveh_ticket_status', true);
                echo $status ? __(ucfirst($status), 'kavehTheme') : __('Open', 'kavehTheme');
                break;
            case 'ticket_department':
                $terms = get_the_terms($post_id, 'kaveh_department');
                if (!empty($terms)) {
                    foreach ($terms as $term) {
                        echo esc_html($term->name) . '<br>';
                    }
                } else {
                    _e('N/A', 'kavehTheme');
                }
                break;
            case 'ticket_priority':
                $priority = get_post_meta($post_id, '_kaveh_ticket_priority', true);
                echo $priority ? __(ucfirst($priority), 'kavehTheme') : __('Normal', 'kavehTheme');
                break;
            case 'ticket_agent':
                $agent_id = get_post_meta($post_id, '_kaveh_ticket_agent', true);
                if ($agent_id) {
                    $agent = get_user_by('ID', $agent_id);
                    echo $agent ? esc_html($agent->display_name) : __('Unassigned', 'kavehTheme');
                } else {
                    _e('Unassigned', 'kavehTheme');
                }
                break;
        }
    }

    public function set_sortable_ticket_columns($columns) {
        $columns['ticket_id'] = 'ID';
        $columns['ticket_status'] = '_kaveh_ticket_status';
        $columns['ticket_priority'] = '_kaveh_ticket_priority';
        // Department and Agent are taxonomies/meta, sorting them directly is complex.
        return $columns;
    }

    public function add_ticket_meta_boxes() {
        add_meta_box(
            'kaveh_ticket_details',
            __('Ticket Details', 'kavehTheme'),
            array($this, 'render_ticket_details_meta_box'),
            'kaveh_ticket',
            'normal',
            'high'
        );
        add_meta_box(
            'kaveh_ticket_messages',
            __('Ticket Messages', 'kavehTheme'),
            array($this, 'render_ticket_messages_meta_box'),
            'kaveh_ticket',
            'normal',
            'high'
        );
    }

    public function render_ticket_details_meta_box($post) {
        wp_nonce_field('save_ticket_meta_data', 'kaveh_ticket_nonce');

        $status = get_post_meta($post->ID, '_kaveh_ticket_status', true);
        $priority = get_post_meta($post->ID, '_kaveh_ticket_priority', true);
        $agent_id = get_post_meta($post->ID, '_kaveh_ticket_agent', true);
        $user_id = $post->post_author;
        $user_info = get_userdata($user_id);
        $departments = get_terms(array('taxonomy' => 'kaveh_department', 'hide_empty' => false));
        // Get all users who have assigned departments (support agents)
        $agents = $this->get_support_agents();

        ?>
        <p>
            <label for="kaveh_ticket_user"><?php _e('Ticket User:', 'kavehTheme'); ?></label>
            <select name="kaveh_ticket_user" id="kaveh_ticket_user">
                <option value=""><?php _e('Select User', 'kavehTheme'); ?></option>
                <?php
                $users = get_users(array('orderby' => 'display_name', 'order' => 'ASC'));
                foreach ($users as $user) :
                ?>
                    <option value="<?php echo esc_attr($user->ID); ?>" <?php selected($user_id, $user->ID); ?>><?php echo esc_html($user->display_name . ' (' . $user->user_email . ')'); ?></option>
                <?php endforeach; ?>
            </select>
            <p class="description"><?php _e('Select the user this ticket belongs to. Leave empty to keep current user.', 'kavehTheme'); ?></p>
        </p>
        <p>
            <label for="kaveh_ticket_status"><?php _e('Status:', 'kavehTheme'); ?></label>
            <select name="kaveh_ticket_status" id="kaveh_ticket_status">
                <option value="open" <?php selected($status, 'open'); ?>><?php _e('Open', 'kavehTheme'); ?></option>
                <option value="pending" <?php selected($status, 'pending'); ?>><?php _e('Pending', 'kavehTheme'); ?></option>
                <option value="closed" <?php selected($status, 'closed'); ?>><?php _e('Closed', 'kavehTheme'); ?></option>
            </select>
        </p>
        <p>
            <label for="kaveh_ticket_priority"><?php _e('Priority:', 'kavehTheme'); ?></label>
            <select name="kaveh_ticket_priority" id="kaveh_ticket_priority">
                <option value="low" <?php selected($priority, 'low'); ?>><?php _e('Low', 'kavehTheme'); ?></option>
                <option value="normal" <?php selected($priority, 'normal'); ?>><?php _e('Normal', 'kavehTheme'); ?></option>
                <option value="high" <?php selected($priority, 'high'); ?>><?php _e('High', 'kavehTheme'); ?></option>
                <option value="urgent" <?php selected($priority, 'urgent'); ?>><?php _e('Urgent', 'kavehTheme'); ?></option>
            </select>
        </p>
        <p>
            <label for="kaveh_ticket_department"><?php _e('Department:', 'kavehTheme'); ?></label>
            <select name="tax_input[kaveh_department][]" id="kaveh_ticket_department">
                <option value=""><?php _e('Select Department', 'kavehTheme'); ?></option>
                <?php foreach ($departments as $department) : ?>
                    <option value="<?php echo esc_attr($department->slug); ?>" <?php selected(has_term($department->slug, 'kaveh_department', $post->ID)); ?>><?php echo esc_html($department->name); ?></option>
                <?php endforeach; ?>
            </select>
        </p>
        <p>
            <label for="kaveh_ticket_agent"><?php _e('Assigned Agent:', 'kavehTheme'); ?></label>
            <select name="kaveh_ticket_agent" id="kaveh_ticket_agent">
                <option value=""><?php _e('Unassigned', 'kavehTheme'); ?></option>
                <?php foreach ($agents as $agent) : ?>
                    <option value="<?php echo esc_attr($agent->ID); ?>" <?php selected($agent_id, $agent->ID); ?>><?php echo esc_html($agent->display_name); ?></option>
                <?php endforeach; ?>
            </select>
        </p>
        <?php
    }

    public function render_ticket_messages_meta_box($post) {
        $messages = get_posts(array(
            'post_type' => 'kaveh_ticket_message',
            'post_parent' => $post->ID,
            'orderby' => 'date',
            'order' => 'ASC',
            'posts_per_page' => -1,
        ));

        if (!empty($messages)) {
            echo '<div class="kaveh-ticket-messages-list">';
            foreach ($messages as $message) {
                $author = get_userdata($message->post_author);
                $author_name = $author ? $author->display_name : __('Guest', 'kavehTheme');
                echo '<div class="kaveh-ticket-message">';
                echo '<strong>' . esc_html($author_name) . '</strong> <em>(' . esc_html(get_the_date('', $message->ID)) . ' ' . esc_html(get_the_time('', $message->ID)) . ')</em>:<br>';
                echo wpautop($message->post_content);
                echo '</div>';
            }
            echo '</div>';
        } else {
            _e('No messages for this ticket yet.', 'kavehTheme');
        }

        echo '<h4>' . __('Add New Message', 'kavehTheme') . '</h4>';
        echo '<textarea name="kaveh_new_ticket_message" rows="5" style="width:100%;"></textarea>';
        echo '<p><input type="submit" class="button button-primary" name="kaveh_add_ticket_message" value="' . __('Add Message', 'kavehTheme') . '"></p>';
    }

    public function save_ticket_meta_data($post_id) {
        if (!isset($_POST['kaveh_ticket_nonce']) || !wp_verify_nonce($_POST['kaveh_ticket_nonce'], 'save_ticket_meta_data')) {
            return;
        }
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        if (isset($_POST['kaveh_ticket_status'])) {
            update_post_meta($post_id, '_kaveh_ticket_status', sanitize_text_field($_POST['kaveh_ticket_status']));
        }
        if (isset($_POST['kaveh_ticket_priority'])) {
            update_post_meta($post_id, '_kaveh_ticket_priority', sanitize_text_field($_POST['kaveh_ticket_priority']));
        }
        if (isset($_POST['kaveh_ticket_agent'])) {
            update_post_meta($post_id, '_kaveh_ticket_agent', sanitize_text_field($_POST['kaveh_ticket_agent']));
        }
        
        // Update ticket user (post_author) if changed
        if (isset($_POST['kaveh_ticket_user']) && !empty($_POST['kaveh_ticket_user'])) {
            $new_user_id = intval($_POST['kaveh_ticket_user']);
            $current_author = get_post_field('post_author', $post_id);
            
            if ($new_user_id !== intval($current_author)) {
                // Update the post author
                wp_update_post(array(
                    'ID' => $post_id,
                    'post_author' => $new_user_id
                ));
            }
        }

        // Save new message
        if (isset($_POST['kaveh_new_ticket_message']) && !empty($_POST['kaveh_new_ticket_message'])) {
            $message_content = wp_kses_post($_POST['kaveh_new_ticket_message']);
            $message_id = wp_insert_post(array(
                'post_title'    => 'Message for Ticket #' . $post_id,
                'post_content'  => $message_content,
                'post_status'   => 'publish',
                'post_type'     => 'kaveh_ticket_message',
                'post_parent'   => $post_id,
                'post_author'   => get_current_user_id(),
            ));

            // Optionally, update ticket status to 'pending' if a new message is added by a support agent
            // and the status is 'open'
            $current_status = get_post_meta($post_id, '_kaveh_ticket_status', true);
            if ($this->is_user_support_agent(get_current_user_id()) && $current_status == 'open') {
                update_post_meta($post_id, '_kaveh_ticket_status', 'pending');
            }
        }
    }

    // --- Department Taxonomy Admin Functions ---

    public function add_department_fields($taxonomy) {
        ?>
        <div class="form-field term-agent-wrap">
            <label for="term-agent"><?php _e('Department Agents', 'kavehTheme'); ?></label>
            <?php
            $agents = $this->get_support_agents();
            if (!empty($agents)) {
                echo '<div style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px;">';
                foreach ($agents as $agent) {
                    echo '<label style="display: block; margin-bottom: 5px;">';
                    echo '<input type="checkbox" name="department_agents[]" value="' . esc_attr($agent->ID) . '" style="margin-right: 5px;"> ';
                    echo esc_html($agent->display_name . ' (' . $agent->user_email . ')');
                    echo '</label>';
                }
                echo '</div>';
            } else {
                _e('No users found.', 'kavehTheme');
            }
            ?>
            <p><?php _e('Assign multiple agents to this department.', 'kavehTheme'); ?></p>
        </div>
        <?php
    }

    public function edit_department_fields($term) {
        $agent_ids = get_term_meta($term->term_id, 'department_agents', true);
        if (!is_array($agent_ids)) {
            $agent_ids = array();
        }
        ?>
        <tr class="form-field term-agent-wrap">
            <th scope="row"><label for="term-agent"><?php _e('Department Agents', 'kavehTheme'); ?></label></th>
            <td>
                <?php
                $agents = $this->get_support_agents();
                if (!empty($agents)) {
                    echo '<div style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px;">';
                    foreach ($agents as $agent) {
                        $checked = in_array($agent->ID, $agent_ids) ? 'checked' : '';
                        echo '<label style="display: block; margin-bottom: 5px;">';
                        echo '<input type="checkbox" name="department_agents[]" value="' . esc_attr($agent->ID) . '" ' . $checked . ' style="margin-right: 5px;"> ';
                        echo esc_html($agent->display_name . ' (' . $agent->user_email . ')');
                        echo '</label>';
                    }
                    echo '</div>';
                } else {
                    _e('No users found.', 'kavehTheme');
                }
                ?>
                <p class="description"><?php _e('Assign multiple agents to this department.', 'kavehTheme'); ?></p>
            </td>
        </tr>
        <?php
    }

    public function save_department_meta_data($term_id) {
        if (isset($_POST['department_agents']) && is_array($_POST['department_agents'])) {
            $agent_ids = array_map('intval', $_POST['department_agents']);
            update_term_meta($term_id, 'department_agents', $agent_ids);
        } else {
            delete_term_meta($term_id, 'department_agents');
        }
        
        // Keep backward compatibility with old single agent field
        if (isset($_POST['department_agent'])) {
            update_term_meta($term_id, 'department_agent', sanitize_text_field($_POST['department_agent']));
        }
    }

    // --- Ticket Message CPT Admin Functions (if needed) ---

    public function set_ticket_message_columns($columns) {
        $columns['ticket_parent'] = __('Parent Ticket', 'kavehTheme');
        $columns['message_author'] = __('Author', 'kavehTheme');
        return $columns;
    }

    public function custom_ticket_message_column($column, $post_id) {
        switch ($column) {
            case 'ticket_parent':
                $parent_id = wp_get_post_parent_id($post_id);
                if ($parent_id) {
                    echo '<a href="' . esc_url(get_edit_post_link($parent_id)) . '">#' . $parent_id . '</a>';
                } else {
                    _e('N/A', 'kavehTheme');
                }
                break;
            case 'message_author':
                $author_id = get_post_field('post_author', $post_id);
                $author = get_userdata($author_id);
                echo $author ? esc_html($author->display_name) : __('Guest', 'kavehTheme');
                break;
        }
    }

    // --- User Profile Fields for Agent Assignment ---

    public function add_agent_department_field($user) {
        if (!current_user_can('manage_options') && !current_user_can('edit_users')) {
            return; // Only administrators can see/edit this
        }

        $assigned_departments = get_user_meta($user->ID, 'kaveh_agent_departments', true);
        if (!is_array($assigned_departments)) {
            $assigned_departments = array();
        }
        $departments = get_terms(array('taxonomy' => 'kaveh_department', 'hide_empty' => false));
        ?>
        <h3><?php _e('Support Agent Settings', 'kavehTheme'); ?></h3>
        <table class="form-table">
            <tr>
                <th><label for="kaveh_agent_departments"><?php _e('Assigned Departments', 'kavehTheme'); ?></label></th>
                <td>
                    <?php if (!empty($departments)) : ?>
                        <?php foreach ($departments as $department) : ?>
                            <input type="checkbox" name="kaveh_agent_departments[]" value="<?php echo esc_attr($department->term_id); ?>" <?php checked(in_array($department->term_id, $assigned_departments)); ?> /> <?php echo esc_html($department->name); ?><br/>
                        <?php endforeach; ?>
                    <?php else : ?>
                        <?php _e('No departments created yet.', 'kavehTheme'); ?>
                    <?php endif; ?>
                    <span class="description"><?php _e('Select departments this user can handle as a support agent.', 'kavehTheme'); ?></span>
                </td>
            </tr>
        </table>
        <?php
    }

    public function save_agent_department_field($user_id) {
        if (!current_user_can('edit_user', $user_id)) {
            return;
        }

        // Save assigned departments
        if (isset($_POST['kaveh_agent_departments']) && is_array($_POST['kaveh_agent_departments'])) {
            $departments = array_map('intval', $_POST['kaveh_agent_departments']);
            update_user_meta($user_id, 'kaveh_agent_departments', $departments);
        } else {
            delete_user_meta($user_id, 'kaveh_agent_departments');
        }
    }

    // --- Admin Notices ---

    public function unassigned_tickets_notice() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $unassigned_tickets = new WP_Query(array(
            'post_type' => 'kaveh_ticket',
            'post_status' => 'publish',
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key' => '_kaveh_ticket_agent',
                    'compare' => 'NOT EXISTS'
                ),
                array(
                    'key' => '_kaveh_ticket_agent',
                    'value' => '',
                    'compare' => '='
                )
            ),
            'posts_per_page' => 1,
            'fields' => 'ids' // Only get IDs for performance
        ));

        if ($unassigned_tickets->have_posts()) {
            $count = $unassigned_tickets->found_posts;
            $link = admin_url('edit.php?post_type=kaveh_ticket&_kaveh_ticket_agent=unassigned'); // Custom filter link
            $message = sprintf(
                _n(
                    /* translators: 1: number of tickets, 2: link URL */
                    'There is %1$s unassigned support ticket. <a href="%2$s">View Ticket</a>',
                    'There are %1$s unassigned support tickets. <a href="%2$s">View Tickets</a>',
                    $count,
                    'kavehTheme'
                ),
                number_format_i18n($count),
                esc_url($link)
            );
            echo '<div class="notice notice-warning is-dismissible"><p>' . $message . '</p></div>';
        }
    }

    // --- AJAX Functions ---

    public function ajax_assign_agent() {
        if (!current_user_can('edit_posts')) { // Capability to edit tickets
            wp_send_json_error('Permission denied.');
        }

        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'kavehboard_assign_agent_nonce')) {
            wp_send_json_error('Nonce verification failed.');
        }

        $ticket_id = isset($_POST['ticket_id']) ? intval($_POST['ticket_id']) : 0;
        $agent_id = isset($_POST['agent_id']) ? intval($_POST['agent_id']) : 0;

        if (!$ticket_id) {
            wp_send_json_error('Invalid ticket ID.');
        }

        update_post_meta($ticket_id, '_kaveh_ticket_agent', $agent_id);
        wp_send_json_success('Agent assigned successfully.');
    }
}

?>