<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
<?php

namespace Elementor\Modules\DesignSystemSync\Classes;

use Exception;
use WP_REST_Server;
use WP_REST_Response;

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

class Controller {
	const API_NAMESPACE = 'elementor/v1';
	const API_BASE = 'design-system-sync';
	const HTTP_CREATED = 201;
	const HTTP_NO_CONTENT = 204;
	const HTTP_INTERNAL_SERVER_ERROR = 500;

	public function register_hooks() {
		add_action( 'rest_api_init', [ $this, 'register_routes' ] );
	}

	public function register_routes() {
		register_rest_route( self::API_NAMESPACE, '/' . self::API_BASE . '/stylesheet', [
			'methods' => WP_REST_Server::CREATABLE,
			'callback' => [ $this, 'generate' ],
			'permission_callback' => [ $this, 'has_permission' ],
		] );
	}

	public function generate(): WP_REST_Response {
		try {
			$stylesheet = new Stylesheet_Manager();
			$result = $stylesheet->generate();

			if ( null === $result ) {
				return new WP_REST_Response( null, self::HTTP_NO_CONTENT );
			}

			return new WP_REST_Response( $result, self::HTTP_CREATED );
		} catch ( Exception $e ) {
			return new WP_REST_Response(
				[ 'message' => $e->getMessage() ],
				self::HTTP_INTERNAL_SERVER_ERROR
			);
		}
	}

	public function has_permission(): bool {
		return current_user_can( 'edit_posts' );
	}
}
