<?php
/**
 * Includes: Users
 */
if (!defined('ABSPATH')) {
    die('Sorry, you cannot access this page.');
}
add_action('admin_init', 'chama_resend_confirmation');
function chama_resend_confirmation()
{
    if (isset($_GET['resend_confirmation'])) {
        if (isset($_GET['chama_nonce']) && wp_verify_nonce(sanitize_key($_GET['chama_nonce']), 'chama_resend_confirmation_nonce')) {
            if (isset($_GET['user_id'])) {
                $user_id = sanitize_text_field(wp_unslash($_GET['user_id']));
                $user = get_userdata($user_id);
                $email = $user->user_email;
                chama_user_register($user_id, true);
                $message = 'A confirmation email has been sent to ' . $email;
                add_action('admin_notices', function () use ($message) {
                    echo '<div class="notice-success notice"><p>', esc_html($message), '</p></div>';
                });
            }

        }
    }

}
add_action('admin_init', 'chama_verify_user');
function chama_verify_user()
{
    if (isset($_GET['verify_user'])) {
        if (isset($_GET['chama_nonce']) && wp_verify_nonce(sanitize_key($_GET['chama_nonce']), 'chama_verify_user_nonce')) {
            if (isset($_GET['user_id'])) {
                $user_id = sanitize_text_field( wp_unslash($_GET['user_id']));
                $user = get_userdata($user_id);
                $email = $user->user_email;
                update_user_meta($user_id, 'is_email_verified', 1);
                $message = $email . ' has been manually verified.';
                add_action('admin_notices', function () use ($message) {
                    echo '<div class="notice-success notice"><p>', esc_html($message), '</p></div>';
                });
            }
        }
    }
}
function chama_users_action_links($actions, $user)
{

    // If the user doesn't have an ID, return.
    if (empty($user->ID)) {
        return $actions;
    }
    $is_email_verified = get_user_meta($user->ID, 'is_email_verified', true);
    if ($is_email_verified) {
        // Add the edit member link.
        $actions['verified'] = '<span class="0">Verified</span>';

    } else {
        $users_url = admin_url('users.php');
        $resend_confirmation_link = esc_url(add_query_arg(
            array(
                'user_id' => (int) $user->ID,
                'chama_nonce' => wp_create_nonce('chama_resend_confirmation_nonce'),
                'resend_confirmation' => true,
            ),
            $users_url
        ));
        $verify_user_link = esc_url(add_query_arg(
            array(
                'user_id' => (int) $user->ID,
                'chama_nonce' => wp_create_nonce('chama_verify_user_nonce'),
                'verify_user' => true,
            ),
            $users_url
        ));
        // Add user links.
        $actions['resend-confirmation'] = '<a href="' . $resend_confirmation_link . '">' . __('Resend Confirmation Email', 'chama') . '</a>';
        $actions['verify-user'] = '<a href="' . $verify_user_link . '">' . __('Verify User', 'chama') . '</a>';
    }

    return $actions;
}
add_filter('user_row_actions', 'chama_users_action_links', 10, 2);
function chama_populate_user_column($column)
{
    $column['is-email-verified'] = __('Email verified?', 'chama');
    $column['newsletter-optin'] = __('Newsletter Opt-in?', 'chama');
    return $column;
}
add_filter('manage_users_columns', 'chama_populate_user_column');
function chama_add_custom_user_columns($val, $column_name, $user_id)
{
    switch ($column_name) {
        case 'is-email-verified':
            $is_email_verified = get_user_meta($user_id, 'is_email_verified', true);
            if (!empty($is_email_verified)) {
                return 'yes';
            } else {
                return 'no';
            }
            break;
        case 'newsletter-optin':
            $is_opted_in = get_user_meta($user_id, 'newsletter_optin', true);
            if (! empty($is_opted_in)) {
                return 'yes';
            } else {
                return 'no';
            }
            break;
        default:
    }
    return $val;
}
add_filter('manage_users_custom_column', 'chama_add_custom_user_columns', 10, 3);

function chama_on_remove_user_from_role($user_id, $role)
{
    if (is_admin() && current_user_can('manage_options')) {
        $current_analytics_total = 0;
        switch ($role) {
            case 'chama_donor':
                $analytics_option = 'chama_total_donors';
                break;
            case 'chama_member':
                $analytics_option = 'chama_total_members';
                break;
            case 'chama_funder':
                $analytics_option = 'chama_total_funders';
                break;
            case 'chama_comissioner':
                $analytics_option = 'chama_total_commissioners';
                break;
            default:
        }
        $current_analytics_total = get_option($analytics_option) ? get_option($analytics_option) : 0;
        $new_analytics_total = $current_analytics_total - 1;
        update_option($analytics_option, $new_analytics_total);
    }
}
// Add the action
add_action("remove_user_role", "chama_on_remove_user_from_role", 10, 2);
function chama_on_add_user_from_role($user_id, $role)
{
    if (is_admin() && current_user_can('manage_options')) {
        $current_analytics_total = 0;
        switch ($role) {
            case 'chama_donor':
                $analytics_option = 'chama_total_donors';
                break;
            case 'chama_member':
                $analytics_option = 'chama_total_members';
                break;
            case 'chama_funder':
                $analytics_option = 'chama_total_funders';
                break;
            case 'chama_comissioner':
                $analytics_option = 'chama_total_commissioners';
                break;
            default:
        }
        $current_analytics_total = get_option($analytics_option) ? get_option($analytics_option) : 0;
        $new_analytics_total = $current_analytics_total + 1;
        update_option($analytics_option, $new_analytics_total);
    }

}
// Add the action
add_action("add_user_role", "chama_on_add_user_from_role", 10, 2);

function chama_on_delete_user($user_id)
{
    try {
        //remove user from role
        $user = $user_id ? get_user_by('id', $user_id) : false;
        if ($user) {
            $user->remove_role('chama_donor');
            $user->remove_role('chama_member');
            $user->remove_role('chama_funder');
            $user->remove_role('chama_comissioner');
        }
        //remove all payments
        global $wpdb;
        $result = $wpdb->query(// check
            $wpdb->prepare("
            DELETE posts,pt,pm
            FROM {$wpdb->posts}  posts
            LEFT JOIN {$wpdb->term_relationships} pt ON pt.object_id = posts.ID
            LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = posts.ID
            WHERE pm.meta_key = 'chama_user_id' AND pm.meta_value = %d
            ",
                $user_id
            )
        );

    } catch (Exception $e) {

        wp_die(esc_html($e->getMessage()));
    }
}
add_action("delete_user", "chama_on_delete_user", 10, 2);
