<?php
/**
 * Database management.
 *
 * @package Polanger_Shield
 */

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

class Polanger_Shield_DB {

  /**
   * Table suffix.
   *
   * @var string
   */
  const TABLE_SUFFIX = 'pdt_shield_rules';

  /**
   * Create/update rules table.
   *
   * @return void
   */
  public static function maybe_create_tables() {
    global $wpdb;

    $table_name = $wpdb->prefix . self::TABLE_SUFFIX;
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table_name} (
      id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      rule_type varchar(20) NOT NULL,
      status varchar(20) NOT NULL DEFAULT 'active',
      screen_id varchar(191) DEFAULT '',
      page_hook varchar(191) DEFAULT '',
      page_slug varchar(191) DEFAULT '',
      request_uri text DEFAULT NULL,
      selector text DEFAULT NULL,
      selector_strength tinyint(3) unsigned DEFAULT 0,
      note longtext DEFAULT NULL,
      rule_meta longtext DEFAULT NULL,
      target_user_ids longtext DEFAULT NULL,
      note_visible_user_ids longtext DEFAULT NULL,
      block_url tinyint(1) unsigned NOT NULL DEFAULT 1,
      created_by bigint(20) unsigned NOT NULL,
      created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at datetime DEFAULT NULL,
      PRIMARY KEY  (id),
      KEY rule_type (rule_type),
      KEY status (status),
      KEY page_slug (page_slug),
      KEY screen_id (screen_id),
      KEY created_by (created_by)
    ) {$charset_collate};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
  }

  /**
   * Return validated table name.
   *
   * @return string
   */
  public static function table_name() {
    global $wpdb;
    $table_name = $wpdb->prefix . self::TABLE_SUFFIX;

    if ( preg_match( '/^[A-Za-z0-9_]+$/', $table_name ) ) {
      return $table_name;
    }

    return $wpdb->prefix . self::TABLE_SUFFIX;
  }
}
