<?php
declare(strict_types=1);

namespace EHxMe\Classes;

use EHxMe\Helpers\Helper;
use EHxMe\Models\Payment;
use EHxMe\Models\User;
use EHxMe\Services\Request;

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

class AdminActionHandler
{
    /**
     * Constructor for AdminActionHandler class.
     *
     * Initializes the AdminActionHandler class and sets up necessary actions and properties.
     *
     * @return void
     */
    public function __construct() 
    {
        // Add a new menu page to the WordPress admin dashboard
        add_action('admin_menu', [$this, 'addMenu'], 999);

        // Handle user status toggle action
        add_action('admin_init', [$this, 'deleteTableRow']);
        add_action('admin_init', [$this, 'memberStatusUpdate']);
    }

    /**
     * Adds a new menu page to the WordPress admin dashboard.
     *
     * This function creates a new menu page with the title 'User Details' and the slug 'ehxmember_user_view'.
     * The page is associated with the 'render_user_view_page' method of the current class.
     * The menu item is visible to users with the 'manage_options' capability.
     * The menu icon is provided by the 'dashicons-admin-users' Dashicon.
     * After adding the menu page, it removes the existing 'ehxmember_user_view' menu page.
     *
     * @return void
     */
    public function addMenu()
    {
        add_submenu_page(
            AdminMenuHandler::$pages['admin'],
            esc_html__('User Details', 'ehx-members'),
            esc_html__('User Details', 'ehx-members'),
            'manage_options',
            AdminMenuHandler::$pages['user_details'],
            [$this, 'renderUserViewPage'],
        );
    }

    /**
     * Renders the user view page.
     *
     * This function retrieves the user ID from the request, validates it, retrieves the user data,
     * and then includes the user details view template. If the user ID is invalid or the user is not found,
     * appropriate error messages are displayed.
     * 
     * @return void
     */
    public function renderUserViewPage() 
    {
        $user_id = (int) Request::getInput('user_id');

        if (!$user_id) {
            echo '<div class="notice notice-error"><p>' . esc_html__('Invalid user ID.', 'ehx-members') . '</p></div>';
            return;
        }

        $user = get_userdata($user_id);

        if (!$user) {
            echo '<div class="notice notice-error"><p>' . esc_html__('User not found.', 'ehx-members') . '</p></div>';
            return;
        }

        $userData = [
            ['label' => esc_html__('Username', 'ehx-members'), 'value' => $user->user_login],
            ['label' => esc_html__('Email', 'ehx-members'), 'value' => $user->user_email],
            ['label' => esc_html__('Full name', 'ehx-members'), 'value' => $user->display_name],
            ['label' => esc_html__('Role', 'ehx-members'), 'value' => Helper::memberRole($user->roles)],
            ['label' => esc_html__('Status', 'ehx-members'), 'value' => Helper::memberStatus((bool) $user->user_status)],
        ];

        $user_meta = get_user_meta($user_id, 'ehxme_user', true);

        require EHXME_PLUGIN_DIR . 'views/admin/pages/user-details.php';
    }

    /**
     * Handles the deletion of a user.
     * This function checks if the current user has the necessary capabilities to delete a user and then proceeds with the deletion.
     * It also performs necessary checks and redirects to the appropriate admin page after the deletion.
     *
     * @param int $user_id The ID of the user to be deleted.
     * @param string $action The action to be performed. It should be 'memberDelete' for this function to execute.
     *
     * @return void
     */
    public function deleteTableRow()
    {
        $id = (int) Request::getInput('id');
        $action  = Request::getInput('action');

        $deleted = false;
        if ($action === 'ehxme_member_delete') {

            if (!current_user_can('delete_users', $id)) {
                wp_die('Permission denied');
            }

            wp_delete_user($id);

            $deleted = true;
        }

        if ($action === 'ehxme_payments_delete') {

            $payment = (new Payment)->where('id', $id)->delete();
            if(!$payment) {
                Helper::show_404();
            }
            $deleted = true;
        }
        
        if($deleted) {
            $page  = Request::getInput('page');
            wp_redirect(admin_url("admin.php?page={$page}&deleted=1"));
            exit;
        }
    }

    /**
     * Handles the user status toggle action.
     * This function is responsible for activating or deactivating a user's status based on the provided action.
     * It checks if the current user has the necessary capabilities to perform the action and then toggles the user's status.
     *
     * @param int $user_id The ID of the user whose status needs to be toggled.
     * @param string $action The action to be performed (toggle_status).
     *
     * @return void
     */
    public function memberStatusUpdate()
    {
        $user_id = (int) Request::getInput('user_id');
        $action  = Request::getInput('action');
        $page    = Request::getInput('page');

        if ($action === 'ehxme_status_update') {

            if (!current_user_can('edit_users', $user_id)) {
                wp_die('Permission denied');
            }

            $user = get_user($user_id);
            
            (new User())->update($user_id, ['user_status' => $user->user_status ? false : true]);

            wp_redirect(admin_url("admin.php?page={$page}&status_updated=1"));

            exit;
        }
    }
}