<?php

namespace PWH_DCFH\App\Admin\Controllers;

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('PWH_DCFH_User_Permissions_Handler')) {
    class PWH_DCFH_User_Permissions_Handler
    {
        /**
         * Initializer Of The Class
         * Add/Remove Necessary Actions/Filters
         */
        public function init()
        {
            add_action('wp_ajax_handle_user_permissions', [$this, 'maybe_update_permissions']);
            add_action('admin_init', [$this, 'update_admin_permissions']);
        }

        /**
         * Update Admin Permissions
         * @return void
         */
        public function update_admin_permissions()
        {
            if (get_option('_pwh_dcfh_default_permissions_beta') !== 'yes') {
                $admin_role = get_role('administrator');
                $permissions = $this->get_permissions();
                foreach ($permissions as $permission) {
                    foreach ($permission as $cap => $value) {
                        $admin_role->add_cap($cap);
                    }
                }
                update_option('_pwh_dcfh_default_permissions_beta', 'yes', 'no');
            }
        }

        /**
         * Update Permissions
         * @return void
         */
        public function maybe_update_permissions()
        {
            $permissions = $this->get_permissions();
            $form_data = $_POST['form_data'] ?? ''; // phpcs:ignore
            // Check if form data is present
            if (empty($form_data)) {
                return;
            }
            // Loop through roles and remove all capabilities
            $roles = get_editable_roles();
            $excluded_roles = ['administrator', 'subscriber'];
            foreach ($roles as $role_key => $role_info) {
                // Skip excluded roles
                if (in_array($role_key, $excluded_roles, true)) {
                    continue;
                }
                $role_object = get_role($role_key);
                foreach ($permissions as $permission) {
                    foreach ($permission as $cap => $value) {
                        $role_object->remove_cap($cap);
                    }
                }
            }
            // Parse form data
            parse_str($form_data, $form_array);
            // Check an if form array is empty
            if (empty($form_array)) {
                return; // No options to process
            }
            // Filter and process form options
            $options = array_filter($form_array, static function ($key) {
                return strpos($key, 'pwh_dcfh_permission_') === 0;
            }, ARRAY_FILTER_USE_KEY);
            // Check if options are present
            if (!empty($options)) {
                // Process each role and its associated capabilities
                foreach ($options as $role => $caps) {
                    $role_name = substr($role, strlen('pwh_dcfh_permission_'));
                    $admin_role = get_role($role_name);
                    // Add capabilities to role
                    foreach ($caps as $cap) {
                        if (isset($permissions[$cap])) {
                            foreach ($permissions[$cap] as $key => $permission) {
                                $admin_role->add_cap($key);
                            }
                        }
                    }
                }
            }
        }

        /**
         * Get Permissions
         * @return array[]
         */
        private function get_permissions()
        {
            return [
                'access_entries' => [
                    //'read_pwh_dcfh' => true,
                    //'edit_pwh_dcfh' => true,
                    //'edit_pwh_dcfhs' => true,
                    //'edit_others_pwh_dcfhs' => true,
                    'edit_draft_pwh_dcfh' => true,
                    'edit_draft_pwh_dcfhs' => true,
                    'edit_others_pwh_dcfhs' => true,
                    'edit_private_pwh_dcfh' => true,
                    'edit_private_pwh_dcfhs' => true,
                    'edit_published_pwh_dcfhs' => true,
                    'edit_pwh_dcfh' => true,
                    'edit_pwh_dcfhs' => true,
                    'publish_pwh_dcfhs' => true,
                    'read_draft_pwh_dcfhs' => true,
                    'read_private_pwh_dcfhs' => true,
                    'read_pwh_dcfh' => true,
                    // Custom Caps
                    'view_forms_pwh_dcfh' => true,
                ],
                'entry_actions' => [
                    'delete_others_pwh_dcfhs' => true,
                    'delete_private_pwh_dcfhs' => true,
                    'delete_published_pwh_dcfhs' => true,
                    'delete_pwh_dcfh' => true,
                    'delete_pwh_dcfhs' => true,
                    // Custom Caps
                    'perform_entry_actions_pwh_dcfh' => true,
                ],
                'export_csv' => [
                    'export_csv_pwh_dcfh' => true,
                ],
            ];
        }
    }
}