<?php

namespace RtmBusiness\PostSync\Pages;

use WordpressModels\Assets;
use WordpressModels\Page;

class PermissionsPage extends Page
{


    /**
     * @param Assets $assets
     */
    public function __construct(Assets $assets)
    {
        parent::__construct('permissions', 'postsync-permissions', 'Permissions', 'postsync-settings', 'administrator', null, '', [], $assets);
    }

    /**
     * @inheritDoc
     */
    public function buildContext(array $context = []): mixed
    {
        $users = get_users();
        $blogUserCapabilities = [];

        // Fetch all sites in the network
        $sites = get_sites();

        $blog_details = [];
        foreach ($sites as $site) {
            $blog_details[$site->blog_id] = [
                'name' => $site->blogname,
                'id' => $site->blog_id
            ];
        }

        $userCapabilities = [];

        foreach ($users as $user) {
            // Switch to the blog
            foreach ($blog_details as $blog_detail) {
                $blogId = $blog_detail['id'];

                switch_to_blog($blogId);

                $userCapabilities[$blogId]["postsync_can_publish"] = user_can($user->ID, "postsync_can_publish");
                $userCapabilities[$blogId]["postsync_can_disconnect"] = user_can($user->ID, "postsync_can_disconnect");
                $userCapabilities[$blogId]["postsync_can_trashrestore"] = user_can($user->ID, "postsync_can_trashrestore");
                $userCapabilities[$blogId]["postsync_can_permdelete"] = user_can($user->ID, "postsync_can_permdelete");

                // Switch back to the original blog
                restore_current_blog();
            }

            $blogUserCapabilities[$user->user_login] = $userCapabilities;
        }

        $context['blogUserCapabilities'] = $blogUserCapabilities;
        $context['blog_details'] = $blog_details;

        return $context;
    }


    /**
     * @return void
     */
    public function doEnqueue()
    {
        wp_localize_script('permissions', 'WP_REST', [
            'url' => get_rest_url(),
            'nonce' => wp_create_nonce('wp_rest'),
            'debug' => wp_get_environment_type() === 'development'
        ]);
    }
}
