<?php namespace MeowCrew\CancellationOffers\Offer\Entity\Statistics;

use MeowCrew\CancellationOffers\Offer\Entity\Offer;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersTable;

class Statistics {
	
	/**
	 * Offer
	 *
	 * @var Offer
	 */
	protected $offer;
	
	public function __construct( Offer $offer ) {
		$this->offer = $offer;
	}
	
	public function getRetentionRate( $withDiscountOffered = false ): ?float {
		
		global $wpdb;
		
		$database = $wpdb;
		
		$tableName = SurveyAnswersTable::getTableName();
		
		$query = 'SELECT
		   		COUNT(CASE WHEN is_discount_offer_accepted = 0 THEN 1 END) AS total_cancellations,
			    COUNT(CASE WHEN is_discount_offer_accepted = 1 THEN 1 END) AS total_retentions,
				ROUND( 100.0 * COUNT(CASE WHEN is_discount_offer_accepted = 1 THEN 1 END) / COUNT(*), 2) AS retention_rate
			FROM
			    %i
			WHERE offer_id = %d';
		
		if ( $withDiscountOffered ) {
			$query .= ' AND is_discount_offer_enabled = 1';
		}
		
		$result = $database->get_row( $database->prepare( $query, $tableName, $this->offer->getId() ) );
		
		if ( ! $result ) {
			return null;
		}
		
		return (float) $result->retention_rate;
	}
	
	public function getSurveyResults(): array {
		global $wpdb;
		
		$database = $wpdb;
		
		$tableName = SurveyAnswersTable::getTableName();
		
		$rawQuery = "SELECT
			    survey_selected_answer as answer,
			    COUNT(*) AS answer_count,
			    ROUND(100.0 * COUNT(*) / (
			        SELECT COUNT(*)
			        FROM  %i
			        WHERE offer_id = %d
			          AND survey_selected_answer IS NOT NULL
			          AND survey_selected_answer != ''
			    )) AS answer_count_rate
			FROM
			    %i
			WHERE
			    offer_id = %d
				AND survey_selected_answer IS NOT NULL
	            AND survey_selected_answer != ''
			GROUP BY
			    survey_selected_answer
			ORDER BY
			    answer_count DESC";
		
		$result = $database->get_results( $database->prepare( $rawQuery, $tableName, $this->offer->getId(), $tableName,
			$this->offer->getId() ), ARRAY_A );
		
		if ( $result ) {
			return $result;
		} else {
			return array();
		}
	}
}
