<?php
/**
 * Creates ambh_consent_records table
 *
 * @package AmbassadorHub\Consent\Migrations
 */

namespace AmbassadorHub\Consent\Migrations;

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

class CreateTables {
	public static function up(): void {
		global $wpdb;
		$charset_collate = $wpdb->get_charset_collate();
		$table           = $wpdb->prefix . 'ambh_consent_records';
		$sql             = "CREATE TABLE IF NOT EXISTS $table (
            id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            subject_type    VARCHAR(20)  NOT NULL,
            subject_id      BIGINT UNSIGNED NOT NULL,
            purpose_slug    VARCHAR(64)  NOT NULL,
            channel         VARCHAR(20)  NOT NULL,
            scope_type      VARCHAR(20)  NOT NULL DEFAULT 'global',
            scope_id        BIGINT UNSIGNED NULL,
            granted         TINYINT(1)   NOT NULL,
            consent_text    TEXT         NOT NULL,
            source          VARCHAR(40)  NOT NULL,
            proof_token     VARCHAR(64)  NOT NULL,
            consented_at    DATETIME     NOT NULL,
            withdrawn_at    DATETIME     NULL,
            withdrawn_by    VARCHAR(20)  NULL,
            INDEX idx_subject   (subject_type, subject_id),
            INDEX idx_slug      (purpose_slug),
            INDEX idx_active    (subject_type, subject_id, purpose_slug, withdrawn_at)
        ) $charset_collate;";
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );
	}
}
