<?php
/**
 * TitanCart Notifications REST Controller
 *
 * Admin-only surface for the SPA notification bell (KI-26, S304).
 *
 *   GET  /titancart/v1/notifications            → { unread, items[] }  (bell fetch)
 *   GET  /titancart/v1/notifications/count       → { unread }           (lightweight poll)
 *   POST /titancart/v1/notifications/(?P<id>\d+)/read → mark one read
 *   POST /titancart/v1/notifications/read-all     → mark all read
 *
 * @package TitanCart\REST\Notifications
 */

namespace TitanCart\REST\Notifications;

use TitanCart\Modules\Notifications\NotificationManager;
use WP_REST_Request;
use WP_REST_Response;

defined( 'ABSPATH' ) || exit;

class NotificationsController {

	private string $ns = 'titancart/v1';
	private ?NotificationManager $mgr = null;

	private function mgr(): NotificationManager {
		if ( ! $this->mgr ) {
			$this->mgr = new NotificationManager();
		}
		return $this->mgr;
	}

	public function admin_check(): bool {
		return current_user_can( 'manage_options' );
	}

	public function register_routes(): void {

		register_rest_route( $this->ns, '/notifications', [
			'methods'             => 'GET',
			'callback'            => [ $this, 'list_notifications' ],
			'permission_callback' => [ $this, 'admin_check' ],
		] );

		register_rest_route( $this->ns, '/notifications/count', [
			'methods'             => 'GET',
			'callback'            => [ $this, 'count' ],
			'permission_callback' => [ $this, 'admin_check' ],
		] );

		register_rest_route( $this->ns, '/notifications/read-all', [
			'methods'             => 'POST',
			'callback'            => [ $this, 'read_all' ],
			'permission_callback' => [ $this, 'admin_check' ],
		] );

		register_rest_route( $this->ns, '/notifications/(?P<id>\d+)/read', [
			'methods'             => 'POST',
			'callback'            => [ $this, 'read_one' ],
			'permission_callback' => [ $this, 'admin_check' ],
		] );
	}

	public function list_notifications( WP_REST_Request $req ): WP_REST_Response {
		$limit = (int) ( $req->get_param( 'limit' ) ?: 20 );
		return new WP_REST_Response( $this->mgr()->summary( $limit ) );
	}

	public function count( WP_REST_Request $req ): WP_REST_Response {
		return new WP_REST_Response( [ 'unread' => $this->mgr()->get_unread_count() ] );
	}

	public function read_one( WP_REST_Request $req ): WP_REST_Response {
		$this->mgr()->mark_read( (int) $req['id'] );
		return new WP_REST_Response( [ 'ok' => true, 'unread' => $this->mgr()->get_unread_count() ] );
	}

	public function read_all( WP_REST_Request $req ): WP_REST_Response {
		$affected = $this->mgr()->mark_all_read();
		return new WP_REST_Response( [ 'ok' => true, 'marked' => $affected, 'unread' => 0 ] );
	}
}
