<?php

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

function aieo_events_install_schema() {
    global $wpdb;

    
    
    if (!function_exists('aieo_dbdelta') && defined('AIEO_DIR')) {
        if (file_exists(AIEO_DIR . 'includes/sql/sprocs.php')) {
            require_once AIEO_DIR . 'includes/sql/sprocs.php';
        }
        if (!function_exists('aieo_dbdelta') && file_exists(AIEO_DIR . 'includes/sql/sql-runtime-helpers.php')) {
            require_once AIEO_DIR . 'includes/sql/sql-runtime-helpers.php';
        }
    }

    $table   = $wpdb->prefix . 'aieo_event_participants';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table} (
        participant_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        event_id bigint(20) UNSIGNED NOT NULL,
        title varchar(32) NOT NULL DEFAULT '',
        salutation varchar(64) NOT NULL DEFAULT '',
        first_name varchar(100) NOT NULL DEFAULT '',
        last_name varchar(100) NOT NULL DEFAULT '',
        department varchar(190) NOT NULL DEFAULT '',
        organization varchar(190) NOT NULL DEFAULT '',
        email varchar(190) NOT NULL DEFAULT '',
        phone varchar(40) NOT NULL DEFAULT '',
        source varchar(16) NOT NULL DEFAULT 'imported',
        rsvp_status varchar(12) NOT NULL DEFAULT 'invited',
        rsvp_token char(64) NOT NULL DEFAULT '',
        imported_by bigint(20) UNSIGNED NOT NULL DEFAULT 0,
        import_batch varchar(32) NOT NULL DEFAULT '',
        eponymous_id bigint(20) UNSIGNED NOT NULL DEFAULT 0,
        wp_user_id bigint(20) UNSIGNED NOT NULL DEFAULT 0,
        amount_due decimal(10,2) NOT NULL DEFAULT 0.00,
        payment_status varchar(12) NOT NULL DEFAULT 'none',
        payment_ref varchar(190) NOT NULL DEFAULT '',
        paid_at datetime NULL DEFAULT NULL,
        invited_at datetime NULL DEFAULT NULL,
        created_at datetime NULL DEFAULT NULL,
        responded_at datetime NULL DEFAULT NULL,
        updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (participant_id),
        UNIQUE KEY uk_event_email (event_id, email),
        UNIQUE KEY uk_token (rsvp_token),
        KEY idx_event_status (event_id, rsvp_status),
        KEY idx_event_batch (event_id, imported_by, import_batch),
        KEY idx_payment (event_id, payment_status),
        KEY idx_email (email),
        KEY idx_eponymous (eponymous_id)
    ) {$charset};";

    if (function_exists('aieo_dbdelta')) {
        aieo_dbdelta($sql);
    } else {
        if (!function_exists('dbDelta')) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; }
        dbDelta($sql);
    }
}
