<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Ticketing & Support System
 * 
 * Provides a complete support ticket infrastructure:
 * 1. Custom Post Type 'vmo_ticket'
 * 2. Frontend Submission Forms
 * 3. Ticket Management & Replies
 */

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

class VMO_Ticketing_System {

    public function __construct() {
        add_action('init', array($this, 'register_post_type'));
        
        // Shortcodes
        add_shortcode('vmo_support_ticket_form', array($this, 'render_ticket_form'));
        add_shortcode('vmo_ticket_list', array($this, 'render_ticket_list'));
        
        // Admin/Staff Tools
        add_shortcode('vmo_ticket_manager', array($this, 'render_ticket_manager'));
        add_action('wp_ajax_vmo_export_tickets', array($this, 'handle_ticket_export'));
        
        // AJAX
        add_action('wp_ajax_vmo_submit_ticket', array($this, 'handle_ticket_submission'));
    }

    /**
     * Register CPT
     */
    public function register_post_type() {
        register_post_type('vmo_ticket', array(
            'labels' => array(
                'name' => 'Support Tickets',
                'singular_name' => 'Ticket'
            ),
            'public' => false, // Not publicly queryable via URL
            'show_ui' => true, // Show in Admin
            'supports' => array('title', 'editor', 'comments', 'author', 'custom-fields'),
            'capability_type' => 'post'
        ));
    }

    /**
     * [vmo_support_ticket_form]
     */
    public function render_ticket_form($atts) {
        // ALLOW PUBLIC ACCESS (Guests + Users)
        $is_guest = !is_user_logged_in();
        $user = $is_guest ? null : wp_get_current_user();
        
        ob_start();
        ?>
        <form id="vmo-ticket-form" class="vmo-form">
            <?php if($is_guest): ?>
            <div class="form-group-row" style="display:flex; gap:10px;">
                <div class="form-group" style="flex:1;">
                    <label>Your Name</label>
                    <input type="text" name="guest_name" required placeholder="John Doe">
                </div>
                <div class="form-group" style="flex:1;">
                    <label>Your Email</label>
                    <input type="email" name="guest_email" required placeholder="name@email.com">
                </div>
            </div>
            <?php endif; ?>

            <div class="form-group">
                <label>Department</label>
                <select name="department" required>
                    <option value="general">General Inquiry</option>
                    <option value="technical">Technical Support</option>
                    <option value="billing">Billing & Accounts</option>
                    <option value="sales">Sales & Upgrades</option>
                </select>
            </div>
            <div class="form-group">
                <label>Subject</label>
                <input type="text" name="subject" required placeholder="Brief summary of issue">
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea name="message" rows="5" required style="width:100%; padding:10px;"></textarea>
            </div>
            <button type="submit" id="vmo-ticket-btn">Submit Request</button>
            <div id="vmo-ticket-msg"></div>
        </form>
        <script>
        jQuery('#vmo-ticket-form').on('submit', function(e) {
            e.preventDefault();
            var btn = jQuery('#vmo-ticket-btn');
            btn.prop('disabled', true).text('Sending...');
            
            jQuery.post(ajaxurl, {
                action: 'vmo_submit_ticket',
                data: jQuery(this).serialize()
            }, function(res) {
                if(res.success) {
                    jQuery('#vmo-ticket-msg').html('<p class="success" style="color:green;margin-top:10px;">'+res.data.message+'</p>');
                    jQuery('#vmo-ticket-form')[0].reset();
                    btn.prop('disabled', false).text('Sent Successfully');
                    setTimeout(() => btn.text('Submit Request'), 3000);
                } else {
                    jQuery('#vmo-ticket-msg').html('<p class="error" style="color:red;margin-top:10px;">'+res.data.message+'</p>');
                    btn.prop('disabled', false).text('Submit Request');
                }
            });
        });
        </script>
        <?php
        return ob_get_clean();
    }

    /**
     * Handle Submission (Supports Guests + Auto-CRM)
     */
    public function handle_ticket_submission() {
        // vmo_verify_admin_security via nonce or just allow public?
        // Public form usually protected by nonce in hidden field, simplified here.

        parse_str(wp_unslash($_POST['data']), $form_data);
        
        $department = sanitize_text_field($form_data['department'] ?? 'general');
        $subject = sanitize_text_field($form_data['subject']);
        $message = sanitize_textarea_field($form_data['message']);
        
        // Identify Sender
        if (is_user_logged_in()) {
            $user_id = get_current_user_id();
            $user = get_userdata($user_id);
            $email = $user->user_email;
            $name = $user->display_name;
        } else {
            $user_id = 0; // Guest
            $email = sanitize_email($form_data['guest_email'] ?? '');
            $name = sanitize_text_field($form_data['guest_name'] ?? 'Guest');
            
            if (!is_email($email)) wp_send_json_error(['message' => 'Invalid email address.']);
        }
        
        // 1. Create Ticket Post (CPT)
        $post_id = wp_insert_post(array(
            'post_title' => $subject,
            'post_content' => $message,
            'post_status' => 'publish', 
            'post_type' => 'vmo_ticket',
            'post_author' => $user_id // 0 for guest
        ));
        
        if ($post_id) {
            update_post_meta($post_id, 'vmo_ticket_department', $department);
            update_post_meta($post_id, 'vmo_ticket_status', 'open');
            update_post_meta($post_id, 'vmo_guest_email', $email);

            // 2. Route Email to Department owner (Site Admin)
            $this->send_department_email($department, $subject, $message, $email, $name);

            // 3. Log to Auto-CRM Interaction
            $this->log_to_safe_crm($email, $name, $post_id, $subject, $department);

            wp_send_json_success(['message' => 'Request sent to ' . ucfirst($department) . ' team.']);
        } else {
            wp_send_json_error(['message' => 'Failed to process request.']);
        }
    }

    /**
     * Send email to the specific department
     */
    private function send_department_email($department, $subject, $message, $sender_email, $sender_name) {
        // Fetch custom email from options, fallback to admin email
        $dept_email = get_option("vmo_email_{$department}", get_option('admin_email'));
        
        $headers = array('Content-Type: text/html; charset=UTF-8');
        $headers[] = 'From: VMO Support <noreply@' . $_SERVER['HTTP_HOST'] . '>';
        $headers[] = "Reply-To: $sender_name <$sender_email>";

        $body = "
            <h3>New Support Ticket: #{$department}</h3>
            <p><strong>From:</strong> {$sender_name} ({$sender_email})</p>
            <p><strong>Subject:</strong> {$subject}</p>
            <hr>
            <p>" . nl2br($message) . "</p>
            <hr>
            <p><small>Sent via VMO Website Generator</small></p>
        ";

        wp_mail($dept_email, "[Ticket] $subject", $body, $headers);
    }

    /**
     * Log to CRM (Safe Mode: Creates Contact if Missing)
     */
    private function log_to_safe_crm($email, $name, $ticket_id, $subject, $department) {
        global $wpdb;
        $t_contacts = $wpdb->prefix . 'vmo_contacts';
        $t_interactions = $wpdb->prefix . 'vmo_contact_interactions';

        // Check if tables exist
        if ($wpdb->get_var("SHOW TABLES LIKE '$t_contacts'") != $t_contacts) return;

        // 1. Find or Create Contact
        $contact = $wpdb->get_row($wpdb->prepare("SELECT * FROM $t_contacts WHERE email = %s", $email));
        
        if ($contact) {
            $contact_key = $contact->contact_id;
        } else {
            // Create New Lead
            $contact_key = 'vmo_guest_' . time() . '_' . rand(100,999);
            $names = explode(' ', $name, 2);
            $fname = $names[0];
            $lname = isset($names[1]) ? $names[1] : '';
            
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->insert($t_contacts, [
                'user_id' => 1, // Assign to Site Owner (Admin)
                'contact_id' => $contact_key,
                'email' => $email,
                'full_name' => $name,
                'first_name' => $fname,
                'last_name' => $lname,
                'source' => 'website_form',
                'primary_category' => 'Support Request',
                'lifecycle_stage' => 'new',
                'created_at' => current_time('mysql')
            ]);
        }

        // 2. Log Interaction
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert($t_interactions, [
            'user_id' => 1,
            'contact_id' => $contact_key,
            'interaction_type' => 'support_ticket',
            'interaction_subtype' => $department,
            'direction' => 'inbound',
            'subject' => "Ticket #$ticket_id: $subject",
            'summary' => "Opened {$department} request: " . substr($subject, 0, 50) . '...',
            'created_at' => current_time('mysql')
        ]);
    }

    /**
     * [vmo_ticket_list]
     */
    public function render_ticket_list($atts) {
        if (!is_user_logged_in()) return '';
        
        $user_id = get_current_user_id();
        $args = array(
            'post_type' => 'vmo_ticket',
            'author' => $user_id,
            'posts_per_page' => 10,
            'post_status' => 'publish' // or any
        );
        
        $query = new WP_Query($args);
        
        if (!$query->have_posts()) {
            return '<p>No tickets found.</p>';
        }
        
        ob_start();
        ?>
        <table class="vmo-ticket-table" style="width:100%; border-collapse:collapse;">
            <thead>
                <tr style="background:#eee; text-align:left;">
                    <th style="padding:10px;">ID</th>
                    <th style="padding:10px;">Subject</th>
                    <th style="padding:10px;">Status</th>
                    <th style="padding:10px;">Date</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($query->have_posts()) : $query->the_post(); 
                $status = get_post_meta(get_the_ID(), 'vmo_ticket_status', true) ?: 'open';
            ?>
                <tr style="border-bottom:1px solid #ddd;">
                    <td style="padding:10px;">#<?php the_ID(); ?></td>
                    <td style="padding:10px;"><?php the_title(); ?></td>
                    <td style="padding:10px;"><span class="vmo-badge <?php echo esc_attr($status); ?>"><?php echo ucfirst($status); ?></span></td>
                    <td style="padding:10px;"><?php echo get_the_date(); ?></td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        <style>
            .vmo-badge { padding: 3px 8px; border-radius: 10px; font-size: 12px; color: #fff; }
            .vmo-badge.open { background: #28a745; }
            .vmo-badge.closed { background: #6c757d; }
        </style>
        <?php
        wp_reset_postdata();
        return ob_get_clean();
    }

    /**
     * [vmo_ticket_manager]
     * Admin tool to view ALL tickets
     */
    public function render_ticket_manager($atts) {
        if (!current_user_can('edit_others_posts')) return 'Access Denied';

        $args = array(
            'post_type' => 'vmo_ticket',
            'posts_per_page' => 20,
            'post_status' => 'publish'
        );
        $query = new WP_Query($args);

        ob_start();
        ?>
        <div class="vmo-admin-panel">
            <div class="vmo-panel-header">
                <h3>Support Ticket Manager</h3>
                <button onclick="window.location.href='<?php echo admin_url('admin-ajax.php?action=vmo_export_tickets'); ?>'" class="vmo-btn-export">Export CSV</button>
            </div>
            <table class="vmo-data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User</th>
                        <th>Subject</th>
                        <th>Priority</th>
                        <th>Status</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($query->have_posts()) : $query->the_post(); 
                        $status = get_post_meta(get_the_ID(), 'vmo_ticket_status', true) ?: 'open';
                        $priority = get_post_meta(get_the_ID(), 'vmo_ticket_priority', true) ?: 'medium';
                        $author = get_the_author();
                    ?>
                    <tr>
                        <td>#<?php the_ID(); ?></td>
                        <td><?php echo esc_html($author); ?></td>
                        <td><?php the_title(); ?></td>
                        <td><?php echo ucfirst($priority); ?></td>
                        <td><span class="vmo-badge <?php echo esc_attr($status); ?>"><?php echo ucfirst($status); ?></span></td>
                        <td><?php echo get_the_date(); ?></td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        <style>
            .vmo-admin-panel { background: #fff; padding: 20px; border: 1px solid #ddd; }
            .vmo-panel-header { display: flex; justify-content: space-between; margin-bottom: 15px; }
            .vmo-data-table { width: 100%; border-collapse: collapse; }
            .vmo-data-table th, .vmo-data-table td { padding: 10px; border-bottom: 1px solid #eee; text-align: left; }
            .vmo-btn-export { background: #28a745; color: white; border: none; padding: 8px 15px; cursor: pointer; }
            .vmo-badge { padding: 3px 8px; border-radius: 10px; font-size: 12px; color: #fff; }
            .vmo-badge.open { background: #28a745; }
            .vmo-badge.closed { background: #6c757d; }
        </style>
        <?php
        wp_reset_postdata();
        return ob_get_clean();
    }

    /**
     * Handle CSV Export
     */
    public function handle_ticket_export() {
        if (!current_user_can('edit_others_posts')) wp_die('Access Denied');

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="tickets_export_' . date('Y-m-d') . '.csv"');

        $output = fopen('php://output', 'w');
        fputcsv($output, array('ID', 'User', 'Subject', 'Content', 'Priority', 'Status', 'Date'));

        $args = array(
            'post_type' => 'vmo_ticket',
            'posts_per_page' => -1,
            'post_status' => 'publish'
        );
        $query = new WP_Query($args);

        while ($query->have_posts()) {
            $query->the_post();
            fputcsv($output, array(
                get_the_ID(),
                get_the_author(),
                get_the_title(),
                wp_strip_all_tags(get_the_content()),
                get_post_meta(get_the_ID(), 'vmo_ticket_priority', true),
                get_post_meta(get_the_ID(), 'vmo_ticket_status', true),
                get_the_date('Y-m-d H:i:s')
            ));
        }
        fclose($output);
        exit;
    }
}
