<?php
/**
 * Handles the creation of the Emails 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 EmailsTable
 *
 * This class creates the `rewardswp_emails` table.
 *
 * @since 1.0.0
 */
class EmailsTable extends AbstractDatabaseTable {
	/**
	 * Returns the name of the emails table (without prefix).
	 *
	 * @since 1.0.0
	 *
	 * @return string Table name.
	 */
	public function get_table_name(): string {
		return 'rewardswp_emails';
	}

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

	/**
	 * 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 'email_id';
	}

	/**
	 * Retrieve the columns and labels.
	 *
	 * @since 1.0.0
	 * @return array
	 */
	public function get_columns(): array {
		return [
			'id'             => __( 'ID', 'rewardswp' ),
			'name'           => __( 'Email Name', 'rewardswp' ),
			'subject'        => __( 'Subject', 'rewardswp' ),
			'context'        => __( 'Context', 'rewardswp' ),
			'recipient_type' => __( 'Recipient Type', 'rewardswp' ),
			'sender'         => __( 'Sender', 'rewardswp' ),
			'is_enabled'     => __( 'Enabled', 'rewardswp' ),
			'created_at'     => __( 'Created At', 'rewardswp' ),
		];
	}

	/**
	 * Creates the `rewardswp_emails` 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,
					name varchar(100) NOT NULL,
					subject text DEFAULT NULL,
					context varchar(50) DEFAULT NULL,
					recipient_type varchar(50) DEFAULT NULL,
					sender varchar(50) DEFAULT 'RewardsWP Core',
					is_enabled tinyint(1) NOT NULL DEFAULT 1,
					created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP(),
					PRIMARY KEY (id),
					UNIQUE KEY name (name),
					KEY context (context),
					KEY recipient_type (recipient_type),
					KEY is_enabled (is_enabled),
					KEY created_at (created_at)
				) %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();
	}
}
