<?php

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

class AIEO_Event_RSVP {

    const QVAR           = 'aieo_rsvp_token';
    const REWRITE_OPTION = 'aieo_event_rsvp_rewrite_v1';
    const NONCE_PREFIX   = 'aieo_rsvp_';

    private static $registered = false;

    public static function register() {
        if (self::$registered) { return; }
        self::$registered = true;
        add_action('init', array(__CLASS__, 'add_rewrite'), 20); 
        add_filter('query_vars', array(__CLASS__, 'add_query_var'));
        
        
        
        add_action('template_redirect', array(__CLASS__, 'maybe_handle'), 0);
    }

    
    public static function add_rewrite() {
        add_rewrite_rule('^event-rsvp/([0-9a-fA-F]{64})/?$', 'index.php?' . self::QVAR . '=$matches[1]', 'top');
        if (get_option(self::REWRITE_OPTION) !== '1') {
            flush_rewrite_rules(false);
            update_option(self::REWRITE_OPTION, '1', false);
        }
    }

    public static function add_query_var($vars) {
        $vars[] = self::QVAR;
        return $vars;
    }

    
    public static function url($token) {
        $token = strtolower(preg_replace('/[^0-9a-fA-F]/', '', (string) $token));
        return home_url('/event-rsvp/' . $token . '/');
    }

    public static function maybe_handle() {
        $token = get_query_var(self::QVAR);
        if (empty($token)) { return; }
        $token = strtolower((string) $token);

        nocache_headers();

        if (!preg_match('/^[0-9a-f]{64}$/', $token) || !class_exists('AIEO_Event_Participants')) {
            self::render_invalid();
        }
        $p = AIEO_Event_Participants::get_by_token($token);
        if (!$p) { self::render_invalid(); }

        $event = get_post((int) $p->event_id);
        if (!$event || !class_exists('AIEO_Event_CPT') || $event->post_type !== AIEO_Event_CPT::POST_TYPE || $event->post_status === 'trash') {
            self::render_invalid();
        }

        $closed = self::is_closed((int) $event->ID);

        
        
        
        $just = '';
        if (!$closed
            && isset($_SERVER['REQUEST_METHOD']) && strtoupper((string) $_SERVER['REQUEST_METHOD']) === 'POST'
            && isset($_POST['aieo_rsvp_do'], $_POST['_wpnonce'])
            && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), self::NONCE_PREFIX . $token)
        ) {
            $do = sanitize_key(wp_unslash($_POST['aieo_rsvp_do']));
            if (in_array($do, array('confirm', 'decline'), true)) {
                AIEO_Event_Participants::set_status_by_token($token, ($do === 'confirm') ? 'confirmed' : 'declined');
                $p    = AIEO_Event_Participants::get_by_token($token); 
                $just = ($do === 'confirm') ? 'confirmed' : 'declined';
            }
        }

        self::render_page($p, $event, $closed, $just);
    }

    private static function is_closed($event_id) {
        $deadline = (string) get_post_meta($event_id, AIEO_Event_CPT::META_RSVP_DEADLINE, true);
        if ($deadline === '') { return false; }
        return current_time('mysql') > $deadline; 
    }

    

    
    private static function greeting($p) {
        $sal = trim((string) $p->salutation);
        if ($sal !== '') { return $sal; }
        $name = trim(trim((string) $p->title) . ' ' . trim((string) $p->first_name) . ' ' . trim((string) $p->last_name));
        if ($name !== '') { return sprintf(__('Dear %s', 'ai-eshop-optimizer'), $name); }
        return __('Hello', 'ai-eshop-optimizer');
    }

    private static function status_line($status) {
        if ($status === 'confirmed') { return __('Your current response: attending.', 'ai-eshop-optimizer'); }
        if ($status === 'declined')  { return __('Your current response: not attending.', 'ai-eshop-optimizer'); }
        return __('You have not responded yet.', 'ai-eshop-optimizer');
    }

    private static function render_invalid() {
        status_header(404);
        self::shell(
            __('Invitation not found', 'ai-eshop-optimizer'),
            '<p class="aieo-rsvp-current">' . esc_html__('This RSVP link is invalid or has expired. Please use the exact link from your invitation email, or contact us.', 'ai-eshop-optimizer') . '</p>'
        );
    }

    private static function render_page($p, $event, $closed, $just) {
        status_header(200);
        $title     = get_the_title($event);
        $start     = AIEO_Event_CPT::fmt_dt(get_post_meta($event->ID, AIEO_Event_CPT::META_START, true));
        $location  = (string) get_post_meta($event->ID, AIEO_Event_CPT::META_LOCATION, true);
        $status    = (string) $p->rsvp_status;
        $permalink = get_permalink($event);

        ob_start();

        echo '<p class="aieo-rsvp-greet">' . esc_html(self::greeting($p)) . '</p>';
        echo '<h1 class="aieo-rsvp-event">' . esc_html($title !== '' ? $title : __('You’re invited', 'ai-eshop-optimizer')) . '</h1>';

        $map_url = class_exists('AIEO_Event_CPT') ? AIEO_Event_CPT::map_url($event->ID) : '';
        echo '<ul class="aieo-rsvp-facts">';
        if ($start !== '')    { echo '<li><strong>' . esc_html__('When', 'ai-eshop-optimizer') . ':</strong> ' . esc_html($start) . '</li>'; }
        if ($location !== '') {
            echo '<li><strong>' . esc_html__('Where', 'ai-eshop-optimizer') . ':</strong> ' . esc_html($location);
            if ($map_url !== '') {
                echo ' &middot; <a href="' . esc_url($map_url) . '" target="_blank" rel="noopener">' . esc_html__('View on map', 'ai-eshop-optimizer') . '</a>';
            }
            echo '</li>';
        } elseif ($map_url !== '') {
            echo '<li><a href="' . esc_url($map_url) . '" target="_blank" rel="noopener">' . esc_html__('View on map', 'ai-eshop-optimizer') . '</a></li>';
        }
        echo '</ul>';

        if (isset($_GET['registered']) && $just === '') { 
            echo '<div class="aieo-rsvp-msg aieo-rsvp-yes">' . esc_html__('Thanks for registering! You can confirm or change your response below.', 'ai-eshop-optimizer') . '</div>';
        }

        if ($just === 'confirmed') {
            echo '<div class="aieo-rsvp-msg aieo-rsvp-yes">' . esc_html__('Your attendance is confirmed — thank you! We look forward to welcoming you.', 'ai-eshop-optimizer') . '</div>';
        } elseif ($just === 'declined') {
            echo '<div class="aieo-rsvp-msg aieo-rsvp-no">' . esc_html__('Thank you for letting us know you can’t make it. We hope to see you at a future event.', 'ai-eshop-optimizer') . '</div>';
        }

        if ($closed) {
            echo '<p class="aieo-rsvp-closed">' . esc_html__('The RSVP period for this event has closed.', 'ai-eshop-optimizer') . '</p>';
            echo '<p class="aieo-rsvp-current">' . esc_html(self::status_line($status)) . '</p>';
        } else {
            echo '<p class="aieo-rsvp-prompt">' . esc_html__('Will you attend?', 'ai-eshop-optimizer') . '</p>';
            $nonce = wp_create_nonce(self::NONCE_PREFIX . strtolower((string) $p->rsvp_token));
            echo '<form method="post" action="' . esc_url(self::url($p->rsvp_token)) . '" class="aieo-rsvp-actions">';
            echo '<input type="hidden" name="_wpnonce" value="' . esc_attr($nonce) . '">';
            echo '<button type="submit" name="aieo_rsvp_do" value="confirm" class="aieo-rsvp-btn aieo-rsvp-btn-yes' . ($status === 'confirmed' ? ' is-active' : '') . '">' . esc_html__('Yes, I’ll attend', 'ai-eshop-optimizer') . '</button>';
            echo '<button type="submit" name="aieo_rsvp_do" value="decline" class="aieo-rsvp-btn aieo-rsvp-btn-no' . ($status === 'declined' ? ' is-active' : '') . '">' . esc_html__('No, I can’t make it', 'ai-eshop-optimizer') . '</button>';
            echo '</form>';
            if ($status !== 'invited') {
                echo '<p class="aieo-rsvp-current">' . esc_html(self::status_line($status)) . ' ' . esc_html__('You can change your response above.', 'ai-eshop-optimizer') . '</p>';
            }
        }

        if ($permalink) {
            echo '<p class="aieo-rsvp-viewlink"><a href="' . esc_url($permalink) . '">' . esc_html__('View event details', 'ai-eshop-optimizer') . ' &rarr;</a></p>';
        }

        self::shell($title !== '' ? $title : __('Event RSVP', 'ai-eshop-optimizer'), ob_get_clean());
    }

    
    private static function shell($title, $body_html) {
        $site = get_bloginfo('name');
        header('Content-Type: text/html; charset=utf-8');
        ?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title><?php echo esc_html($title . ' — ' . $site); ?></title>
<style>
*{box-sizing:border-box}
body.aieo-rsvp-body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f4f1ee;color:#2b2b2b;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;line-height:1.6;padding:24px}
.aieo-rsvp-card{background:#fff;max-width:560px;width:100%;border-radius:14px;box-shadow:0 10px 40px rgba(0,0,0,.08);padding:36px 32px;text-align:center}
.aieo-rsvp-head{font-size:13px;letter-spacing:.14em;text-transform:uppercase;color:#9a8f86;font-weight:600;margin-bottom:22px;border-bottom:1px solid #efeae5;padding-bottom:14px}
.aieo-rsvp-greet{font-size:18px;font-weight:600;margin:0 0 2px}
.aieo-rsvp-event{font-size:25px;line-height:1.25;margin:8px 0 14px;color:#1a1a1a}
.aieo-rsvp-facts{list-style:none;padding:0;margin:0 0 20px;color:#555;font-size:15px}
.aieo-rsvp-facts li{margin:3px 0}
.aieo-rsvp-prompt{font-size:17px;font-weight:600;margin:18px 0 14px}
.aieo-rsvp-actions{display:flex;gap:12px;justify-content:center;flex-wrap:wrap;margin:0 0 8px}
.aieo-rsvp-btn{appearance:none;-webkit-appearance:none;border:2px solid transparent;border-radius:9px;padding:13px 22px;font-size:15px;font-weight:600;cursor:pointer;transition:.15s;min-width:175px}
.aieo-rsvp-btn-yes{background:#1f8a4c;color:#fff}
.aieo-rsvp-btn-yes:hover{background:#176c3b}
.aieo-rsvp-btn-no{background:#fff;color:#9a3a36;border-color:#e3cfce}
.aieo-rsvp-btn-no:hover{background:#fbf4f3}
.aieo-rsvp-btn.is-active{outline:3px solid rgba(31,138,76,.25);outline-offset:1px}
.aieo-rsvp-btn-no.is-active{outline-color:rgba(154,58,54,.22)}
.aieo-rsvp-msg{border-radius:9px;padding:14px 16px;margin:16px 0;font-weight:600}
.aieo-rsvp-yes{background:#e8f5ec;color:#1f7a45}
.aieo-rsvp-no{background:#fbeeed;color:#9a3a36}
.aieo-rsvp-closed{background:#fdf6e3;color:#8a6d1a;border-radius:9px;padding:12px 14px;font-weight:600}
.aieo-rsvp-current{color:#777;font-size:14px;margin:10px 0 0}
.aieo-rsvp-viewlink{margin-top:22px}
.aieo-rsvp-viewlink a{color:#8a7a6e;text-decoration:none;font-size:14px}
.aieo-rsvp-viewlink a:hover{text-decoration:underline}
</style>
</head>
<body class="aieo-rsvp-body">
<main class="aieo-rsvp-card">
<div class="aieo-rsvp-head"><?php echo esc_html($site); ?></div>
<?php echo $body_html; ?>
</main>
</body>
</html>
<?php
        exit;
    }
}
