<?php
/**
 * Creates default portal pages with the required shortcodes.
 *
 * @package TradeSchoolManager
 */

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

class TSM_Portal_Pages {

	const CREATED_OPTION = 'tsm_core_portal_pages_created';

	public static function init() {
		add_action( 'admin_init', array( __CLASS__, 'maybe_create_pages' ) );
	}

	public static function maybe_create_pages() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$pages = array(
			array(
				'setting'   => 'student_login_page',
				'slug'      => 'student-login',
				'title'     => __( 'Student Login', 'tradeschool-manager' ),
				'shortcode' => '[tsm_student_login]',
			),
			array(
				'setting'   => 'student_portal_page',
				'slug'      => 'student-portal',
				'title'     => __( 'Student Portal', 'tradeschool-manager' ),
				'shortcode' => '[tsm_student_portal]',
			),
			array(
				'setting'   => 'teacher_login_page',
				'slug'      => 'teacher-login',
				'title'     => __( 'Teacher Login', 'tradeschool-manager' ),
				'shortcode' => '[tsm_teacher_login]',
			),
			array(
				'setting'   => 'teacher_portal_page',
				'slug'      => 'teacher-portal',
				'title'     => __( 'Teacher Portal', 'tradeschool-manager' ),
				'shortcode' => '[tsm_teacher_portal]',
			),
		);

		$settings = class_exists( 'TSM_Settings' ) ? TSM_Settings::get_all() : get_option( 'tsm_settings', array() );
		$changed  = false;

		foreach ( $pages as $page ) {
			if ( ! empty( $settings[ $page['setting'] ] ) && 'publish' === get_post_status( (int) $settings[ $page['setting'] ] ) ) {
				continue;
			}

			$page_id = self::ensure_page( $page['slug'], $page['title'], $page['shortcode'] );
			if ( $page_id ) {
				$settings[ $page['setting'] ] = $page_id;
				$changed = true;
			}
		}

		if ( $changed ) {
			if ( class_exists( 'TSM_Settings' ) ) {
				TSM_Settings::update( $settings );
			} else {
				update_option( 'tsm_settings', $settings );
			}
			update_option( self::CREATED_OPTION, 1, false );
		}
	}

	protected static function ensure_page( $slug, $title, $shortcode ) {
		$existing = get_page_by_path( $slug );
		$page_id  = self::usable_page_id( $existing, $shortcode );
		if ( $page_id ) {
			return $page_id;
		}

		$existing = self::find_page_by_title( $title );
		$page_id  = self::usable_page_id( $existing, $shortcode );
		if ( $page_id ) {
			return $page_id;
		}

		$id = wp_insert_post(
			array(
				'post_title'   => $title,
				'post_name'    => $slug,
				'post_status'  => 'publish',
				'post_type'    => 'page',
				'post_content' => $shortcode,
			),
			true
		);

		return ( $id && ! is_wp_error( $id ) ) ? (int) $id : 0;
	}

	protected static function usable_page_id( $page, $shortcode ) {
		if ( ! $page || 'page' !== get_post_type( $page ) ) {
			return 0;
		}

		$content = (string) $page->post_content;
		if ( false !== strpos( $content, $shortcode ) ) {
			return (int) $page->ID;
		}

		if ( '' === trim( wp_strip_all_tags( $content ) ) ) {
			wp_update_post(
				array(
					'ID'           => (int) $page->ID,
					'post_content' => $shortcode,
				)
			);
			return (int) $page->ID;
		}

		return 0;
	}

	protected static function find_page_by_title( $title ) {
		$pages = get_posts(
			array(
				'post_type'              => 'page',
				'post_status'            => array( 'publish', 'draft', 'private' ),
				'title'                  => $title,
				'posts_per_page'         => 1,
				'orderby'                => 'ID',
				'order'                  => 'ASC',
				'no_found_rows'          => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
			)
		);

		return $pages ? $pages[0] : null;
	}
}
