<?php
namespace QuizPress\API\Query;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Category {

	public static function category_insert( $postarr ) {
		if ( ! is_array( $postarr ) ) {
			return null;
		}

		global $wpdb;

		$defaults = array(
			'category_title'          => '',
			'category_slug'           => '',
			'category_content'        => '',
		);

		$category_arr = wp_parse_args( $postarr, $defaults );
		$category_arr['category_title'] = html_entity_decode( $category_arr['category_title'] );

		$table_name = $wpdb->prefix . 'quizpress_category';
		$id = 0;
		$update = false;

		if ( ! empty( $postarr['id'] ) ) {
			$id = (int) $postarr['id'];
			$update = true;
			unset( $category_arr['id'] );
		}

		$formats = array(
			'%s', // category_title
			'%s', // category_slug
			'%s', // question_content
		);

		if ( $update ) {
			$wpdb->update(
				$table_name,
				$category_arr,
				array( 'id' => $id ),
				$formats,
				array( '%d' )
			);
			return $id;
		} else {
			$wpdb->insert(
				$table_name,
				$category_arr,
				$formats
			);
			return $wpdb->insert_id;
		}

		return null;
	}

	public static function get_category( $args = array() ) {
		global $wpdb;

		$defaults = array(
			'per_page' => 10,
			'offset'   => 0,
			'status'   => 'any',
			'keyword'  => '',
		);

		$args = wp_parse_args( $args, $defaults );

		$per_page = absint( $args['per_page'] );
		$offset   = absint( $args['offset'] );
		$keyword  = sanitize_text_field( $args['keyword'] );

		$table = "{$wpdb->prefix}quizpress_category";

		$where  = array();
		$params = array();

		if ( ! empty( $keyword ) ) {
			$where[]  = '(category_title LIKE %s OR category_slug LIKE %s)';
			$search   = '%' . $wpdb->esc_like( $keyword ) . '%';
			$params[] = $search;
			$params[] = $search;
		}

		$sql = "SELECT * FROM {$table}";

		if ( ! empty( $where ) ) {
			$sql .= ' WHERE ' . implode( ' AND ', $where );
		}

		$sql .= ' ORDER BY id DESC LIMIT %d OFFSET %d';
		$params[] = $per_page;
		$params[] = $offset;

		return $wpdb->get_results( $wpdb->prepare( $sql, $params ), OBJECT );// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	}

	public static function get_question_category( $ID ) {
		global $wpdb;
		$question   = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}quizpress_category WHERE id=%d", $ID ), OBJECT );
		return current( $question );
	}

	public static function delete_category( $category_id ) {
		global $wpdb;
		$is_deleted = $wpdb->delete( $wpdb->prefix . 'quizpress_category', array( 'id' => $category_id ), array( '%d' ) );
		return $is_deleted;
	}

	public static function get_total_category(): int {
		global $wpdb;

		return (int) $wpdb->get_var(
			"SELECT COUNT(id) FROM {$wpdb->prefix}quizpress_category"
		);
	}
}
