<?php
/**
 * Handles the creation of the Points table in the database.
 *
 * @package Awesomemotive\Rewardswp\Database\Tables
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Database\Tables;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractDatabaseTable;

/**
 * Class PointsTable
 *
 * This class creates the `rewardswp_points` table.
 *
 * @since 1.0.0
 */
class PointsTable extends AbstractDatabaseTable {
	/**
	 * Returns the name of the points table (without prefix).
	 *
	 * @since 1.0.0
	 *
	 * @return string Table name.
	 */
	public function get_table_name(): string {
		return 'rewardswp_points';
	}

	/**
	 * Returns the name of the points meta table (without prefix).
	 *
	 * @since 1.0.0
	 * @return string Table name.
	 */
	public function get_meta_table_name(): string {
		return 'rewardswp_pointsmeta';
	}

	/**
	 * Returns the name of the column used to create the relationship between the main table and the meta table.
	 *
	 * @since 1.0.0
	 *
	 * @return string Column name.
	 */
	public function get_meta_table_relationship_field_name(): string {
		return 'points_id';
	}

	/**
	 * Retrieve the columns and labels.
	 *
	 * @since 1.0.0
	 * @return array
	 */
	public function get_columns(): array {
		return [
			'id'            => __( 'ID', 'rewardswp' ),
			'member_id'     => __( 'Member ID', 'rewardswp' ),
			'points'        => __( 'Points', 'rewardswp' ),
			'type'          => __( 'Type', 'rewardswp' ),
			'source_type'   => __( 'Source Type', 'rewardswp' ),
			'source_id'     => __( 'Source ID', 'rewardswp' ),
			'status'        => __( 'Status', 'rewardswp' ),
			'expires_at'    => __( 'Expires At', 'rewardswp' ),
			'note_internal' => __( 'Internal Note', 'rewardswp' ),
			'note_public'   => __( 'Public Note', 'rewardswp' ),
			'created_at'    => __( 'Created At', 'rewardswp' ),
		];
	}

	/**
	 * Creates the `rewardswp_points` table in the database.
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function create_or_update_table(): void {
		$this->db_delta(
			sprintf(
				"CREATE TABLE %s (
					id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
					member_id bigint(20) unsigned NOT NULL,
					points int(11) NOT NULL DEFAULT 0,
					type varchar(50) NOT NULL,
					source_type varchar(50) NOT NULL,
					source_id bigint(20) unsigned DEFAULT NULL,
					status varchar(50) NOT NULL DEFAULT 'approved',
					created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
					expires_at datetime DEFAULT NULL,
					note_internal text DEFAULT NULL,
					note_public text DEFAULT NULL,
					PRIMARY KEY (id),
					KEY member_id (member_id),
					KEY status (status),
					KEY expires_at (expires_at),
					KEY source_type_source_id (source_type, source_id)
				) %s;",
				$this->get_prefixed_table_name(),
				$this->global_config->get_db()->get_charset_collate()
			)
		);

		// Create the meta table for this model.
		$this->create_meta_table();
	}
}
