<?php 

namespace WPVOFW;

use WPVOFW\Feedback;

// a class to handle frontend submission through ajax. Validate and save the feedback

class Submission{

    public function __construct(){
        add_action('wp_ajax_wpvofw_submit_feedback', [$this, 'submit_feedback']);
        add_action('wp_ajax_nopriv_wpvofw_submit_feedback', [$this, 'submit_feedback']);
    }

    /**
     * Submit feedback
     * @return void
     * @since 1.0.0
     */
    public function submit_feedback(){
        check_ajax_referer('wpvofw_thankyou', 'wpvofw_thankyou_nonce');
        
        $data = $_POST;

        $response = [
            'status' => 'error',
            'error_code' => 1038,
            'message' => esc_html__('An error occurred. Please try again later', 'order-feedback-woo')
        ];
 
        $response['message'] = apply_filters('wpvofw/response/error_message', $response['message']);

        if(!isset($data['order_id']) || empty($data['order_id'])){
            wp_send_json($response);
        }

        $order_id = $data['order_id'];
        $order = wc_get_order($order_id);

        if(!$order){
            wp_send_json($response);
        }

        $this->validate_data($data);

        $feedback = [
            'order_id' => $order_id,
            'title' => isset($data['title']) ? sanitize_text_field($data['title']) : '',
            'message' => isset($data['message']) ? sanitize_textarea_field($data['message']) : '',
            'rating' => isset($data['rating']) ? intval($data['rating']) : 0,
        ];

        $feedback['id'] = Feedback::add_feedback($feedback);

        if($feedback['id']){

            // update the order meta to mark the feedback as submitted
            $meta_key   = 'feedback_form_submitted';
            $meta_value = 'true';

            $order->add_meta_data($meta_key, $meta_value);
            $order->save();
            
            $response = [
                'status' => 'success',
                'message' => esc_html__('Thank you for your feedback!', 'order-feedback-woo')
            ];

            $response['message'] = apply_filters('wpvofw/response/success_message', $response['message']);


            // Trigger emails 
            $this->send_emails($order, $feedback);
        }else{
            $response = [
                'status' => 'error',
                'error_code' => 1034,
                'message' => esc_html__('An error occurred. Please try again later', 'order-feedback-woo')
            ];
            $response['message'] = apply_filters('wpvofw/response/error_message', $response['message']);

        }

        wp_send_json($response);
    }

    /**
     * Validate the feedback data
     * @param $data
     * @return void
     * @since 1.0.0
     */
    private function validate_data($data){
        
        // validate the fields and prepare error messages in a array. 
        // if there are any errors, send the error messages as response and exit

        $errors = [];

        if(!isset($data['title']) || empty($data['title'])){
            $errors[] = [
                'key' => 'title',
                'message' => esc_html__('Title is required', 'order-feedback-woo')
            ];
        }

        if(!isset($data['message']) || empty($data['message'])){
            $errors[] = [
                'key' => 'message',
                'message' => esc_html__('Message is required', 'order-feedback-woo')
            ];
        }

        if(!isset($data['rating']) || empty($data['rating'])){
            $errors[] = [
                'key' => 'rating',
                'message' => esc_html__('Rating is required', 'order-feedback-woo')
            ];
        }

        /**
         * Filter the errors
         * @param array $errors
         * @param array $data
         * @return array
         * @since 1.0.0
         */
        $errors = apply_filters('wpvofw/validate_feedback_data', $errors, $data);
        
        if(!empty($errors)){
            wp_send_json([
                'status' => 'error',
                'message' => esc_html__('Please fill in all the required fields', 'order-feedback-woo'),
                'errors' => $errors
            ]);
        }
    }

    /**
     * Send emails to admin and customer
     * @param $order
     * @param $feedback
     * @return void
     * @since 1.0.0
     */
    private function send_emails($order, $feedback){
        

        $send_admin_mail = apply_filters('wpvofw/feedback-received/send_admin_email', __return_true(), $order, $feedback);
        if($send_admin_mail){

            // send email to admin 
            $admin_email = get_option('admin_email');
            $subject = 'New feedback submitted';
            $message = 'A new feedback has been submitted for order #' . $order->get_order_number();
        
            /**
             * Filters the admin email
             * @param string $admin_email
             * @param WC_Order $order
             * @param array $feedback
             */
            $admin_email = apply_filters('wpvofw/feedback-received/admin_email', $admin_email, $order, $feedback);

            /**
             * Filters the admin email subject
             * @param string $subject
             * @param WC_Order $order
             * @param array $feedback
             */
            $subject = apply_filters('wpvofw/feedback-received/admin_email_subject', $subject, $order, $feedback);

            /**
             * Filters the admin email message
             * @param string $message
             * @param WC_Order $order
             * @param array $feedback
             */
            $message = apply_filters('wpvofw/feedback-received/admin_email_message', $message, $order, $feedback);

            wp_mail($admin_email, $subject, $message);
        }

        $send_customer_mail = apply_filters('wpvofw/feedback-received/send_customer_email', __return_true(), $order, $feedback);
        
        if($send_customer_mail){

            // send email to customer
            $customer_email = $order->get_billing_email();
            $subject = 'Thank you for your feedback';
            $message = 'Thank you for your feedback. We appreciate your time';
        
            /**
             * Filters the customer email
             * @param string $customer_email
             * @param WC_Order $order
             * @param array $feedback
             */
            $customer_email = apply_filters('wpvofw/feedback-received/customer_email', $customer_email, $order, $feedback);

            /**
             * Filters the customer email subject
             * @param string $subject
             * @param WC_Order $order
             * @param array $feedback
             */
            $subject = apply_filters('wpvofw/feedback-received/customer_email_subject', $subject, $order, $feedback);

            /**
             * Filters the customer email message
             * @param string $message
             * @param WC_Order $order
             * @param array $feedback
             */
            $message = apply_filters('wpvofw/feedback-received/customer_email_message', $message, $order, $feedback);

            wp_mail($customer_email, $subject, $message);
        }
    }
  
}