<?php

namespace WPSN\Admin;

use WPSN\Core\Capabilities;

defined('ABSPATH') || exit;

/**
 * Per-user override for external AI usage (OpenAI).
 *
 * This is intentionally kept small and safe:
 * - Only administrators (manage_options) can change overrides.
 * - The override wins over role caps (allow/deny).
 */
final class UserProfileAIPermissions
{
    public function register(): void
    {
        add_action('show_user_profile', [$this, 'render']);
        add_action('edit_user_profile', [$this, 'render']);

        add_action('personal_options_update', [$this, 'save']);
        add_action('edit_user_profile_update', [$this, 'save']);
    }

    /**
     * @param \WP_User $user
     */
    public function render($user): void
    {
        if (!$user instanceof \WP_User) {
            return;
        }

        // Only admins can change per-user overrides.
        if (!current_user_can('manage_options')) {
            return;
        }

        $modeUse = Capabilities::getUserAIUseOverride((int) $user->ID);
        $modeManage = Capabilities::getUserAIManageOverride((int) $user->ID);
        ?>
        <h2><?php echo esc_html__('WP SEO Next — AI Permissions', 'wp-seo-next'); ?></h2>
        <table class="form-table" role="presentation">
            <tr>
                <th><label for="wpsn_ai_use_override"><?php echo esc_html__('OpenAI access override', 'wp-seo-next'); ?></label></th>
                <td>
                    <select name="wpsn_ai_use_override" id="wpsn_ai_use_override">
                        <option value="inherit" <?php selected($modeUse, 'inherit'); ?>><?php echo esc_html__('Inherit role (default)', 'wp-seo-next'); ?></option>
                        <option value="allow" <?php selected($modeUse, 'allow'); ?>><?php echo esc_html__('Allow', 'wp-seo-next'); ?></option>
                        <option value="deny" <?php selected($modeUse, 'deny'); ?>><?php echo esc_html__('Deny', 'wp-seo-next'); ?></option>
                    </select>
                    <p class="description">
                        <?php
                            echo esc_html__('This overrides role-based permissions for external AI (OpenAI).', 'wp-seo-next');
                            echo ' ';
                            echo esc_html__('Allow = user can use OpenAI even if their role does not have wpsn_use_ai.', 'wp-seo-next');
                            echo ' ';
                            echo esc_html__('Deny = user cannot use OpenAI even if their role has wpsn_use_ai.', 'wp-seo-next');
                        ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th><label for="wpsn_ai_manage_override"><?php echo esc_html__('AI admin/tools access override', 'wp-seo-next'); ?></label></th>
                <td>
                    <select name="wpsn_ai_manage_override" id="wpsn_ai_manage_override">
                        <option value="inherit" <?php selected($modeManage, 'inherit'); ?>><?php echo esc_html__('Inherit role (default)', 'wp-seo-next'); ?></option>
                        <option value="allow" <?php selected($modeManage, 'allow'); ?>><?php echo esc_html__('Allow', 'wp-seo-next'); ?></option>
                        <option value="deny" <?php selected($modeManage, 'deny'); ?>><?php echo esc_html__('Deny', 'wp-seo-next'); ?></option>
                    </select>
                    <p class="description">
                        <?php
                            echo esc_html__('This overrides role-based permissions for AI admin/tools screens (capability: wpsn_manage_ai).', 'wp-seo-next');
                            echo ' ';
                            echo esc_html__('Allow = user can access SEO AI tools even if their role does not have wpsn_manage_ai.', 'wp-seo-next');
                            echo ' ';
                            echo esc_html__('Deny = user cannot access SEO AI tools even if their role has wpsn_manage_ai.', 'wp-seo-next');
                        ?>
                    </p>
                </td>
            </tr>
        </table>
        <?php
    }

    public function save(int $userId): void
    {
        $userId = (int) $userId;
        if ($userId <= 0) {
            return;
        }

        // Only admins can change per-user overrides.
        if (!current_user_can('manage_options')) {
            return;
        }

        if (!current_user_can('edit_user', $userId)) {
            return;
        }

        // OpenAI usage override
        if (isset($_POST['wpsn_ai_use_override'])) {
            $raw = sanitize_key((string) wp_unslash($_POST['wpsn_ai_use_override']));
            $old = Capabilities::getUserAIUseOverride($userId);

            Capabilities::setUserAIUseOverride($userId, $raw);

            $new = Capabilities::getUserAIUseOverride($userId);
            if ($new !== $old) {
                /**
                 * Fired when per-user AI override changes.
                 *
                 * @param int    $actorUserId   Who made the change.
                 * @param int    $targetUserId  User being changed.
                 * @param string $oldValue      allow|deny|inherit
                 * @param string $newValue      allow|deny|inherit
                 * @param string $scope         use|manage
                 */
                do_action('wpsn/ai/user_override_updated', (int) get_current_user_id(), $userId, $old, $new, 'use');
            }
        }

        // AI admin/tools override
        if (isset($_POST['wpsn_ai_manage_override'])) {
            $raw = sanitize_key((string) wp_unslash($_POST['wpsn_ai_manage_override']));
            $old = Capabilities::getUserAIManageOverride($userId);

            Capabilities::setUserAIManageOverride($userId, $raw);

            $new = Capabilities::getUserAIManageOverride($userId);
            if ($new !== $old) {
                do_action('wpsn/ai/user_override_updated', (int) get_current_user_id(), $userId, $old, $new, 'manage');
            }
        }
    }
}
