<?php

namespace EasyRestaurantManager\Http\Router;

use WP_REST_Server;
use WP_REST_Request;
use WP_Error;

class API_Router {
    private static $routes = [];

    /**
     * Register a GET route
     */
    public static function get($route, $callback) {
        self::add_route('GET', $route, $callback);
    }

    /**
     * Register a POST route (with Nonce Validation)
     */
    public static function post($route, $callback) {
        self::add_route('POST', $route, function (WP_REST_Request $request) use ($callback) {
            return call_user_func($callback, $request);
        });
    }

    /**
     * Register a PUT route (with Nonce Validation)
     */
    public static function put($route, $callback) {
        self::add_route('PUT', $route, function (WP_REST_Request $request) use ($callback) {
            return call_user_func($callback, $request);
        });
    }

    /**
     * Register a DELETE route (with Nonce Validation)
     */
    public static function delete($route, $callback) {
        self::add_route('DELETE', $route, function (WP_REST_Request $request) use ($callback) {
            return call_user_func($callback, $request);
        });
    }

    /**
     * Add route to list
     */
    private static function add_route($method, $route, $callback) {
        self::$routes[] = [
            'method' => $method,
            'route' => $route,
            'callback' => $callback
        ];
    }

    /**
     * Register all stored routes
     */
    public static function register_routes() {
        foreach (self::$routes as $route) {
            register_rest_route('easy-restaurant-manage/v1', $route['route'], [
                'methods'  => $route['method'],
                'callback' => $route['callback'],
                'permission_callback' => [self::class, 'admin_permission_check'], // Change this for custom permission checks
            ]);
        }
    }

    /**
     * Check if current user is admin
    */
    public static function admin_permission_check() {
        if (!is_user_logged_in()) {
            return new WP_Error('rest_forbidden', __('You must be logged in.', 'easy-restaurant-manager'), ['status' => 403]);
        }

        if (!current_user_can('manage_options')) {
            return new WP_Error('rest_forbidden', __('Admins only.', 'easy-restaurant-manager'), ['status' => 403]);
        }

        return true;
    }
}
