<?php
/**
 * Emails Sent Chart
 *
 * @package     EDD\Pro\CartRecovery\Admin\Reports\Endpoints\Charts
 * @copyright   Copyright (c) 2026, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.6.5
 */

namespace EDD\Pro\CartRecovery\Admin\Reports\Endpoints\Charts;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

use EDD\Reports\Endpoints\Charts\Graph;
use EDD\Reports\Utilities\Database;

/**
 * Emails Sent Chart class.
 *
 * Builds chart data for recovery emails sent.
 *
 * @since 3.6.5
 */
class EmailsSent extends Graph {
	use \EDD\Reports\Endpoints\Traits\Colors;

	/**
	 * The key for the dataset.
	 *
	 * @since 3.6.5
	 * @var string
	 */
	protected $key = 'emails_sent';

	/**
	 * Gets the chart endpoint ID.
	 *
	 * @since 3.6.5
	 * @return string
	 */
	protected function get_id(): string {
		return 'acr_emails_sent_chart';
	}

	/**
	 * Gets the chart label for display.
	 *
	 * @since 3.6.5
	 * @return string
	 */
	protected function get_label(): string {
		return __( 'Emails Sent', 'easy-digital-downloads' );
	}

	/**
	 * Gets the query results for building the chart.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	protected function get_query_results(): array {
		global $wpdb;

		// Get emails table name.
		$emails_table = $wpdb->prefix . 'edd_acr_emails';

		// Build SQL clauses using the Database utility.
		$clauses = Database::get_sql_clauses( $this->period, 'date_sent' );

		// Format dates for SQL.
		$start_date = $this->dates['start']->copy()->format( 'Y-m-d H:i:s' );
		$end_date   = $this->dates['end']->copy()->format( 'Y-m-d H:i:s' );

		$sql = "SELECT COUNT(*) AS value, {$clauses['select']}
				FROM {$emails_table}
				WHERE date_sent BETWEEN %s AND %s
				GROUP BY {$clauses['groupby']}
				ORDER BY {$clauses['orderby']} ASC";

		$results = $wpdb->get_results( $wpdb->prepare( $sql, $start_date, $end_date ) );

		return is_array( $results ) ? $results : array();
	}

	/**
	 * Gets the chart arguments.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	protected function get_args(): array {
		$args                = parent::get_args();
		$args['borderColor'] = "rgba({$this->colors['green']},0.75)";

		return $args;
	}
}
