<?php
/**
 * Hourly auto-recovery email + daily purge.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Modules\Cart_Recovery;

use SuiteMkt3k\Installer;
use SuiteMkt3k\Modules\Settings\Settings_Manager;
use SuiteMkt3k\Utils\Logger;

defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

final class Cart_Recovery_Cron {

	public static function register(): void {
		add_action( 'suitemkt3k_cron_hourly', array( __CLASS__, 'auto_send' ) );
		add_action( 'suitemkt3k_cron_daily', array( __CLASS__, 'purge' ) );
	}

	public static function auto_send(): void {
		$enabled = (bool) Settings_Manager::get( 'cart', 'auto_send_enabled', false );
		if ( ! $enabled ) {
			return;
		}
		$hours = (int) Settings_Manager::get( 'cart', 'auto_send_hours', 1 );
		$hours = max( 1, min( 168, $hours ) );

		global $wpdb;
		$cutoff = gmdate( 'Y-m-d H:i:s', time() - $hours * HOUR_IN_SECONDS );
		$rows = $wpdb->get_col(
			$wpdb->prepare(
				'SELECT id FROM %i WHERE status = %s AND recovery_email_sent_at IS NULL AND last_activity_at <= %s LIMIT 50',
				Cart_Recovery_Manager::table(),
				'pending',
				$cutoff
			)
		);
		$template = Cart_Recovery_Manager::get_default_template();
		foreach ( (array) $rows as $id ) {
			Cart_Recovery_Manager::send_email( (int) $id, $template );
		}
		Logger::info( 'cart_cron', 'Auto sent', array( 'count' => count( (array) $rows ) ) );
	}

	public static function purge(): void {
		$days = (int) Settings_Manager::get( 'cart', 'purge_days', 30 );
		$days = max( 7, min( 365, $days ) );
		global $wpdb;
		$cutoff = gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS );
		$wpdb->query(
			$wpdb->prepare(
				'DELETE FROM %i WHERE status IN (%s,%s,%s) AND created_at <= %s',
				Cart_Recovery_Manager::table(),
				'recovered',
				'expired',
				'deleted',
				$cutoff
			)
		);
	}
}
