<?php
/**
 * Database repository helpers.
 *
 * @package PlugozaEventTicketing
 */

namespace PlugozaEventTicketing;

defined( 'ABSPATH' ) || exit;

/** Small prepared-query repository for plugin tables. */
final class Repository {
	public static function table( $name ) {
		global $wpdb;

		return $wpdb->prefix . 'plugoza_ett_' . $name;
	}

	public static function events( $published = false ) {
		global $wpdb;

		if ( $published ) {
			return $wpdb->get_results(
				$wpdb->prepare(
					'SELECT * FROM %i WHERE status = %s ORDER BY start_date ASC',
					self::table( 'events' ),
					'published'
				)
			);
		}

		return $wpdb->get_results(
			$wpdb->prepare(
				'SELECT * FROM %i ORDER BY start_date ASC',
				self::table( 'events' )
			)
		);
	}

	public static function event( $id ) {
		global $wpdb;

		return $wpdb->get_row(
			$wpdb->prepare(
				'SELECT * FROM %i WHERE id = %d',
				self::table( 'events' ),
				absint( $id )
			)
		);
	}

	public static function tickets( $event_id, $active = false ) {
		global $wpdb;

		if ( $active ) {
			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT * FROM %i WHERE event_id = %d AND status = 'active' AND available_quantity > 0 AND (sale_start IS NULL OR sale_start <= UTC_TIMESTAMP()) AND (sale_end IS NULL OR sale_end >= UTC_TIMESTAMP())",
					self::table( 'tickets' ),
					absint( $event_id )
				)
			);
		}

		return $wpdb->get_results(
			$wpdb->prepare(
				'SELECT * FROM %i WHERE event_id = %d',
				self::table( 'tickets' ),
				absint( $event_id )
			)
		);
	}
}
