<?php
/**
 * Matador / REST API / Submission Screening 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) 2025, Matador Software, LLC
 *
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 */

// @todo: for PHP 8.0 update, add union type return typing

namespace matador\MatadorJobs\Rest\Endpoint;

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

use Matador\Matador;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use matador\Application;
use matador\MatadorJobs\Core\Logger;
use matador\MatadorJobs\Core\Severity;
use matador\MatadorJobs\Rest\Schema\SubmissionScreening as Schema;

/**
 * Application Endpoint Class
 *
 * @since 3.9.0
 */
class SubmissionScreening extends EndpointAbstract {

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

	/**
	 * Routes
	 *
	 * Called in a WordPress rest_api_init action to add the routes.
	 *
	 * @since 3.9.0
	 *
	 * @access public
	 * @static
	 *
	 * @return void
	 */
	public static function routes() {
	// public static function routes() : void {
		register_rest_route( self::rest_namespace(), self::get_route(), [
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => [ __CLASS__, 'action' ],
				'permission_callback' => [ __CLASS__, 'validate_hash' ],
				'args'                => Schema::index(),
			],
		] );
	}

	/**
	 * Retrieves the route for the pre-filter application endpoint.
	 *
	 * @since 3.9.0
	 *
	 * @return string The route for the pre-filter application endpoint.
	 */
	public static function get_route() {
		return '/application/screening';
	}

	/**
	 * Performs an action based on the provided request.
	 *
	 * @since 3.9.0
	 *
	 * @param WP_REST_Request $request The request object.
	 *
	 * @return WP_REST_Response The response object.
	 */
	public static function action( WP_REST_Request $request ) {

		$params = $request->get_params();

		// handle already set application / missing
		switch ( $params['action'] ) {
			case 'apply':
				update_post_meta( $params['id'], Matador::variable( 'candidate_sync_status' ), -1 );
				update_post_meta( $params['id'], Matador::variable( 'application_processing_preapproval_status' ), 'marked-for-apply' );
				$message = __( 'Application Screened: Add Candidate and Apply to Job(s)', 'matador-jobs' );
				break;
			case 'add':
				update_post_meta( $params['id'], Matador::variable( 'candidate_sync_status' ), -1 );
				update_post_meta( $params['id'], Matador::variable( 'application_processing_preapproval_status' ), 'marked-for-add' );
				$message = __( 'Application Screened: Add Candidate', 'matador-jobs' );
				break;
			case 'delete':
				if ( Matador::setting( 'application_delete_local_on_sync' ) ) { // @todo, DRY/Common (action on post meta update, function in application-screening delete_on_rejection
					Logger::entry( 'matador-app-pre-filter-delete-success-delete', esc_html__( 'Application deleted due to Privacy and Data Storage settings. Removing local candidate.', 'matador-jobs' ), Severity::NOTICE );
					wp_delete_post( $params['id'], true );
					$data = [ 'status' => esc_html__( 'Deleted', 'matador-jobs' ) ];
					if ( str_contains( $params['url'], 'index.php' ) ) {
						$message = __( 'Application Screened: Deleted', 'matador-jobs' );
					} else {
						$url = add_query_arg( 'post_type', Matador::variable( 'post_type_key_application' ), remove_query_arg( [
							'post',
							'action'
						], $params['url'] ) );
						wp_safe_redirect( str_replace( 'post.php', 'edit.php', $url ) );
					}

				} else {
					update_post_meta( $params['id'], Matador::variable( 'candidate_sync_status' ), 1 );
					update_post_meta( $params['id'], Matador::variable( 'application_processing_preapproval_status' ), 'marked-for-deletion' );
					$message = __( 'Application Screened: Marked for Delete', 'matador-jobs' );
				}
				break;
			case 'reset':
				update_post_meta( $params['id'], Matador::variable( 'candidate_sync_status' ), - 2 );
				delete_post_meta( $params['id'], Matador::variable( 'application_processing_preapproval_status' ) );
				$message = __( 'Application Screened: Reset Actions', 'matador-jobs' );
		}

		$data = [
			'action'            => $params['action'],
			'status'            => Application::get_sync_status_label( $params['id'] ),
			'buttons'           => Application::get_sync_single_button( $params['id'], $params['referrer'] ),
			'redirect_location' => admin_url() . 'edit.php?post_type=' . Matador::variable( 'post_type_key_application' ),
			'message'           => $message,
		];

		if ( str_contains( $params['referrer'], 'index.php' ) ) {
			header( 'content-type: text/html; charset=UTF-8' );
			printf( '<h1 style="text-align: center; margin-top:50px">%s</h1><p style="text-align: center;">%s</p>', $message, __( 'You can close this window/tab now.', 'matador-jobs' ) );
			die();
		} else {
			return new WP_REST_Response( $data, 200 );
		}
	}

	/**
	 * Validate Request
	 *
	 * This function checks if the unique number (hash) provided in the request matches the stored data in the post meta
	 * for the given application ID. It's used to ensure the request is authorized to perform actions on the post.
	 *
	 * @since 3.9.0
	 *
	 * @param WP_REST_Request $request The REST API request object.
	 *
	 * @return bool Returns true if the hash is valid and matches, false otherwise.
	 */
	public static function validate_hash( WP_REST_Request $request ): bool {
		$post_id   = $request->get_param( 'id' );
		$passed_id = $request->get_param( 'hash' );
		$stored_id = get_post_meta( $post_id, Matador::variable( 'submission_actions_hash' ), true );

		if ( empty( $passed_id ) || $passed_id !== $stored_id ) {

			return false;
		}

		return true;
	}
}
