<?php

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

class Kavehboardticketsubmission {

    public function __construct() {
        add_shortcode('kaveh_submit_ticket', array($this, 'render_ticket_submission_form'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_ajax_kaveh_submit_ticket', array($this, 'handle_ticket_submission'));
        add_action('wp_ajax_nopriv_kaveh_submit_ticket', array($this, 'handle_ticket_submission'));
    }

    public function enqueue_scripts() {
        wp_enqueue_script('kaveh-ticket-submission', KAVEHBOARD_URL . 'assets/js/ticket-submission.js', array('jquery'), KAVEHBOARD_VERSION, true);
        wp_localize_script('kaveh-ticket-submission', 'kavehTicketAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('kaveh_submit_ticket_nonce')
        ));
    }

    public function render_ticket_submission_form($atts) {
        if (!is_user_logged_in()) {
            return '<p>' . __('Please log in to submit a support ticket.', 'kavehTheme') . '</p>';
        }

        ob_start();
        ?>
        <div class="kaveh-ticket-submission-form">
            <h3><?php _e('Submit a New Support Ticket', 'kavehTheme'); ?></h3>
            <form id="kaveh-ticket-form">
                <p>
                    <label for="ticket_title"><?php _e('Subject:', 'kavehTheme'); ?></label>
                    <input type="text" id="ticket_title" name="ticket_title" required>
                </p>
                <p>
                    <label for="ticket_department"><?php _e('Department:', 'kavehTheme'); ?></label>
                    <select id="ticket_department" name="ticket_department" required>
                        <option value=""><?php _e('Select a Department', 'kavehTheme'); ?></option>
                        <?php
                        $departments = get_terms(array('taxonomy' => 'kaveh_department', 'hide_empty' => false));
                        foreach ($departments as $department) {
                            echo '<option value="' . esc_attr($department->slug) . '">' . esc_html($department->name) . '</option>';
                        }
                        ?>
                    </select>
                </p>
                <p>
                    <label for="ticket_priority"><?php _e('Priority:', 'kavehTheme'); ?></label>
                    <select id="ticket_priority" name="ticket_priority">
                        <option value="normal"><?php _e('Normal', 'kavehTheme'); ?></option>
                        <option value="low"><?php _e('Low', 'kavehTheme'); ?></option>
                        <option value="high"><?php _e('High', 'kavehTheme'); ?></option>
                        <option value="urgent"><?php _e('Urgent', 'kavehTheme'); ?></option>
                    </select>
                </p>
                <p>
                    <label for="ticket_content"><?php _e('Message:', 'kavehTheme'); ?></label>
                    <textarea id="ticket_content" name="ticket_content" rows="8" required></textarea>
                </p>
                <p>
                    <label for="ticket_attachments"><?php _e('Attachments:', 'kavehTheme'); ?></label>
                    <input type="file" id="ticket_attachments" name="ticket_attachments[]" multiple accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.txt,.zip">
                    <small><?php _e('You can attach multiple files (max 5MB each). Allowed formats: JPG, PNG, GIF, PDF, DOC, DOCX, TXT, ZIP', 'kavehTheme'); ?></small>
                </p>
                <p>
                    <input type="submit" value="<?php _e('Submit Ticket', 'kavehTheme'); ?>">
                </p>
                <div id="kaveh-ticket-message"></div>
            </form>
        </div>
        <?php
        return ob_get_clean();
    }

    public function handle_ticket_submission() {
        check_ajax_referer('kaveh_submit_ticket_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => __('You must be logged in to submit a ticket.', 'kavehTheme')));
        }

        $title = sanitize_text_field($_POST['ticket_title']);
        $department_slug = sanitize_text_field($_POST['ticket_department']);
        $priority = sanitize_text_field($_POST['ticket_priority']);
        $content = wp_kses_post($_POST['ticket_content']);
        $user_id = get_current_user_id();

        if (empty($title) || empty($department_slug) || empty($content)) {
            wp_send_json_error(array('message' => __('Please fill in all required fields.', 'kavehTheme')));
        }

        // Create the ticket post
        $ticket_id = wp_insert_post(array(
            'post_title'    => $title,
            'post_content'  => $content,
            'post_status'   => 'publish',
            'post_type'     => 'kaveh_ticket',
            'post_author'   => $user_id,
        ));

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

        // Set department taxonomy
        wp_set_object_terms($ticket_id, $department_slug, 'kaveh_department');

        // Set priority meta
        update_post_meta($ticket_id, '_kaveh_ticket_priority', $priority);
        update_post_meta($ticket_id, '_kaveh_ticket_status', 'open');

        // Handle file attachments
        $this->handle_file_attachments($ticket_id);

        // Get default department from CSF options
        $kavehboard_options = get_option('kavehboard_options', array());
        $default_department = '';

        // Assign agent if department has agents
        $department_term = get_term_by('slug', $department_slug, 'kaveh_department');
        $assigned_agent_id = null;
        if ($department_term) {
            // Try new multiple agents system first
            $agent_ids = get_term_meta($department_term->term_id, 'department_agents', true);
            if (!empty($agent_ids) && is_array($agent_ids)) {
                // Randomly assign one of the available agents
                $random_agent_id = $agent_ids[array_rand($agent_ids)];
                update_post_meta($ticket_id, '_kaveh_ticket_agent', $random_agent_id);
                $assigned_agent_id = $random_agent_id;
            } else {
                // Fallback to old single agent system for backward compatibility
                $default_agent_id = get_term_meta($department_term->term_id, 'department_agent', true);
                if ($default_agent_id) {
                    update_post_meta($ticket_id, '_kaveh_ticket_agent', $default_agent_id);
                    $assigned_agent_id = $default_agent_id;
                }
            }
        }

        // Send email notifications if enabled
        $email_notifications_enabled = isset($kavehboard_options['kavehboard_ticket_email_notifications']) ? $kavehboard_options['kavehboard_ticket_email_notifications'] : false;
        if ($email_notifications_enabled) {
            $this->send_new_ticket_notification($ticket_id, $assigned_agent_id);
        }

        wp_send_json_success(array('message' => __('Your ticket has been submitted successfully! Ticket ID: #', 'kavehTheme') . $ticket_id));
    }

    private function send_new_ticket_notification($ticket_id, $assigned_agent_id = null) {
        $ticket = get_post($ticket_id);
        if (!$ticket) {
            return;
        }

        $customer = get_userdata($ticket->post_author);
        $department_terms = get_the_terms($ticket_id, 'kaveh_department');
        $department_name = !empty($department_terms) ? $department_terms[0]->name : __('General', 'kavehTheme');
        $priority = get_post_meta($ticket_id, '_kaveh_ticket_priority', true);
        
        $site_name = get_bloginfo('name');
        $ticket_url = home_url('/dashboard/?ticket=' . $ticket_id); // Adjust URL as needed
        
        // Email to customer (confirmation)
        /* translators: 1: site name, 2: ticket ID, 3: ticket subject */
        $customer_subject = sprintf(__('[%1$s] Ticket #%2$d Created - %3$s', 'kavehTheme'), $site_name, $ticket_id, $ticket->post_title);
        /* translators: 1: customer name, 2: ticket ID, 3: ticket subject, 4: department name, 5: priority, 6: ticket URL, 7: site name */
        $customer_message = sprintf(
            __('Dear %1$s,\n\nYour support ticket has been created successfully.\n\nTicket Details:\n- Ticket ID: #%2$d\n- Subject: %3$s\n- Department: %4$s\n- Priority: %5$s\n- Status: Open\n\nYou can view and manage your ticket at: %6$s\n\nWe will respond to your ticket as soon as possible.\n\nBest regards,\n%7$s Support Team', 'kavehTheme'),
            $customer->display_name,
            $ticket_id,
            $ticket->post_title,
            $department_name,
            __(ucfirst($priority), 'kavehTheme'),
            $ticket_url,
            $site_name
        );
        
        wp_mail($customer->user_email, $customer_subject, $customer_message);
        
        // Email to assigned agent (if any)
        if ($assigned_agent_id) {
            $agent = get_userdata($assigned_agent_id);
            if ($agent) {
                /* translators: 1: site name, 2: ticket ID, 3: ticket subject */
                $agent_subject = sprintf(__('[%1$s] New Ticket Assigned #%2$d - %3$s', 'kavehTheme'), $site_name, $ticket_id, $ticket->post_title);
                /* translators: 1: agent name, 2: ticket ID, 3: ticket subject, 4: customer name, 5: customer email, 6: department name, 7: priority, 8: ticket content, 9: ticket URL, 10: site name */
                $agent_message = sprintf(
                    __('Hello %1$s,\n\nA new support ticket has been assigned to you.\n\nTicket Details:\n- Ticket ID: #%2$d\n- Subject: %3$s\n- Customer: %4$s (%5$s)\n- Department: %6$s\n- Priority: %7$s\n- Status: Open\n\nTicket Content:\n%8$s\n\nYou can view and respond to this ticket at: %9$s\n\nBest regards,\n%10$s Support System', 'kavehTheme'),
                    $agent->display_name,
                    $ticket_id,
                    $ticket->post_title,
                    $customer->display_name,
                    $customer->user_email,
                    $department_name,
                    __(ucfirst($priority), 'kavehTheme'),
                    strip_tags($ticket->post_content),
                    $ticket_url,
                    $site_name
                );
                
                wp_mail($agent->user_email, $agent_subject, $agent_message);
            }
        }
    }

    /**
     * Handle file attachments for tickets
     */
    private function handle_file_attachments($ticket_id) {
        if (empty($_FILES['ticket_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();
        $ticket_upload_dir = $upload_dir['basedir'] . '/kaveh-tickets/' . $ticket_id;
        
        // Create directory if it doesn't exist
        if (!file_exists($ticket_upload_dir)) {
            wp_mkdir_p($ticket_upload_dir);
        }

        $attachment_ids = array();
        $files = $_FILES['ticket_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($ticket_upload_dir, $file_name);
            $file_path = $ticket_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' => $ticket_id,
                    'post_mime_type' => $file_type,
                ), $file_path, $ticket_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 ticket meta
        if (!empty($attachment_ids)) {
            update_post_meta($ticket_id, '_kaveh_ticket_attachments', $attachment_ids);
        }
    }
}

new Kavehboardticketsubmission();

?>