<?php

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

class AIEO_Event_SelfReg {

    const ACTION = 'aieo_event_register';

    private static $registered = false;
    private static $style_done = false;

    public static function register() {
        if (self::$registered) { return; }
        self::$registered = true;
        add_shortcode('aieo_event_register', array(__CLASS__, 'shortcode'));
        add_action('admin_post_nopriv_' . self::ACTION, array(__CLASS__, 'handle'));
        add_action('admin_post_' . self::ACTION, array(__CLASS__, 'handle'));
    }

    
    public static function is_open($event_id) {
        if (class_exists('AIEO_Event_CPT') && method_exists('AIEO_Event_CPT', 'schedule_state')
            && AIEO_Event_CPT::schedule_state($event_id) === 'ended') {
            return false;
        }
        $deadline = (string) get_post_meta($event_id, AIEO_Event_CPT::META_RSVP_DEADLINE, true);
        if ($deadline !== '' && current_time('mysql') > $deadline) { return false; }
        return true;
    }

    public static function shortcode($atts) {
        $atts     = shortcode_atts(array('event_id' => 0), $atts, 'aieo_event_register');
        $event_id = (int) $atts['event_id'];
        if ($event_id <= 0) {
            $p = get_post();
            if ($p && class_exists('AIEO_Event_CPT') && $p->post_type === AIEO_Event_CPT::POST_TYPE) { $event_id = (int) $p->ID; }
        }
        if ($event_id <= 0 || !class_exists('AIEO_Event_CPT') || get_post_type($event_id) !== AIEO_Event_CPT::POST_TYPE) {
            return '';
        }
        return self::render_form($event_id);
    }

    public static function render_form($event_id) {
        if (!self::is_open($event_id)) {
            return self::style() . '<div class="aieo-selfreg aieo-selfreg--closed">' . esc_html__('Registration for this event is closed.', 'ai-eshop-optimizer') . '</div>';
        }

        $err = '';
        if (isset($_GET['aieo_reg_error'])) { 
            $err = self::error_text(sanitize_key(wp_unslash($_GET['aieo_reg_error'])));
        }

        ob_start();
        echo self::style(); 
        ?>
        <div class="aieo-selfreg">
            <h3 class="aieo-selfreg__title"><?php echo esc_html__('Register for this event', 'ai-eshop-optimizer'); ?></h3>
            <?php if ($err !== '') : ?><div class="aieo-selfreg__msg aieo-selfreg__msg--err"><?php echo esc_html($err); ?></div><?php endif; ?>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="aieo-selfreg__form">
                <input type="hidden" name="action" value="<?php echo esc_attr(self::ACTION); ?>">
                <input type="hidden" name="event_id" value="<?php echo esc_attr($event_id); ?>">
                <input type="hidden" name="redirect" value="<?php echo esc_url(get_permalink($event_id)); ?>">
                <div class="aieo-selfreg__hp" aria-hidden="true"><label><?php echo esc_html__('Website', 'ai-eshop-optimizer'); ?> <input type="text" name="aieo_hp" tabindex="-1" autocomplete="off"></label></div>
                <div class="aieo-selfreg__row">
                    <input type="text" name="first_name" placeholder="<?php echo esc_attr__('First name', 'ai-eshop-optimizer'); ?>" required>
                    <input type="text" name="last_name" placeholder="<?php echo esc_attr__('Last name', 'ai-eshop-optimizer'); ?>" required>
                </div>
                <div class="aieo-selfreg__row">
                    <input type="email" name="email" placeholder="<?php echo esc_attr__('Email', 'ai-eshop-optimizer'); ?>" required>
                </div>
                <div class="aieo-selfreg__row">
                    <input type="text" name="organization" placeholder="<?php echo esc_attr__('Organization (optional)', 'ai-eshop-optimizer'); ?>">
                    <input type="text" name="phone" placeholder="<?php echo esc_attr__('Phone (optional)', 'ai-eshop-optimizer'); ?>">
                </div>
                <button type="submit" class="aieo-selfreg__btn"><?php echo esc_html__('Register', 'ai-eshop-optimizer'); ?></button>
            </form>
        </div>
        <?php
        return ob_get_clean();
    }

    public static function handle() {
        $event_id = isset($_POST['event_id']) ? (int) $_POST['event_id'] : 0;
        $redirect = isset($_POST['redirect']) ? esc_url_raw(wp_unslash($_POST['redirect'])) : '';

        if ($event_id <= 0 || !class_exists('AIEO_Event_CPT') || get_post_type($event_id) !== AIEO_Event_CPT::POST_TYPE) {
            wp_safe_redirect(home_url('/'));
            exit;
        }
        if ($redirect === '') { $redirect = get_permalink($event_id); }

        $fail = static function ($code) use ($redirect) {
            wp_safe_redirect(add_query_arg('aieo_reg_error', $code, $redirect));
            exit;
        };

        if (!empty($_POST['aieo_hp']))   { $fail('spam'); }      
        if (!self::is_open($event_id))   { $fail('closed'); }

        
        $rk  = 'aieo_selfreg_' . md5(self::client_ip());
        $cnt = (int) get_transient($rk);
        if ($cnt >= 10) { $fail('rate'); }

        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        $first = isset($_POST['first_name']) ? sanitize_text_field(wp_unslash($_POST['first_name'])) : '';
        $last  = isset($_POST['last_name']) ? sanitize_text_field(wp_unslash($_POST['last_name'])) : '';
        if (!is_email($email))            { $fail('email'); }
        if ($first === '' && $last === '') { $fail('name'); }

        $org   = isset($_POST['organization']) ? sanitize_text_field(wp_unslash($_POST['organization'])) : '';
        $phone = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '';

        if (!class_exists('AIEO_Event_Participants')) { $fail('unavailable'); }

        
        
        
        $pid = AIEO_Event_Participants::upsert($event_id, array(
            'first_name'   => $first,
            'last_name'    => $last,
            'email'        => $email,
            'organization' => $org,
            'phone'        => $phone,
            'rsvp_status'  => 'confirmed',
        ), 'self-registered', 0, '');

        set_transient($rk, $cnt + 1, HOUR_IN_SECONDS);

        if ($pid <= 0) { $fail('save'); }

        
        if (class_exists('AIEO_Event_RSVP')) {
            global $wpdb;
            $token = $wpdb->get_var($wpdb->prepare(
                'SELECT rsvp_token FROM ' . AIEO_Event_Participants::table() . ' WHERE participant_id = %d',
                (int) $pid
            ));
            if ($token) {
                wp_safe_redirect(add_query_arg('registered', '1', AIEO_Event_RSVP::url($token)));
                exit;
            }
        }
        wp_safe_redirect(add_query_arg('aieo_reg', 'ok', $redirect));
        exit;
    }

    

    private static function client_ip() {
        foreach (array('HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR') as $k) {
            if (!empty($_SERVER[$k])) {
                $parts = explode(',', (string) wp_unslash($_SERVER[$k]));
                $ip    = trim($parts[0]);
                if (filter_var($ip, FILTER_VALIDATE_IP)) { return $ip; }
            }
        }
        return '0.0.0.0';
    }

    private static function error_text($code) {
        $map = array(
            'spam'        => __('Your submission could not be processed.', 'ai-eshop-optimizer'),
            'closed'      => __('Registration for this event is closed.', 'ai-eshop-optimizer'),
            'rate'        => __('Too many attempts. Please try again later.', 'ai-eshop-optimizer'),
            'email'       => __('Please enter a valid email address.', 'ai-eshop-optimizer'),
            'name'        => __('Please enter your name.', 'ai-eshop-optimizer'),
            'save'        => __('Sorry, we could not complete your registration. Please try again.', 'ai-eshop-optimizer'),
            'unavailable' => __('Registration is temporarily unavailable.', 'ai-eshop-optimizer'),
        );
        return isset($map[$code]) ? $map[$code] : __('Please check your details and try again.', 'ai-eshop-optimizer');
    }

    private static function style() {
        if (self::$style_done) { return ''; }
        self::$style_done = true;
        return '<style>'
            . '.aieo-selfreg{max-width:560px;margin:24px 0;padding:24px;border:1px solid #e6e0da;border-radius:12px;background:#fff;}'
            . '.aieo-selfreg__title{margin:0 0 14px;font-size:20px;}'
            . '.aieo-selfreg__hp{position:absolute!important;left:-9999px!important;width:1px;height:1px;overflow:hidden;}'
            . '.aieo-selfreg__row{display:flex;gap:12px;flex-wrap:wrap;margin:0 0 12px;}'
            . '.aieo-selfreg__row input{flex:1;min-width:180px;padding:11px 12px;border:1px solid #cfc8c1;border-radius:8px;font-size:15px;}'
            . '.aieo-selfreg__btn{appearance:none;border:0;border-radius:8px;background:#1f8a4c;color:#fff;padding:12px 28px;font-size:15px;font-weight:600;cursor:pointer;}'
            . '.aieo-selfreg__btn:hover{background:#176c3b;}'
            . '.aieo-selfreg__msg{padding:11px 14px;border-radius:8px;margin:0 0 14px;font-weight:600;}'
            . '.aieo-selfreg__msg--err{background:#fbeeed;color:#9a3a36;}'
            . '.aieo-selfreg--closed{max-width:560px;margin:24px 0;padding:16px 20px;border-radius:10px;background:#fdf6e3;color:#8a6d1a;font-weight:600;}'
            . '</style>';
    }
}
