<?php

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

function aieo_competitions_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_competition_participants';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table} (
        participant_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        competition_id bigint(20) UNSIGNED NOT NULL,
        gf_entry_id bigint(20) UNSIGNED NOT NULL DEFAULT 0,
        email varchar(190) NOT NULL DEFAULT '',
        first_name varchar(100) NOT NULL DEFAULT '',
        last_name varchar(100) NOT NULL DEFAULT '',
        status varchar(12) NOT NULL DEFAULT 'pending',
        source varchar(12) NOT NULL DEFAULT 'optin',
        eponymous_id bigint(20) UNSIGNED NOT NULL DEFAULT 0,
        wp_user_id bigint(20) UNSIGNED NOT NULL DEFAULT 0,
        is_winner tinyint(1) NOT NULL DEFAULT 0,
        won_at datetime NULL DEFAULT NULL,
        created_at datetime NULL DEFAULT NULL,
        confirmed_at datetime NULL DEFAULT NULL,
        updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (participant_id),
        UNIQUE KEY uk_comp_entry (competition_id, gf_entry_id),
        KEY idx_email (email),
        KEY idx_status (status),
        KEY idx_competition (competition_id),
        KEY idx_eponymous (eponymous_id),
        KEY idx_winner (competition_id, is_winner)
    ) {$charset};";

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