<?php
    if (! defined('ABSPATH')) {
        exit;
    }
    $opted_out = false;
    // This endpoint uses a secure, single-use verification code stored in user meta
    // and does not require a nonce because the request is initiated via a unique link
    // sent to the user's email (similar to WordPress password reset links).
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Token-based validation is handled below.
    $user_id = isset($_GET['uid']) ? absint($_GET['uid']) : 0;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Token-based validation is handled below.
    $code = isset($_GET['code']) ? sanitize_text_field(wp_unslash($_GET['code'])) : '';

    $saved_code = get_user_meta($user_id, 'optout_code', true);

    if ($saved_code && hash_equals($saved_code, $code)) {
        // Code is valid — verify email
        update_user_meta($user_id, 'newsletter_optin', 0);
        $opted_out = true;
    } else {
        //invalid verification code
        chama_errors()->add('invalid_opt_out_code', __('Invalid or expired opt out code', 'chama'));
    }
?>


    <div class="chama-card">
    <div class="chama-card-body">
	<?php
        // show any error messages
    chama_show_error_messages(); ?>
<?php if ($opted_out) {?>
            <h3>Unsubscription Successful</h3>
            <p>You've successfully unsubscribed from our newsletter. We're sorry to see you go!</p>
        <p>If you ever change your mind, feel free to subscribe again.</p>

            	<?php }?>


    </div>
    </div>
