<?php

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

class Kavehboardticketdashboard {

    public function __construct() {
        add_shortcode('kaveh_user_tickets', array($this, 'render_user_tickets_dashboard'));
        add_action('wp_ajax_kaveh_get_ticket_messages', array($this, 'ajax_get_ticket_messages'));
        add_action('wp_ajax_nopriv_kaveh_get_ticket_messages', array($this, 'ajax_get_ticket_messages'));
        add_action('wp_ajax_kaveh_get_ticket_details', array($this, 'ajax_get_ticket_details'));
        add_action('wp_ajax_nopriv_kaveh_get_ticket_details', array($this, 'ajax_get_ticket_details'));
        add_action('wp_ajax_kaveh_add_ticket_message', array($this, 'ajax_add_ticket_message'));
        add_action('wp_ajax_nopriv_kaveh_add_ticket_message', array($this, 'ajax_add_ticket_message'));
        add_action('wp_ajax_kaveh_close_ticket', array($this, 'ajax_close_ticket'));
        add_action('wp_ajax_nopriv_kaveh_close_ticket', array($this, 'ajax_close_ticket'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_dashboard_scripts'));
    }

    public function enqueue_dashboard_scripts() {
        if (is_page(get_option('kavehboard_dashboard_page_id'))) { // Only enqueue on the dashboard page
            wp_enqueue_script('kaveh-ticket-dashboard', KAVEHBOARD_URL . 'assets/js/ticket-dashboard.js', array('jquery'), KAVEHBOARD_VERSION, true);
            wp_localize_script('kaveh-ticket-dashboard', 'kavehTicketDashboardAjax', array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('kaveh_ticket_dashboard_nonce')
            ));
            wp_enqueue_style('kaveh-ticket-dashboard-style', KAVEHBOARD_URL . 'assets/css/ticket-dashboard.css', array(), KAVEHBOARD_VERSION);
        }
    }

    /**
     * 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
    }

    /**
     * Get ticket IDs from departments where the user is assigned as an agent
     */
    private function get_department_tickets_for_user($user_id) {
        global $wpdb;
        
        // Get all departments and check their agents properly
        $all_departments = get_terms(array(
            'taxonomy' => 'kaveh_department',
            'hide_empty' => false
        ));
        
        $user_department_ids = array();
        
        foreach ($all_departments as $department) {
            $agents = get_term_meta($department->term_id, 'department_agents', true);
            if (is_array($agents) && in_array($user_id, $agents)) {
                $user_department_ids[] = $department->term_id;
            }
        }
        
        if (empty($user_department_ids)) {
            return array();
        }
        
        // Get all tickets from these departments
        $placeholders = implode(',', array_fill(0, count($user_department_ids), '%d'));
        $query = $wpdb->prepare(
            "SELECT DISTINCT p.ID FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
             INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
             WHERE p.post_type = 'kaveh_ticket'
             AND p.post_status = 'publish'
             AND tt.taxonomy = 'kaveh_department'
             AND tt.term_id IN ($placeholders)",
            ...$user_department_ids
        );
        
        return $wpdb->get_col($query);
    }

    /**
     * Check if a user can access a specific ticket
     */
    private function can_user_access_ticket($user_id, $ticket_id) {
        $ticket = get_post($ticket_id);
        if (!$ticket) {
            return false;
        }
        
        // Admin can access all tickets
        if (current_user_can('manage_options')) {
            return true;
        }
        
        // Ticket author can access their own tickets
        if ($ticket->post_author == $user_id) {
            return true;
        }
        
        // Check if user is directly assigned to this ticket
        $assigned_agent_id = get_post_meta($ticket_id, '_kaveh_ticket_agent', true);
        if ($assigned_agent_id == $user_id) {
            return true;
        }
        
        // Check if user is an agent in the ticket's department
        $ticket_departments = wp_get_post_terms($ticket_id, 'kaveh_department', array('fields' => 'ids'));
        if (!empty($ticket_departments)) {
            global $wpdb;
            foreach ($ticket_departments as $dept_id) {
                $agents = get_term_meta($dept_id, 'department_agents', true);
                if (is_array($agents) && in_array($user_id, $agents)) {
                    return true;
                }
            }
        }
        
        return false;
    }

    /**
     * Get HTML for displaying attachments
     */
    private function get_attachments_html($post_id) {
        $attachments = get_post_meta($post_id, '_kaveh_ticket_attachments', true);
        if (empty($attachments) || !is_array($attachments)) {
            return '';
        }

        $html = '<div class="kaveh-ticket-files" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">';
        $html .= '<strong style="display: block; margin-bottom: 8px; color: #333;">' . __('Attachments:', 'kavehTheme') . '</strong>';
        $html .= '<div class="kaveh-file-list" style="list-style: none; margin: 0; padding: 0;">';
        
        foreach ($attachments as $attachment_id) {
            $attachment = get_post($attachment_id);
            if ($attachment) {
                $file_url = wp_get_attachment_url($attachment_id);
                $file_name = $attachment->post_title;
                $file_size = size_format(filesize(get_attached_file($attachment_id)));
                
                $html .= '<div class="kaveh-file-item" style="margin-bottom: 5px; padding: 5px; background: white; border-radius: 3px;">';
                $html .= '<a href="' . esc_url($file_url) . '" target="_blank" rel="nofollow" data-elementor-open-lightbox="no" data-no-lightbox="true" class="kaveh-download-link" style="text-decoration: none; color: #0073aa; font-weight: 500;">' . esc_html($file_name) . '</a>';
                $html .= ' <span style="color: #666; font-size: 0.9em;">(' . $file_size . ')</span>';
                $html .= '</div>';
            }
        }
        
        $html .= '</div>';
        $html .= '</div>';
        
        return $html;
    }

    /**
     * Handle file attachments for ticket replies
     */
    private function handle_reply_attachments($message_id) {
        if (empty($_FILES['reply_attachments']['name'][0])) {
            return; // No files uploaded
        }

        $allowed_types = array(
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg', 
            'png' => 'image/png',
            'gif' => 'image/gif',
            'pdf' => 'application/pdf',
            'doc' => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'txt' => 'text/plain',
            'zip' => 'application/zip'
        );

        $max_file_size = 5 * 1024 * 1024; // 5MB
        $upload_dir = wp_upload_dir();
        $message_upload_dir = $upload_dir['basedir'] . '/kaveh-tickets/replies/' . $message_id;
        
        // Create directory if it doesn't exist
        if (!file_exists($message_upload_dir)) {
            wp_mkdir_p($message_upload_dir);
        }

        $attachment_ids = array();
        $files = $_FILES['reply_attachments'];
        
        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                continue;
            }

            $file_name = sanitize_file_name($files['name'][$i]);
            $file_size = $files['size'][$i];
            $file_tmp = $files['tmp_name'][$i];
            $file_type = $files['type'][$i];
            
            // Validate file size
            if ($file_size > $max_file_size) {
                continue;
            }

            // Validate file type
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            if (!array_key_exists($file_ext, $allowed_types) || $file_type !== $allowed_types[$file_ext]) {
                continue;
            }

            // Generate unique filename
            $unique_filename = wp_unique_filename($message_upload_dir, $file_name);
            $file_path = $message_upload_dir . '/' . $unique_filename;
            
            // Move uploaded file
            if (move_uploaded_file($file_tmp, $file_path)) {
                // Create attachment post
                $attachment_id = wp_insert_attachment(array(
                    'post_title' => $file_name,
                    'post_content' => '',
                    'post_status' => 'inherit',
                    'post_parent' => $message_id,
                    'post_mime_type' => $file_type,
                ), $file_path, $message_id);
                
                if (!is_wp_error($attachment_id)) {
                    $attachment_ids[] = $attachment_id;
                    // Add custom meta to identify ticket attachments
                    update_post_meta($attachment_id, '_kaveh_ticket_attachment', true);
                }
            }
        }
        
        // Store attachment IDs in message meta
        if (!empty($attachment_ids)) {
            update_post_meta($message_id, '_kaveh_ticket_attachments', $attachment_ids);
        }
    }

    public function render_user_tickets_dashboard($atts) {
        if (!is_user_logged_in()) {
            return '<p>' . __('Please log in to view your support tickets.', 'kavehTheme') . '</p>';
        }

        $user_id = get_current_user_id();
        $is_agent = current_user_can('manage_options') || $this->is_user_support_agent($user_id);

        ob_start();
        
        // Get ticket statistics
        $stats_args = array(
            'post_type'      => 'kaveh_ticket',
            'posts_per_page' => -1,
            'post_status'    => array('publish'),
            'author'         => $user_id,
        );
        
        if ($is_agent) {
            global $wpdb;
            
            // Get tickets assigned directly to the user OR tickets from departments where user is an agent
            $department_ticket_ids = $this->get_department_tickets_for_user($user_id);
            
            $ticket_ids = $wpdb->get_col($wpdb->prepare(
                "SELECT DISTINCT p.ID FROM {$wpdb->posts} p 
                 LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_kaveh_ticket_agent'
                 WHERE p.post_type = 'kaveh_ticket' 
                 AND p.post_status = 'publish'
                 AND (p.post_author = %d OR pm.meta_value = %d)",
                $user_id, $user_id
            ));
            
            // Merge directly assigned tickets with department tickets
            $all_ticket_ids = array_unique(array_merge($ticket_ids, $department_ticket_ids));
            
            if (!empty($all_ticket_ids)) {
                $stats_args['post__in'] = $all_ticket_ids;
                unset($stats_args['author']);
            } else {
                $stats_args['post__in'] = array(0);
            }
        }
        
        $stats_query = new WP_Query($stats_args);
        $total_tickets = $stats_query->found_posts;
        
        // Count tickets by status
        $status_counts = array(
            'open' => 0,
            'replied' => 0,
            'closed' => 0
        );
        
        // Count tickets by priority
        $priority_counts = array(
            'low' => 0,
            'medium' => 0,
            'high' => 0,
            'urgent' => 0
        );
        
        if ($stats_query->have_posts()) {
            while ($stats_query->have_posts()) {
                $stats_query->the_post();
                $ticket_id = get_the_ID();
                $status = get_post_meta($ticket_id, '_kaveh_ticket_status', true) ?: 'open';
                $priority = get_post_meta($ticket_id, '_kaveh_ticket_priority', true) ?: 'medium';
                
                if (isset($status_counts[$status])) {
                    $status_counts[$status]++;
                }
                
                if (isset($priority_counts[$priority])) {
                    $priority_counts[$priority]++;
                }
            }
            wp_reset_postdata();
        }
        
        ?>
        <div class="kaveh-ticket-dashboard">
            <!-- Ticket List View -->
            <div class="ticket-list-view">
                <h3><?php _e('Your Support Tickets', 'kavehTheme'); ?></h3>
                
                <!-- Dashboard Statistics -->
                <div class="ticket-dashboard-stats">
                <div class="stats-overview">
                    <div class="stat-card total-tickets">
                     
                        <div class="stat-number"><?php echo $total_tickets; ?></div>
                        <div class="stat-label"><?php _e('Total Tickets', 'kavehTheme'); ?></div>
                           <div>
                            <i class="isax isax-ticket-24" style="font-size: 40px;margin-top: 12px;"></i>
                        </div>
                        
                    </div>
                    <div class="stat-card open-tickets">
                        <div class="stat-number"><?php echo $status_counts['open']; ?></div>
                        <div class="stat-label"><?php _e('Open', 'kavehTheme'); ?></div>
                          <div>
                            <i class="isax isax-ticket-24" style="font-size: 40px;margin-top: 12px;"></i>
                        </div>
                    </div>
                    <div class="stat-card replied-tickets">
                        <div class="stat-number"><?php echo $status_counts['replied']; ?></div>
                        <div class="stat-label"><?php _e('Replied', 'kavehTheme'); ?></div>
                           <div>
                            <i class="isax isax-ticket-24" style="font-size: 40px;margin-top: 12px;"></i>
                        </div>
                    </div>
                    <div class="stat-card closed-tickets">
                        <div class="stat-number"><?php echo $status_counts['closed']; ?></div>
                        <div class="stat-label"><?php _e('Closed', 'kavehTheme'); ?></div>
                           <div>
                            <i class="isax isax-ticket-24" style="font-size: 40px;margin-top: 12px;"></i>
                        </div>
                    </div>
                </div>
                
                <div class="priority-breakdown">
                    <h4><?php _e('Priority Breakdown', 'kavehTheme'); ?></h4>
                    <div class="priority-stats">
                        <div class="priority-item urgent">
                            <span class="priority-label"><?php _e('Urgent', 'kavehTheme'); ?></span>
                            <span class="priority-count"><?php echo $priority_counts['urgent']; ?></span>
                        </div>
                        <div class="priority-item high">
                            <span class="priority-label"><?php _e('High', 'kavehTheme'); ?></span>
                            <span class="priority-count"><?php echo $priority_counts['high']; ?></span>
                        </div>
                        <div class="priority-item medium">
                            <span class="priority-label"><?php _e('Medium', 'kavehTheme'); ?></span>
                            <span class="priority-count"><?php echo $priority_counts['medium']; ?></span>
                        </div>
                        <div class="priority-item low">
                            <span class="priority-label"><?php _e('Low', 'kavehTheme'); ?></span>
                            <span class="priority-count"><?php echo $priority_counts['low']; ?></span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Filter Options -->
            <div class="ticket-filters">
                <div class="filter-group">
                    <label for="status-filter"><?php _e('Filter by Status:', 'kavehTheme'); ?></label>
                    <select id="status-filter" class="ticket-filter">
                        <option value="all"><?php _e('All Statuses', 'kavehTheme'); ?></option>
                        <option value="open"><?php _e('Open', 'kavehTheme'); ?></option>
                        <option value="replied"><?php _e('Replied', 'kavehTheme'); ?></option>
                        <option value="closed"><?php _e('Closed', 'kavehTheme'); ?></option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label for="priority-filter"><?php _e('Filter by Priority:', 'kavehTheme'); ?></label>
                    <select id="priority-filter" class="ticket-filter">
                        <option value="all"><?php _e('All Priorities', 'kavehTheme'); ?></option>
                        <option value="urgent"><?php _e('Urgent', 'kavehTheme'); ?></option>
                        <option value="high"><?php _e('High', 'kavehTheme'); ?></option>
                        <option value="medium"><?php _e('Medium', 'kavehTheme'); ?></option>
                        <option value="low"><?php _e('Low', 'kavehTheme'); ?></option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <button id="clear-filters" class="button"><?php _e('Clear Filters', 'kavehTheme'); ?></button>
                </div>
            </div>
            
            <div class="ticket-list">
                <?php
                $args = array(
                    'post_type'      => 'kaveh_ticket',
                    'posts_per_page' => -1,
                    'post_status'    => array('publish'),
                    'author'         => $user_id,
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                );

                // If user is an agent, show tickets they created, assigned to them, and from their departments
                if ($is_agent) {
                    global $wpdb;
                    
                    // Get tickets assigned directly to the user
                    $direct_ticket_ids = $wpdb->get_col($wpdb->prepare(
                        "SELECT DISTINCT p.ID FROM {$wpdb->posts} p 
                         LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_kaveh_ticket_agent'
                         WHERE p.post_type = 'kaveh_ticket' 
                         AND p.post_status = 'publish'
                         AND (p.post_author = %d OR pm.meta_value = %d)",
                        $user_id, $user_id
                    ));
                    
                    // Get tickets from departments where user is an agent
                    $department_ticket_ids = $this->get_department_tickets_for_user($user_id);
                    
                    // Merge all ticket IDs
                    $all_ticket_ids = array_unique(array_merge($direct_ticket_ids, $department_ticket_ids));
                    
                    if (!empty($all_ticket_ids)) {
                        $args = array(
                            'post_type'      => 'kaveh_ticket',
                            'posts_per_page' => -1,
                            'post_status'    => array('publish'),
                            'post__in'       => $all_ticket_ids,
                            'orderby'        => 'date',
                            'order'          => 'DESC',
                        );
                    } else {
                        // No tickets found, set empty query
                        $args['post__in'] = array(0);
                    }
                }

                $tickets_query = new WP_Query($args);

                if ($tickets_query->have_posts()) {
                    while ($tickets_query->have_posts()) {
                        $tickets_query->the_post();
                        $ticket_id = get_the_ID();
                        $status = get_post_meta($ticket_id, '_kaveh_ticket_status', true);
                        $priority = get_post_meta($ticket_id, '_kaveh_ticket_priority', true);
                        $department_terms = get_the_terms($ticket_id, 'kaveh_department');
                        $department_name = !empty($department_terms) ? $department_terms[0]->name : __('N/A', 'kavehTheme');
                        ?>
                        <div class="ticket-item <?php echo esc_attr($status); ?>" data-ticket-id="<?php echo esc_attr($ticket_id); ?>">
                            <div class="ticket-header">
                                <span class="ticket-title">#<?php echo esc_html($ticket_id); ?> - <?php the_title(); ?></span>
                                <span class="ticket-status status-<?php echo esc_attr($status); ?>"><?php echo esc_html(__(ucfirst($status), 'kavehTheme')); ?></span>
                                <span class="ticket-priority priority-<?php echo esc_attr($priority); ?>"><?php echo esc_html(__(ucfirst($priority), 'kavehTheme')); ?></span>
                                <span class="ticket-department"><?php echo esc_html($department_name); ?></span>
                                <span class="ticket-date"><?php echo get_the_date(); ?></span>
                            </div>
                            <div class="ticket-content" style="display:none;">
                                <div class="ticket-messages"></div>
                                <div class="ticket-reply-form">
                                    <textarea class="ticket-reply-message" placeholder="<?php _e('Type your reply here...', 'kavehTheme'); ?>"></textarea>
                                    <div class="reply-attachments">
                                        <label for="reply_attachments_<?php echo esc_attr($ticket_id); ?>"><?php _e('Attachments:', 'kavehTheme'); ?></label>
                                        <input type="file" id="reply_attachments_<?php echo esc_attr($ticket_id); ?>" class="reply-attachments-input" multiple accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.txt,.zip">
                                        <small><?php _e('Max 5MB each. Formats: JPG, PNG, GIF, PDF, DOC, DOCX, TXT, ZIP', 'kavehTheme'); ?></small>
                                    </div>
                                    <button class="button kaveh-add-message" data-ticket-id="<?php echo esc_attr($ticket_id); ?>"><?php _e('Add Reply', 'kavehTheme'); ?></button>
                                    <?php if ($status !== 'closed') { ?>
                                        <button class="button kaveh-close-ticket" data-ticket-id="<?php echo esc_attr($ticket_id); ?>"><?php _e('Close Ticket', 'kavehTheme'); ?></button>
                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                        <?php
                    }
                    wp_reset_postdata();
                } else {
                    echo '<p>' . __('No support tickets found.', 'kavehTheme') . '</p>';
                }
                ?>
                </div>
            </div>
            
            <!-- Ticket Detail View -->
            <div class="ticket-detail-view" style="display: none;">
                <div class="ticket-detail-header">
                    <button class="back-to-list-btn" style="margin-bottom: 15px; padding: 8px 16px; background: #0073aa; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        ← <?php _e('Back to Tickets', 'kavehTheme'); ?>
                    </button>
                    <h3 class="ticket-detail-title"></h3>
                </div>
                <div class="ticket-detail-content">
                    <div class="ticket-detail-info"></div>
                    <div class="ticket-detail-messages"></div>
                    <div class="ticket-detail-reply-form"></div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    public function ajax_get_ticket_messages() {
        check_ajax_referer('kaveh_ticket_dashboard_nonce', 'nonce');

        $ticket_id = intval($_POST['ticket_id']);
        if (!$ticket_id) {
            wp_send_json_error(array('message' => __('Invalid ticket ID.', 'kavehTheme')));
        }

        $ticket = get_post($ticket_id);
        if (!$ticket || $ticket->post_type !== 'kaveh_ticket') {
            wp_send_json_error(array('message' => __('Ticket not found.', 'kavehTheme')));
        }

        // Check if current user can access this ticket
        $user_id = get_current_user_id();
        if (!$this->can_user_access_ticket($user_id, $ticket_id)) {
            wp_send_json_error(array('message' => __('You do not have permission to view this ticket.', 'kavehTheme')));
        }

        $messages_query = new WP_Query(array(
            'post_type'      => 'kaveh_ticket_message',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'meta_query'     => array(
                array(
                    'key'     => '_kaveh_ticket_id',
                    'value'   => $ticket_id,
                    'compare' => '='
                )
            ),
            'orderby'        => 'date',
            'order'          => 'ASC'
        ));

        $messages_html = '';
        // Display initial ticket content as the first message
        $author_name = get_the_author_meta('display_name', $ticket->post_author);
        $messages_html .= '<div class="ticket-message original-ticket">';
        $messages_html .= '<div class="message-author">' . esc_html($author_name) . '</div>';
        $messages_html .= '<div class="message-date">' . get_the_date('', $ticket) . '</div>';
        $messages_html .= '<div class="message-content">' . wpautop(wp_kses_post($ticket->post_content)) . '</div>';
        // Display ticket attachments
        $messages_html .= $this->get_attachments_html($ticket_id);
        $messages_html .= '</div>';

        if ($messages_query->have_posts()) {
            while ($messages_query->have_posts()) {
                $messages_query->the_post();
                $message_author_id = get_the_author_meta('ID');
                $message_author_name = get_the_author_meta('display_name', $message_author_id);
                $messages_html .= '<div class="ticket-message">';
                $messages_html .= '<div class="message-author">' . esc_html($message_author_name) . '</div>';
                $messages_html .= '<div class="message-date">' . get_the_date() . '</div>';
                $messages_html .= '<div class="message-content">' . wpautop(wp_kses_post(get_the_content())) . '</div>';
                // Display message attachments
                $messages_html .= $this->get_attachments_html(get_the_ID());
                $messages_html .= '</div>';
            }
            wp_reset_postdata();
        }

        wp_send_json_success(array('messages_html' => $messages_html));
    }

    public function ajax_get_ticket_details() {
        check_ajax_referer('kaveh_ticket_dashboard_nonce', 'nonce');

        $ticket_id = intval($_POST['ticket_id']);
        if (!$ticket_id) {
            wp_send_json_error(array('message' => __('Invalid ticket ID.', 'kavehTheme')));
        }

        $ticket = get_post($ticket_id);
        if (!$ticket || $ticket->post_type !== 'kaveh_ticket') {
            wp_send_json_error(array('message' => __('Ticket not found.', 'kavehTheme')));
        }

        // Check if current user can access this ticket
        $user_id = get_current_user_id();
        if (!$this->can_user_access_ticket($user_id, $ticket_id)) {
            wp_send_json_error(array('message' => __('You do not have permission to view this ticket.', 'kavehTheme')));
        }

        // Get ticket info
        $status = get_post_meta($ticket_id, '_kaveh_ticket_status', true);
        $priority = get_post_meta($ticket_id, '_kaveh_ticket_priority', true);
        $department_terms = get_the_terms($ticket_id, 'kaveh_department');
        $department_name = !empty($department_terms) ? $department_terms[0]->name : __('N/A', 'kavehTheme');
        $author_name = get_the_author_meta('display_name', $ticket->post_author);
        
        // Build ticket info HTML
        $info_html = '<div class="ticket-info-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; padding: 15px; background: #f9f9f9; border-radius: 5px;">';
        $info_html .= '<div><strong>' . __('Status:', 'kavehTheme') . '</strong> <span class="status-' . esc_attr($status) . '">' . esc_html(__(ucfirst($status), 'kavehTheme')) . '</span></div>';
        $info_html .= '<div><strong>' . __('Priority:', 'kavehTheme') . '</strong> <span class="priority-' . esc_attr($priority) . '">' . esc_html(__(ucfirst($priority), 'kavehTheme')) . '</span></div>';
        $info_html .= '<div><strong>' . __('Department:', 'kavehTheme') . '</strong> ' . esc_html($department_name) . '</div>';
        $info_html .= '<div><strong>' . __('Created by:', 'kavehTheme') . '</strong> ' . esc_html($author_name) . '</div>';
        $info_html .= '<div><strong>' . __('Date:', 'kavehTheme') . '</strong> ' . get_the_date('', $ticket) . '</div>';
        $info_html .= '</div>';

        // Get messages
        $messages_query = new WP_Query(array(
            'post_type'      => 'kaveh_ticket_message',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'meta_query'     => array(
                array(
                    'key'     => '_kaveh_ticket_id',
                    'value'   => $ticket_id,
                    'compare' => '='
                )
            ),
            'orderby'        => 'date',
            'order'          => 'ASC'
        ));

        $messages_html = '';
        // Display initial ticket content as the first message
        $author_name = get_the_author_meta('display_name', $ticket->post_author);
        $messages_html .= '<div class="ticket-message original-ticket" style="margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #fff;">';
        $messages_html .= '<div class="message-author" style="font-weight: bold; color: #333;">' . esc_html($author_name) . '</div>';
        $messages_html .= '<div class="message-date" style="color: #666; font-size: 0.9em; margin-bottom: 10px;">' . get_the_date('', $ticket) . '</div>';
        $messages_html .= '<div class="message-content">' . wpautop(wp_kses_post($ticket->post_content)) . '</div>';
        // Display ticket attachments
        $messages_html .= $this->get_attachments_html($ticket_id);
        $messages_html .= '</div>';

        if ($messages_query->have_posts()) {
            while ($messages_query->have_posts()) {
                $messages_query->the_post();
                $message_author_id = get_the_author_meta('ID');
                $message_author_name = get_the_author_meta('display_name', $message_author_id);
                $messages_html .= '<div class="ticket-message" style="margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #fff;">';
                $messages_html .= '<div class="message-author" style="font-weight: bold; color: #333;">' . esc_html($message_author_name) . '</div>';
                $messages_html .= '<div class="message-date" style="color: #666; font-size: 0.9em; margin-bottom: 10px;">' . get_the_date() . '</div>';
                $messages_html .= '<div class="message-content">' . wpautop(wp_kses_post(get_the_content())) . '</div>';
                // Display message attachments
                $messages_html .= $this->get_attachments_html(get_the_ID());
                $messages_html .= '</div>';
            }
            wp_reset_postdata();
        }

        // Build reply form HTML
        $reply_form_html = '<div class="ticket-reply-form" style="margin-top: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;">';
        $reply_form_html .= '<h4>' . __('Add Reply', 'kavehTheme') . '</h4>';
        $reply_form_html .= '<textarea class="ticket-reply-message" placeholder="' . __('Type your reply here...', 'kavehTheme') . '" style="width: 100%; min-height: 100px; margin-bottom: 10px; padding: 10px; border: 1px solid #ccc; border-radius: 4px;"></textarea>';
        $reply_form_html .= '<div class="reply-attachments" style="margin-bottom: 15px;">';
        $reply_form_html .= '<label for="reply_attachments_' . $ticket_id . '">' . __('Attachments:', 'kavehTheme') . '</label>';
        $reply_form_html .= '<input type="file" id="reply_attachments_' . $ticket_id . '" class="reply-attachments-input" multiple accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.txt,.zip" style="display: block; margin-top: 5px;">';
        $reply_form_html .= '<small style="color: #666;">' . __('Max 5MB each. Formats: JPG, PNG, GIF, PDF, DOC, DOCX, TXT, ZIP', 'kavehTheme') . '</small>';
        $reply_form_html .= '</div>';
        $reply_form_html .= '<div class="reply-form-buttons">';
        $reply_form_html .= '<button class="button kaveh-add-message" data-ticket-id="' . $ticket_id . '" style="margin-right: 10px; padding: 10px 20px; background: #0073aa; color: white; border: none; border-radius: 4px; cursor: pointer;">' . __('Add Reply', 'kavehTheme') . '</button>';
        if ($status !== 'closed') {
            $reply_form_html .= '<button class="button kaveh-close-ticket" data-ticket-id="' . $ticket_id . '" style="padding: 10px 20px; background: #dc3232; color: white; border: none; border-radius: 4px; cursor: pointer;">' . __('Close Ticket', 'kavehTheme') . '</button>';
        }
        $reply_form_html .= '</div>';
        $reply_form_html .= '</div>';

        wp_send_json_success(array(
            'title' => '#' . $ticket_id . ' - ' . $ticket->post_title,
            'info_html' => $info_html,
            'messages_html' => $messages_html,
            'reply_form_html' => $reply_form_html
        ));
    }

    public function ajax_add_ticket_message() {
        check_ajax_referer('kaveh_ticket_dashboard_nonce', 'nonce');

        $ticket_id = intval($_POST['ticket_id']);
        $message_content = wp_kses_post($_POST['message_content']);
        $user_id = get_current_user_id();

        if (!$ticket_id || empty($message_content)) {
            wp_send_json_error(array('message' => __('Invalid data provided.', 'kavehTheme')));
        }

        $ticket = get_post($ticket_id);
        if (!$ticket || $ticket->post_type !== 'kaveh_ticket') {
            wp_send_json_error(array('message' => __('Ticket not found.', 'kavehTheme')));
        }

        // Check if current user can access this ticket
        if (!$this->can_user_access_ticket($user_id, $ticket_id)) {
            wp_send_json_error(array('message' => __('You do not have permission to reply to this ticket.', 'kavehTheme')));
        }

        // Create the message post
        $message_id = wp_insert_post(array(
            'post_title'    => 'Message for Ticket #' . $ticket_id,
            'post_content'  => $message_content,
            'post_status'   => 'publish',
            'post_type'     => 'kaveh_ticket_message',
            'post_author'   => $user_id,
        ));

        if (is_wp_error($message_id)) {
            wp_send_json_error(array('message' => __('Error adding message: ', 'kavehTheme') . $message_id->get_error_message()));
        }

        // Link message to ticket
        update_post_meta($message_id, '_kaveh_ticket_id', $ticket_id);

        // Handle file attachments for the reply
        $this->handle_reply_attachments($message_id);

        // Determine if this is an agent reply (not the ticket author)
        $is_agent_reply = ($ticket->post_author != $user_id);
        
        // Update ticket status to 'replied' if it was 'open' and agent replied
        if ($ticket->post_status === 'publish' && $is_agent_reply) {
            update_post_meta($ticket_id, '_kaveh_ticket_status', 'replied');
        }

        // Send email notification for reply
        $kavehboard_options = get_option('kavehboard_options', array());
        $email_notifications_enabled = isset($kavehboard_options['kavehboard_ticket_email_notifications']) ? $kavehboard_options['kavehboard_ticket_email_notifications'] : false;
        if ($email_notifications_enabled && $message_id) {
            $this->send_reply_notification($ticket_id, $message_id, $user_id, $is_agent_reply);
        }

        wp_send_json_success(array('message' => __('Message added successfully.', 'kavehTheme')));
    }

    public function ajax_close_ticket() {
        check_ajax_referer('kaveh_ticket_dashboard_nonce', 'nonce');

        $ticket_id = intval($_POST['ticket_id']);
        if (!$ticket_id) {
            wp_send_json_error(array('message' => __('Invalid ticket ID.', 'kavehTheme')));
        }

        $ticket = get_post($ticket_id);
        if (!$ticket || $ticket->post_type !== 'kaveh_ticket') {
            wp_send_json_error(array('message' => __('Ticket not found.', 'kavehTheme')));
        }

        // Check if current user can access this ticket
        $user_id = get_current_user_id();
        if (!$this->can_user_access_ticket($user_id, $ticket_id)) {
            wp_send_json_error(array('message' => __('You do not have permission to close this ticket.', 'kavehTheme')));
        }

        update_post_meta($ticket_id, '_kaveh_ticket_status', 'closed');
        
        // Send email notification for ticket closure
        $kavehboard_options = get_option('kavehboard_options', array());
        $email_notifications_enabled = isset($kavehboard_options['kavehboard_ticket_email_notifications']) ? $kavehboard_options['kavehboard_ticket_email_notifications'] : false;
        if ($email_notifications_enabled) {
            $this->send_closure_notification($ticket_id, $user_id);
        }
        
        wp_send_json_success(array('message' => __('Ticket closed successfully.', 'kavehTheme')));
    }

    private function send_reply_notification($ticket_id, $message_id, $reply_author_id, $is_agent_reply) {
        $ticket = get_post($ticket_id);
        $message = get_post($message_id);
        if (!$ticket || !$message) {
            return;
        }

        $site_name = get_bloginfo('name');
        $ticket_url = home_url('/dashboard/?ticket=' . $ticket_id);
        $reply_author = get_userdata($reply_author_id);
        $customer = get_userdata($ticket->post_author);
        $assigned_agent_id = get_post_meta($ticket_id, '_kaveh_ticket_agent', true);
        
        if ($is_agent_reply) {
            // Agent replied - notify customer
            $subject = sprintf(__(/* translators: 1: site name, 2: ticket ID, 3: ticket subject */ '[%1$s] Reply to Ticket #%2$d - %3$s', 'kavehTheme'), $site_name, $ticket_id, $ticket->post_title);
            $email_message = sprintf(
                __(/* translators: 1: customer name, 2: ticket ID, 3: ticket subject, 4: reply author name, 5: reply content, 6: ticket URL, 7: site name */ 'Dear %1$s,\n\nYou have received a new reply to your support ticket.\n\nTicket Details:\n- Ticket ID: #%2$d\n- Subject: %3$s\n- Reply from: %4$s\n\nReply:\n%5$s\n\nYou can view the full conversation at: %6$s\n\nBest regards,\n%7$s Support Team', 'kavehTheme'),
                $customer->display_name,
                $ticket_id,
                $ticket->post_title,
                $reply_author->display_name,
                strip_tags($message->post_content),
                $ticket_url,
                $site_name
            );
            
            wp_mail($customer->user_email, $subject, $email_message);
        } else {
            // Customer replied - notify assigned agent
            if ($assigned_agent_id) {
                $agent = get_userdata($assigned_agent_id);
                if ($agent) {
                    $subject = sprintf(__(/* translators: 1: site name, 2: ticket ID, 3: ticket subject */ '[%1$s] Customer Reply to Ticket #%2$d - %3$s', 'kavehTheme'), $site_name, $ticket_id, $ticket->post_title);
                    $email_message = sprintf(
                        __(/* translators: 1: agent name, 2: ticket ID, 3: ticket ID (duplicate), 4: ticket subject, 5: customer name, 6: customer email, 7: reply content, 8: ticket URL, 9: site name */ 'Hello %1$s,\n\nThe customer has replied to ticket #%2$d.\n\nTicket Details:\n- Ticket ID: #%3$d\n- Subject: %4$s\n- Customer: %5$s (%6$s)\n\nCustomer Reply:\n%7$s\n\nYou can view and respond to this ticket at: %8$s\n\nBest regards,\n%9$s Support System', 'kavehTheme'),
                        $agent->display_name,
                        $ticket_id,
                        $ticket_id,
                        $ticket->post_title,
                        $customer->display_name,
                        $customer->user_email,
                        strip_tags($message->post_content),
                        $ticket_url,
                        $site_name
                    );
                    
                    wp_mail($agent->user_email, $subject, $email_message);
                }
            }
        }
    }

    private function send_closure_notification($ticket_id, $closed_by_user_id) {
        $ticket = get_post($ticket_id);
        if (!$ticket) {
            return;
        }

        $site_name = get_bloginfo('name');
        $ticket_url = home_url('/dashboard/?ticket=' . $ticket_id);
        $closed_by = get_userdata($closed_by_user_id);
        $customer = get_userdata($ticket->post_author);
        $assigned_agent_id = get_post_meta($ticket_id, '_kaveh_ticket_agent', true);
        
        // Notify customer
        $customer_subject = sprintf(__(/* translators: 1: site name, 2: ticket ID, 3: ticket subject */ '[%1$s] Ticket #%2$d Closed - %3$s', 'kavehTheme'), $site_name, $ticket_id, $ticket->post_title);
        $customer_message = sprintf(
            __(/* translators: 1: customer name, 2: ticket ID, 3: ticket subject, 4: closed by user name, 5: ticket URL, 6: site name */ 'Dear %1$s,\n\nYour support ticket has been closed.\n\nTicket Details:\n- Ticket ID: #%2$d\n- Subject: %3$s\n- Closed by: %4$s\n- Status: Closed\n\nIf you need further assistance, please create a new ticket.\n\nYou can view the ticket history at: %5$s\n\nBest regards,\n%6$s Support Team', 'kavehTheme'),
            $customer->display_name,
            $ticket_id,
            $ticket->post_title,
            $closed_by->display_name,
            $ticket_url,
            $site_name
        );
        
        wp_mail($customer->user_email, $customer_subject, $customer_message);
        
        // Notify assigned agent if customer closed the ticket
        if ($assigned_agent_id && $closed_by_user_id != $assigned_agent_id) {
            $agent = get_userdata($assigned_agent_id);
            if ($agent) {
                $agent_subject = sprintf(__(/* translators: 1: site name, 2: ticket ID, 3: ticket subject */ '[%1$s] Ticket #%2$d Closed by Customer - %3$s', 'kavehTheme'), $site_name, $ticket_id, $ticket->post_title);
                $agent_message = sprintf(
                    __(/* translators: 1: agent name, 2: ticket ID, 3: ticket ID (duplicate), 4: ticket subject, 5: customer name, 6: customer email, 7: ticket URL, 8: site name */ 'Hello %1$s,\n\nTicket #%2$d has been closed by the customer.\n\nTicket Details:\n- Ticket ID: #%3$d\n- Subject: %4$s\n- Customer: %5$s (%6$s)\n- Status: Closed\n\nYou can view the ticket history at: %7$s\n\nBest regards,\n%8$s Support System', 'kavehTheme'),
                    $agent->display_name,
                    $ticket_id,
                    $ticket_id,
                    $ticket->post_title,
                    $customer->display_name,
                    $customer->user_email,
                    $ticket_url,
                    $site_name
                );
                
                wp_mail($agent->user_email, $agent_subject, $agent_message);
            }
        }
    }
}

new Kavehboardticketdashboard();

?>