<?php
/**
 * Matador / REST API / Jobs Namespace / Post Type Endpoint
 *
 * @link        https://matadorjobs.com/
 * @since       3.9.0
 *
 * @package     Matador Jobs Board
 * @subpackage  REST API
 * @author      Matador Software LLC, Jeremy Scott, Paul Bearne
 * @copyright   (c) 2024, Matador Software, LLC
 *
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 */

namespace matador\MatadorJobs\Rest\Endpoint\Jobs;

use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

use matador\Matador;
use matador\MatadorJobs\Rest\Endpoint\EndpointAbstract;
use matador\MatadorJobs\Core\Logger;
use matador\MatadorJobs\Core\Severity;

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

/**
 * Job Post Type Endpoint Class
 *
 * @since 3.9.0
 */
class PostType extends EndpointAbstract {

	/**
	 * Class Name
	 *
	 * @var string
	 *
	 * @since 3.9.0
	 */
	protected static $class = __CLASS__;

	/**
	 * Routes
	 *
	 * Called in a WordPress rest_api_init action to add the routes.
	 *
	 * @since 3.9.0
	 *
	 * @return void
	 */
	public static function routes(): void {

		// INDEX
		register_rest_route( self::rest_namespace(), '/jobs/post-type', [
			'methods' => WP_REST_Server::READABLE,
			'callback' => [ __CLASS__, 'index' ],
			'permission_callback' => '__return_true',
		] );
	}

	/**
	 * Index
	 *
	 * Returns the post type for the Matador Jobs job post type.
	 *
	 * @since 3.9.0
	 *
	 * @param WP_REST_Request $request
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public static function index( WP_REST_Request $request ): WP_REST_Response|WP_Error {

		$job_post_type = Matador::variable( 'post_type_key_job_listing' );

		if ( ! empty( $job_post_type ) ) {

			$response = [
				'postType' => $job_post_type,
			];

			return new WP_REST_Response( $response, 200 );
		}

		$code    = 'rest-jobs-post-type-retrieval-error';
		$message = __( 'Failed to retrieve the post type for the job post type.', 'matador-jobs' );

		Logger::entry( $code, $message, Severity::ERROR );

		return new WP_Error(
			$code,
			$message,
			[ 'status' => 500 ]
		);
	}
}
