<?php 

namespace WPVOFW;

class Feedback{
     /**
     * Insert data
     */
    public static function add_feedback($data){
        
        global $wpdb;

        $feedback_table = $wpdb->prefix . 'wpvofw_feedbacks';

        $data = wp_parse_args($data, [
            'order_id' => 0,
            'title' => '',
            'message' => '',
            'rating' => 0,
            'rating_scale' => 5,
            'date_created' => current_time('mysql')
        ]);

        $data = apply_filters('wpvofw/before_feedback_insert', $data);

        $wpdb->insert($feedback_table, $data);

        do_action('wpvofw/after_feedback_insert', $wpdb->insert_id, $data);

        return $wpdb->insert_id;
    }

   /**
    * Get feedback by feedback id
    */
   public static function get_feedback($id){
        global $wpdb;

        $feedback_table = $wpdb->prefix . 'wpvofw_feedbacks';

        // use prepare query to get the data
        $query = $wpdb->prepare("SELECT * FROM {$feedback_table} WHERE id = %d", $id);

        return $wpdb->get_row($query);
   }

   /**
    * Get feedback by order id
    */

    public static function get_feedback_by_order_id($order_id){
          global $wpdb;
    
          $feedback_table = $wpdb->prefix . 'wpvofw_feedbacks';
    
          // use prepare query to get the data
          $query = $wpdb->prepare("SELECT * FROM {$feedback_table} WHERE order_id = %d", $order_id);
    
          return $wpdb->get_row($query);
    }

    /**
     * Get all feedbacks
     */

    // get all feedbacks based on args provided. Args can include filtering options like date range, order id, date range and can also have options for limit, offset and sorting.
    public static function get_feedbacks($args = []){

        global $wpdb;

        $feedback_table = $wpdb->prefix . 'wpvofw_feedbacks';

        $query = "SELECT * FROM {$feedback_table} WHERE 1=1";


        // setup data parameters 
        if ( empty( $args['start_date'] ) ) {
			$args['start_date'] = date( 'Y-m-d H:i:s', strtotime( '-30 days' ) );
		}

        if ( empty( $args['end_date'] ) ) {
			$args['end_date'] = date( 'Y-m-d H:i:s' );
		}

        if ( $args['start_date'] !== '' && $args['start_date'] !== null ) {
			$orignalStartDateTS  = strtotime( $args['start_date'] );
			$args['start_date'] = date( 'Y-m-d', $orignalStartDateTS );
		}

		if ( $args['end_date'] !== '' && $args['end_date'] !== null ) {
			$orignalEndDateTS  = strtotime( $args['end_date'] );
			$args['end_date'] = date( 'Y-m-d', $orignalEndDateTS );
		}


        // check if order id is provided
        if(isset($args['order_id'])){
            $query .= $wpdb->prepare("order_id = %d", $args['order_id']);
        }

        // check if order ids are present
        if(isset($args['order_ids']) && is_array($args['order_ids'])){
            $query .= $wpdb->prepare("order_id IN (%s)", implode(',', $args['order_ids']));
        }

        // check if date range is provided
        if(isset($args['start_date']) && isset($args['end_date'])){
            $query .= $wpdb->prepare("DATE_FORMAT(date_created,GET_FORMAT(DATE,'JIS') BETWEEN %s AND %s", $args['start_date'], $args['end_date']);
        }

        // check if limit is provided
        if(isset($args['limit'])){
            $query .= $wpdb->prepare(" LIMIT %d", $args['limit']);
        }

        // check if offset is provided
        if(isset($args['offset'])){
            $query .= $wpdb->prepare(" OFFSET %d", $args['offset']);
        }

        // check if order by is provided
        if(isset($args['orderby'])){
            $query .= $wpdb->prepare(" ORDER BY %s", $args['orderby']);
        }

        return $wpdb->get_results($query);
    }
    
    /**
     * Get feedbacks by customer id
     */
    // first get order ids by customer id and then get feedbacks by order ids
    public static function get_feedbacks_by_customer_id($customer_id){
        global $wpdb;

        // get order ids by customer id using wc_get_orders function
        $order_ids = wc_get_orders([
            'customer' => $customer_id,
            'return' => 'ids'
        ]);

        // get feedback of all the order ids using get_feedbacks function
        return self::get_feedbacks([
            'order_ids' => $order_ids
        ]);
    } 
    
    // get all feedbacks along with order data and customer data
    public static function get_feedbacks_with_order_and_customer_data($args = [], $get_count = false){
        global $wpdb;

        $feedback_table = $wpdb->prefix . 'wpvofw_feedbacks';


         // setup data parameters 
         if ( empty( $args['start_date'] ) ) {
			$args['start_date'] = date( 'Y-m-d H:i:s', strtotime( '-30 days' ) );
		}

        if ( empty( $args['end_date'] ) ) {
			$args['end_date'] = date( 'Y-m-d H:i:s' );
		}

        if ( $args['start_date'] !== '' && $args['start_date'] !== null ) {
			$orignalStartDateTS  = strtotime( $args['start_date'] );
			$args['start_date'] = date( 'Y-m-d', $orignalStartDateTS );
		}

		if ( $args['end_date'] !== '' && $args['end_date'] !== null ) {
			$orignalEndDateTS  = strtotime( $args['end_date'] );
			$args['end_date'] = date( 'Y-m-d', $orignalEndDateTS );
		}



        if($get_count){
            $query = "SELECT COUNT(*) FROM {$feedback_table} WHERE 1=1 ";
        }else{
            $query = "SELECT * FROM {$feedback_table} WHERE 1=1 ";
        }

        // check if order id is provided
        if(isset($args['order_id'])){
            $query .= $wpdb->prepare(" AND order_id = %d", $args['order_id']);
        }

        // check if order ids are present
        if(isset($args['order_ids'])){
            $query .= $wpdb->prepare(" AND order_id IN (%s)", explode(',', $args['order_ids']));
        }

        // rating
        if(isset($args['rating'])){
            $query .= $wpdb->prepare(" AND rating = %d", $args['rating']);
        }


        // check if date range is provided
        if(isset($args['start_date']) && isset($args['end_date'])){
            $query .= $wpdb->prepare(" AND DATE_FORMAT(date_created,GET_FORMAT(DATE,'JIS')) BETWEEN %s AND %s", $args['start_date'], $args['end_date']);
        }

        if($get_count){
            return $wpdb->get_var($query);
        }

        // check if limit is provided
        if(isset($args['limit'])){
            $query .= $wpdb->prepare(" LIMIT %d", $args['limit']);
        }

        // apply offset based on current_page and per_page
        if(isset($args['current_page']) && isset($args['limit'])){
            $offset = ($args['current_page'] - 1) * $args['limit'];
            $query .= $wpdb->prepare(" OFFSET %d", $offset);
        }
        
        $feedbacks = $wpdb->get_results($query);
        
        // get order data and customer data for each feedback
        foreach($feedbacks as $feedback){ 
            
            $order = wc_get_order($feedback->order_id);
            
            if(!$order){
                continue;
            }
            $customer = $order->get_user();

            $feedback->order_link = $order->get_edit_order_url();
            
            $feedback->customer_id = $customer->data->ID;
            $feedback->customer_email = $customer->data->user_email;
            $feedback->customer_name = $customer->data->user_nicename;

            $feedback->customer_url = get_edit_user_link($customer->data->ID);
        }

        return $feedbacks;
    }

    public static function get_feedbacks_count(){
        global $wpdb;

        $feedback_table = $wpdb->prefix . 'wpvofw_feedbacks';

        $query = "SELECT COUNT(*) FROM {$feedback_table}";

        return $wpdb->get_var($query);
    }

   

}