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

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

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

	/**
	 * Retrieve the columns and labels.
	 *
	 * @since 1.0.0
	 * @return array
	 */
	public function get_columns(): array {
		return [
			'id'             => __( 'ID', 'rewardswp' ),
			'referral_id'    => __( 'Referral ID', 'rewardswp' ),
			'advocate_id'    => __( 'Advocate ID', 'rewardswp' ),
			'recipient_type' => __( 'Recipient Type', 'rewardswp' ),
			'reward_type'    => __( 'Reward Type', 'rewardswp' ),
			'amount'         => __( 'Amount', 'rewardswp' ),
			'status'         => __( 'Status', 'rewardswp' ),
			'created_at'     => __( 'Created At', 'rewardswp' ),
			'applied_at'     => __( 'Applied At', 'rewardswp' ),
			'expires_at'     => __( 'Expires At', 'rewardswp' ),
		];
	}

	/**
	 * Creates the `rewardswp_advocates` 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,
                referral_id bigint(20) unsigned NOT NULL,
                advocate_id bigint(20) unsigned NOT NULL,
            	recipient_type varchar(20) NOT NULL,
                reward_type varchar(50) NOT NULL,
                amount int NOT NULL,
                status varchar(20) NOT NULL,
                created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP(),
                applied_at datetime DEFAULT NULL,
                expires_at datetime DEFAULT NULL,
                PRIMARY KEY (id),
                KEY referral_id (referral_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();
	}
}
