<?php
/**
 * @package Hafenstudios\Kurato
 */

namespace Hafenstudios\Kurato\Cockpit\Rest;

use Hafenstudios\Kurato\Db\StageRepository;

defined( 'ABSPATH' ) || exit;

/**
 * GET kurato-cockpit/v1/session - Bootstrap fuer die App.
 *
 * Bearer-Ticket. Der Authenticator hat den Schattennutzer bereits gesetzt;
 * die Permission prueft nur die Kontakt-Lesebefugnis. Liefert Agent-Identitaet,
 * Capabilities, Site-Metadaten, Stufen-Liste und Plugin-Version.
 */
final class SessionController {

	public const REST_NAMESPACE = 'kurato-cockpit/v1';

	private StageRepository $stages;

	/**
	 * @param StageRepository $stages Stufen-Repository.
	 */
	public function __construct( StageRepository $stages ) {
		$this->stages = $stages;
	}

	/**
	 * @return void
	 */
	public function register_routes(): void {
		register_rest_route(
			self::REST_NAMESPACE,
			'/session',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'session' ),
				'permission_callback' => static function () {
					if ( current_user_can( 'hs_view_contacts' ) ) {
						return true;
					}
					return new \WP_Error(
						'invalid_ticket',
						__( 'Anmeldung nicht moeglich. Bitte melden Sie sich im Cockpit neu an.', 'kurato' ),
						array( 'status' => 401 )
					);
				},
			)
		);
	}

	/**
	 * @return \WP_REST_Response
	 */
	public function session(): \WP_REST_Response {
		$user = wp_get_current_user();

		return new \WP_REST_Response(
			array(
				'ok'             => true,
				'agent'          => array(
					'wp_user_id'   => (int) $user->ID,
					'display_name' => (string) $user->display_name,
					'email'        => (string) $user->user_email,
					'agent_id'     => (string) get_user_meta( (int) $user->ID, 'kurato_agent_id', true ),
				),
				'capabilities'   => array(
					'view_contacts'   => current_user_can( 'hs_view_contacts' ),
					'manage_contacts' => current_user_can( 'hs_manage_contacts' ),
					'send_mails'      => current_user_can( 'hs_send_mails' ),
					'manage_settings' => current_user_can( 'hs_manage_settings' ),
				),
				'site'           => array(
					'name'     => get_bloginfo( 'name' ),
					'url'      => home_url(),
					'timezone' => function_exists( 'wp_timezone_string' ) ? wp_timezone_string() : 'UTC',
				),
				'stages'         => $this->stages->all(),
				'contract'       => 'v1',
				'plugin_version' => defined( 'KURATO_VERSION' ) ? KURATO_VERSION : '',
			),
			200
		);
	}
}
