<?php

namespace BwlFaqManager\Api\Db;

class QueryHelper {


	public $table;
	public $faqId;
	public $selectFields = '*';
	public $args;
	public $placeholders;
	public $dateTimeColumn;
	public $orderByString = '';
	public $groupByString = '';

	// public function __construct()
	// {
	// }

	public function getData() {
		global $wpdb;

		$this->args = $this->getArgs();

		// echo "<pre>";
		// print_r($this->args);
		// echo "</pre>";

		// echo "<pre>";
		// print_r($this->placeholders);
		// echo "</pre>";
		$query = "SELECT {$this->selectFields} FROM {$this->table} ";

		if ( count( $this->args ) ) {
			$this->placeholders = $this->createPlaceholders();
			$query             .= $this->createWhereText();
			$query             .= $this->groupByString;
			$query             .= $this->orderByString;
			$data               = $wpdb->get_results( $wpdb->prepare( $query, $this->placeholders ), ARRAY_A );
		} else {
			$query .= $this->groupByString;
			$query .= $this->orderByString;
			$data   = $wpdb->get_results( $query, ARRAY_A );
		}
		// $query .= " LIMIT 100";

		// echo "<pre>";
		// print_r($query);
		// echo "</pre>";
		// die();
		// echo $wpdb->last_query;

		// echo "<pre>";

		// print_r($data);
		// echo "</pre>";
		// // die();
		return $data;
	}


	public function getArgs() {

		$urlFields = [];

		if ( isset( $_GET['faq_id'] ) && ! empty( $_GET['faq_id'] ) && is_numeric( $_GET['faq_id'] ) ) {
			$urlFields['post_id'] = sanitize_text_field( $_GET['faq_id'] ) ?? '';
		}

		if ( isset( $_GET['date_range'] ) && ! empty( $_GET['date_range'] ) && is_numeric( $_GET['date_range'] ) ) {
			$urlFields['date_range'] = sanitize_text_field( $_GET['date_range'] ) ?? 7;
		} else {
			// Last 7 days views and likes.
			$urlFields['date_range'] = 7;
		}

		return array_filter($urlFields, function ( $x ) {
			return $x;
		});
	}

	public function createPlaceholders() {
		return array_map(function ( $x ) {
			return $x;
		}, $this->args);
	}

	public function createWhereText() {
		$whereQuery = '';

		if ( count( $this->args ) ) {
			$whereQuery = 'WHERE ';

			$currentPos = 0;

			foreach ( $this->args as $index => $item ) {
				$whereQuery .= $this->specifcQuery( $index );
				if ( $currentPos != count( $this->args ) - 1 ) {
					$whereQuery .= ' AND ';
				}
				++$currentPos;
			}
		}

		return $whereQuery;
	}

	public function specifcQuery( $index ) {

		switch ( $index ) {
			case 'post_id':
				return 'post_id = %d';
			case 'date_range':
				return "$this->dateTimeColumn BETWEEN CURDATE() - INTERVAL %d DAY AND CURDATE()";
			default:
				return $index . ' = %s';
		}
	}
}
