<?php
/**
 * Emails Clicked 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; // @codeCoverageIgnore

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

/**
 * Emails Clicked Chart class.
 *
 * Builds chart data for recovery emails clicked.
 *
 * @since 3.6.5
 */
class EmailsClicked extends Graph {

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

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

	/**
	 * Gets the chart label for display.
	 *
	 * @since 3.6.5
	 * @return string
	 */
	protected function get_label(): string {
		return __( 'Emails Clicked', '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_clicked' );

		// 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_clicked BETWEEN %s AND %s
				AND date_clicked IS NOT NULL
				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['orange']},0.75)";

		return $args;
	}
}
