<?php
namespace eazyDocsPro\Admin;

/**
 * Class Doc_Visibility
 */
class Doc_Visibility {
	public function __construct() {
		add_action( 'admin_init', [ $this, 'ezd_doc_visibility' ] );
	}

	public function ezd_doc_visibility() {
		if (
			isset( $_GET['doc_visibility'], $_GET['doc_visibility_type'], $_GET['_wpnonce'] ) &&
			wp_verify_nonce( sanitize_text_field( $_GET['_wpnonce'] ), sanitize_text_field( $_GET['doc_visibility'] ) )
		) {
			// Check user capabilities
			if ( ! current_user_can( 'edit_posts' ) ) {
				wp_die( esc_html__( 'You do not have permission to perform this action.', 'eazydocs-pro' ) );
			}

			$doc_id              = absint( $_GET['doc_visibility'] );
			$visibility_type     = sanitize_text_field( $_GET['doc_visibility_type'] );
			$doc_password_input  = '';

			if ( $visibility_type === 'protected' ) {
				$doc_password_input = isset( $_GET['doc_password_input'] ) ? sanitize_text_field( str_replace( ';hash;', '#', $_GET['doc_password_input'] ) ) : '';
				$visibility_type    = 'publish';
			}

			if ( $doc_id ) {
				$this->ezd_apply_visibility_recursive( $doc_id, $visibility_type, $doc_password_input );
				wp_safe_redirect( admin_url( 'admin.php?page=eazydocs' ) );
				exit;
			}
		}
	}

	private function ezd_apply_visibility_recursive( $post_id, $visibility_type, $password = '' ) {
		$post = get_post( $post_id );

		if ( $post && $post->post_type === 'docs' ) {
			$title_parts = explode( '#', $post->post_title );
			$title_clean = $title_parts[0];

			wp_update_post( [
				'ID'            => $post_id,
				'post_title'    => $title_clean,
				'post_status'   => $visibility_type,
				'post_password' => $password,
			] );

			$children = get_children( [
				'post_parent' => $post_id,
				'post_type'   => 'docs',
				'post_status' => 'any',
			] );

			foreach ( $children as $child ) {
				$this->ezd_apply_visibility_recursive( $child->ID, $visibility_type, $password );
			}
		}
	}
}