<?php
/**
 * Admin: menu, the three screens, handlers, upsell.
 *
 * Guideline 11: everything lives under the plugin's own menu; no site-wide
 * notices, no dashboard takeover.
 *
 * @package Upload_Vault
 */

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

/**
 * Class Uvgf_Admin
 */
class Uvgf_Admin {

	/**
	 * Wire hooks.
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
		add_action( 'admin_post_uvgf_run_audit', array( $this, 'handle_run_audit' ) );
		add_action( 'admin_post_uvgf_protect', array( $this, 'handle_protect' ) );
		add_action( 'admin_post_uvgf_unprotect', array( $this, 'handle_unprotect' ) );
		add_action( 'admin_post_uvgf_save_settings', array( $this, 'handle_save_settings' ) );
	}

	/**
	 * Menu.
	 */
	public function menu() {
		add_menu_page(
			__( 'Upload Vault', 'buildsbyluke-upload-vault-for-gravity-forms' ),
			__( 'Upload Vault', 'buildsbyluke-upload-vault-for-gravity-forms' ),
			'manage_options',
			'upload-vault-for-gravity-forms',
			array( $this, 'render_audit' ),
			'dashicons-lock',
			81
		);
		add_submenu_page( 'upload-vault-for-gravity-forms', __( 'Exposure Audit', 'buildsbyluke-upload-vault-for-gravity-forms' ), __( 'Exposure Audit', 'buildsbyluke-upload-vault-for-gravity-forms' ), 'manage_options', 'upload-vault-for-gravity-forms', array( $this, 'render_audit' ) );
		add_submenu_page( 'upload-vault-for-gravity-forms', __( 'Files', 'buildsbyluke-upload-vault-for-gravity-forms' ), __( 'Files', 'buildsbyluke-upload-vault-for-gravity-forms' ), 'manage_options', 'uvgf-files', array( $this, 'render_files' ) );
		add_submenu_page( 'upload-vault-for-gravity-forms', __( 'Settings', 'buildsbyluke-upload-vault-for-gravity-forms' ), __( 'Settings', 'buildsbyluke-upload-vault-for-gravity-forms' ), 'manage_options', 'uvgf-settings', array( $this, 'render_settings' ) );
	}

	/**
	 * Own-screen CSS only.
	 *
	 * @param string $hook Admin page hook.
	 */
	public function assets( $hook ) {
		if ( false === strpos( (string) $hook, 'upload-vault-for-gravity-forms' ) && false === strpos( (string) $hook, 'uvgf-' ) ) {
			return;
		}
		wp_enqueue_style( 'uvgf-admin', UVGF_URL . 'admin/css/uvgf-admin.css', array(), UVGF_VERSION );
	}

	/**
	 * Audit screen.
	 */
	public function render_audit() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		require UVGF_DIR . 'admin/views/audit.php';
	}

	/**
	 * Files screen.
	 */
	public function render_files() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		require UVGF_DIR . 'admin/views/files.php';
	}

	/**
	 * Settings screen.
	 */
	public function render_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		require UVGF_DIR . 'admin/views/settings.php';
	}

	/**
	 * The in-dashboard upsell — own pages only, unlicensed users only.
	 */
	public static function render_upsell() {
		if ( ! function_exists( 'uvgf_fs' ) || uvgf_fs()->can_use_premium_code() ) {
			return;
		}
		$trial   = uvgf_fs()->get_trial_url();
		$pricing = uvgf_fs()->get_upgrade_url();
		?>
		<div class="uvgf-upsell">
			<h2><?php esc_html_e( 'Share safely, prove who downloaded what', 'buildsbyluke-upload-vault-for-gravity-forms' ); ?></h2>
			<ul>
				<li><?php esc_html_e( 'Expiring signed share links — hand a client one file for 24 hours without creating a WordPress user', 'buildsbyluke-upload-vault-for-gravity-forms' ); ?></li>
				<li><?php esc_html_e( 'Per-form access rules + a download audit trail (who, when, what, allowed or denied) with CSV export', 'buildsbyluke-upload-vault-for-gravity-forms' ); ?></li>
				<li><?php esc_html_e( 'Retention auto-purge with preview — per-form maximum file age, with a dry run before anything is deleted', 'buildsbyluke-upload-vault-for-gravity-forms' ); ?></li>
				<li><?php esc_html_e( 'Slack & webhook alerts the moment an audit finds new exposure', 'buildsbyluke-upload-vault-for-gravity-forms' ); ?></li>
			</ul>
			<p>
				<a class="button button-primary" href="<?php echo esc_url( $trial ); ?>"><?php esc_html_e( 'Start 14-day free trial — no card', 'buildsbyluke-upload-vault-for-gravity-forms' ); ?></a>
				<a class="button" href="<?php echo esc_url( $pricing ); ?>"><?php esc_html_e( 'See plans', 'buildsbyluke-upload-vault-for-gravity-forms' ); ?></a>
			</p>
		</div>
		<?php
	}

	/**
	 * Success notice from the redirect message code, on our pages only. The
	 * selector is honoured only with the nonce the redirecting (itself
	 * nonce-checked) handler minted via notice_url().
	 */
	public static function render_notice() {
		$msg = '';
		if (
			isset( $_GET['uvgf_msg'], $_GET['uvgf_msg_nonce'] )
			&& false !== wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['uvgf_msg_nonce'] ) ), 'uvgf_msg' )
		) {
			$msg = sanitize_key( wp_unslash( $_GET['uvgf_msg'] ) );
		}
		if ( '' === $msg ) {
			return;
		}
		$map = array(
			'audited'     => __( 'Audit complete.', 'buildsbyluke-upload-vault-for-gravity-forms' ),
			'protected'   => __( 'Protection rules installed. The audit below shows what the server now actually serves.', 'buildsbyluke-upload-vault-for-gravity-forms' ),
			'unprotected' => __( 'Protection rules removed — direct access is back to Gravity Forms\' stock behaviour.', 'buildsbyluke-upload-vault-for-gravity-forms' ),
			'saved'       => __( 'Settings saved.', 'buildsbyluke-upload-vault-for-gravity-forms' ),
		);
		if ( isset( $map[ $msg ] ) ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $map[ $msg ] ) . '</p></div>';
		}
	}

	/**
	 * Redirect target carrying a notice code and the nonce render_notice()
	 * requires for it.
	 *
	 * @param string $msg Notice code (see render_notice()).
	 * @param string $url Base admin URL.
	 * @return string
	 */
	public static function notice_url( $msg, $url ) {
		return add_query_arg(
			array(
				'uvgf_msg'       => $msg,
				'uvgf_msg_nonce' => wp_create_nonce( 'uvgf_msg' ),
			),
			$url
		);
	}

	// ------------------------------------------------------------------
	// Handlers (admin-post): nonce + capability, then redirect.
	// ------------------------------------------------------------------

	/**
	 * "Audit now".
	 */
	public function handle_run_audit() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'buildsbyluke-upload-vault-for-gravity-forms' ) );
		}
		check_admin_referer( 'uvgf_run_audit' );
		Uvgf_Auditor::audit();
		wp_safe_redirect( self::notice_url( 'audited', admin_url( 'admin.php?page=upload-vault-for-gravity-forms' ) ) );
		exit;
	}

	/**
	 * Install protection, then re-audit so the verdict reflects served reality.
	 */
	public function handle_protect() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'buildsbyluke-upload-vault-for-gravity-forms' ) );
		}
		check_admin_referer( 'uvgf_protect' );
		Uvgf_Protector::protect();
		Uvgf_Auditor::audit();
		wp_safe_redirect( self::notice_url( 'protected', admin_url( 'admin.php?page=upload-vault-for-gravity-forms' ) ) );
		exit;
	}

	/**
	 * Remove protection, then re-audit.
	 */
	public function handle_unprotect() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'buildsbyluke-upload-vault-for-gravity-forms' ) );
		}
		check_admin_referer( 'uvgf_unprotect' );
		Uvgf_Protector::unprotect();
		Uvgf_Auditor::audit();
		wp_safe_redirect( self::notice_url( 'unprotected', admin_url( 'admin.php?page=upload-vault-for-gravity-forms' ) ) );
		exit;
	}

	/**
	 * Settings save.
	 */
	public function handle_save_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'buildsbyluke-upload-vault-for-gravity-forms' ) );
		}
		check_admin_referer( 'uvgf_save_settings' );

		$email = isset( $_POST['uvgf_alert_email'] ) ? sanitize_email( wp_unslash( $_POST['uvgf_alert_email'] ) ) : '';

		$recurrence = isset( $_POST['uvgf_audit_recurrence'] ) ? sanitize_key( wp_unslash( $_POST['uvgf_audit_recurrence'] ) ) : 'weekly';
		if ( ! in_array( $recurrence, Uvgf_Plugin::recurrences(), true ) ) {
			$recurrence = 'weekly';
		}

		$open = array();
		if ( isset( $_POST['uvgf_open_form_dirs'] ) && is_array( $_POST['uvgf_open_form_dirs'] ) ) {
			// Read each key inline and sanitised: the raw array never becomes a
			// variable and never crosses a hook (R15 / Entry 6).
			foreach ( array_keys( $_POST['uvgf_open_form_dirs'] ) as $uvgf_i ) {
				if ( is_array( $_POST['uvgf_open_form_dirs'][ $uvgf_i ] ) ) {
					continue; // A nested array is not a folder name.
				}
				$clean = sanitize_file_name( wp_unslash( $_POST['uvgf_open_form_dirs'][ $uvgf_i ] ) );
				if ( '' !== $clean ) {
					$open[] = $clean;
				}
			}
		}

		$settings = array(
			'alert_email'           => is_email( $email ) ? $email : get_option( 'admin_email' ),
			'weekly_audit'          => isset( $_POST['uvgf_weekly_audit'] ) ? 1 : 0,
			'audit_recurrence'      => $recurrence,
			'email_on_new'          => isset( $_POST['uvgf_email_on_new'] ) ? 1 : 0,
			'rewrite_entry_links'   => isset( $_POST['uvgf_rewrite_entry_links'] ) ? 1 : 0,
			'rewrite_notifications' => isset( $_POST['uvgf_rewrite_notifications'] ) ? 1 : 0,
			'open_form_dirs'        => array_values( array_unique( $open ) ),
		);
		update_option( 'uvgf_settings', $settings );

		Uvgf_Plugin::maybe_schedule();

		// Excluded-folder changes only take effect through the protector; refresh
		// rules if protection is currently installed.
		if ( Uvgf_Protector::rules_installed() ) {
			Uvgf_Protector::protect();
			Uvgf_Auditor::audit();
		}

		wp_safe_redirect( self::notice_url( 'saved', admin_url( 'admin.php?page=uvgf-settings' ) ) );
		exit;
	}
}
