/**
 * Support Ticket JavaScript
 *
 * This file contains the Vue.js application for the support ticket system.
 * It handles form submission, ticket listing, and modal functionality.
 *
 * @package Postomatic
 * @subpackage Admin/Assets/JS
 * @since 1.2.0
 */

document.addEventListener('DOMContentLoaded', function() {
    const app = Vue.createApp({
        data() {
            return {
                formData: {
                    title: '',
                    description: '',
                    high_priority: false
                },
                tickets: [],
                loading: true,
                isSubmitting: false,
                isProUltimate: false,
                alert: {
                    show: false,
                    type: 'success',
                    message: ''
                },
                isModalVisible: false,
                modalData: {},
                modalLoading: false,
                modalError: ''
            };
        },
        mounted() {
            this.fetchTickets();
        },
        methods: {
            // Submit a new support ticket
            submitTicket() {
                this.isSubmitting = true;

                const formData = new FormData();
                formData.append('action', postomaticSupportData.apiEndpoints.POST_TICKET);
                formData.append('nonce', postomaticSupportData.nonce);
                formData.append('title', this.formData.title);
                formData.append('description', this.formData.description);
                formData.append('high_priority', this.formData.high_priority ? 1 : 0);

                axios.post(postomaticSupportData.ajaxUrl, formData)
                    .then(response => {
                        if (response.data.success) {
                            this.alert = {
                                show: true,
                                type: 'success',
                                message: 'Your support ticket has been submitted successfully!'
                            };

                            // Reset form
                            this.formData = {
                                title: '',
                                description: '',
                                high_priority: false
                            };

                            // Refresh tickets list
                            this.fetchTickets();
                        } else {
                            this.alert = {
                                show: true,
                                type: 'error',
                                message: (response.data.data && response.data.data.message) || response.data.message || 'An error occurred while submitting your ticket.'
                            };
                        }
                    })
                    .catch(error => {
                        this.alert = {
                            show: true,
                            type: 'error',
                            message: 'An error occurred while submitting your ticket. Please try again.'
                        };
                        console.error('Error submitting ticket:', error);
                    })
                    .finally(() => {
                        this.isSubmitting = false;
                    });
            },

            // Fetch all tickets for the current user
            fetchTickets() {
                this.loading = true;

                const data = {
                    action: postomaticSupportData.apiEndpoints.GET_TICKETS,
                    nonce: postomaticSupportData.nonce
                };

                axios.get(postomaticSupportData.ajaxUrl, { params: data })
                    .then(response => {
                        if (response.data.success) {
                            this.tickets = response.data.data.tickets || [];
                            this.isProUltimate = response.data.data.plan === 'pro-ultimate';
                         } else {
                             this.tickets = [];
                             this.alert = {
                                 show: true,
                                 type: 'error',
                                 message: (response.data.data && response.data.data.message) || response.data.message || 'Unable to load your support tickets. Please try again.'
                             };
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching tickets:', error);
                        this.tickets = [];
                        this.alert = {
                            show: true,
                            type: 'error',
                            message: 'Unable to load your support tickets. Please try again.'
                        };
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // Show ticket details in modal
            showTicket(ticketId) {
                this.isModalVisible = true;
                this.modalLoading = true;
                this.modalData = {};
                this.modalError = '';


                const data = {
                    action: postomaticSupportData.apiEndpoints.GET_SINGLE_TICKET,
                    nonce: postomaticSupportData.nonce,
                    ticket_id: ticketId
                };

                axios.get(postomaticSupportData.ajaxUrl, { params: data })
                    .then(response => {
                        if (response.data.success) {
                            this.modalData = response.data.data || {};
                         } else {
                             this.modalError = (response.data.data && response.data.data.message) || response.data.message || 'Unable to load this ticket. Please try again.';
                         }
                    })
                    .catch(error => {
                        console.error('Error loading ticket:', error);
                        this.modalError = 'Unable to load this ticket. Please try again.';
                    })
                    .finally(() => {
                        this.modalLoading = false;
                    });
            },

            // Close the modal
            closeModal() {
                this.isModalVisible = false;
                this.modalError = '';
            },

            // Get status color class based on ticket status
            getStatusColorClass(status) {
                switch (status) {
                    case 'Open':
                        return 'bg-blue-100 text-blue-800';
                    case 'In Progress':
                        return 'bg-yellow-100 text-yellow-800';
                    case 'Resolved':
                        return 'bg-green-100 text-green-800';
                    case 'Closed':
                        return 'bg-gray-100 text-gray-800';
                    case 'PENDING':
                        return 'bg-purple-100 text-purple-800';
                    default:
                        return 'bg-gray-100 text-gray-800';
                }
            },

            // Get status text color class for modal
            getStatusTextColorClass(status) {
                switch (status) {
                    case 'Open':
                        return 'bg-blue-100 text-blue-800';
                    case 'In Progress':
                        return 'bg-yellow-100 text-yellow-800';
                    case 'Resolved':
                        return 'bg-green-100 text-green-800';
                    case 'Closed':
                        return 'bg-gray-100 text-gray-800';
                    case 'PENDING':
                        return 'bg-purple-100 text-purple-800';
                    default:
                        return 'bg-gray-100 text-gray-800';
                }
            },

            // Get status icon based on ticket status
            getStatusIcon(status) {
                switch (status) {
                    case 'Open':
                        return 'fas fa-envelope-open-text';
                    case 'In Progress':
                        return 'fas fa-spinner';
                    case 'Resolved':
                        return 'fas fa-check-circle';
                    case 'Closed':
                        return 'fas fa-times-circle';
                    case 'PENDING':
                        return 'fas fa-clock';
                    default:
                        return 'fas fa-question-circle';
                }
            }
        }
    });

    app.mount('#app');
});
