<?php

namespace Simple_Giveaways;

use WP_Post;

/**
 * Class SG_Giveaway_Factory
 */
class SG_Giveaway_Factory {

	/**
	 * @param integer|WP_Post $post
	 *
	 * @return SG_Giveaway|boolean
	 */
	public static function get_giveaway( $post ) {
		if ( ! $post ) {
			return false;
		}

		if ( is_a( $post, 'WP_Post' ) ) {
			$post_id = $post->ID;
		} else {
			$post_id = $post;
		}

		if ( ! $post_id ) {
			return false;
		}

		if ( ! is_numeric( $post_id ) ) {
			return false;
		}

		$class = self::get_class_from_giveaway( $post_id );

		if ( $class ) {
			return new $class( $post );
		} else {
			return false;
		}
	}

	/**
	 * @param $post_id
	 */
	public static function get_class_from_giveaway( $post_id ) {
		$type = self::get_type( $post_id );
		return self::get_class_from_type( $type );
	}

	/**
	 * Get the product Type
	 *
	 * @param $post_id
	 *
	 * @return string
	 */
	public static function get_type( $post_id ) {
		return get_post_meta( $post_id, 'giveasap_type', true );
	}

	/**
	 * Get the Giveaway Class for
	 *
	 * @param $type
	 */
	public static function get_class_from_type( $type ) {
		$class = $type ? 'SG_Giveaway_' . ucfirst( str_replace( '-', '_', $type ) ) : '\Simple_Giveaways\SG_Giveaway_Simple';

		// Let's prefix it to try and find.
		if ( ! class_exists( $class ) ) {
			$class = '\Simple_Giveaways\\' . $class;
		}

		if ( ! class_exists( $class ) ) {
			$class = '\Simple_Giveaways\SG_Giveaway_Simple';
		}

		return apply_filters( 'sg_giveaway_factory_class_from_type', $class, $type );
	}
}
