<?php
/**
 * CheckoutStartedTrigger — fires after a guest enters email at checkout without completing.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

use CartCue\DB;

defined( 'ABSPATH' ) || exit;

class CheckoutStartedTrigger extends AbstractTrigger {

	public function get_slug(): string {
		return 'checkout_started';
	}

	public function get_label(): string {
		return __( 'Checkout Started', 'cartcue-sales-automation' );
	}

	public function get_sentence(): string {
		return __( 'someone enters their email at checkout but does not finish', 'cartcue-sales-automation' );
	}

	public function get_description(): string {
		return __( 'Customer enters email at checkout but doesn’t finish.', 'cartcue-sales-automation' );
	}

	public function supports_recheck(): bool {
		return true;
	}

	public function is_still_valid( array $data ): bool {
		global $wpdb;
		$cart_id = (int) ( $data['cart_id'] ?? 0 );
		if ( ! $cart_id ) {
			return false;
		}
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$status = $wpdb->get_var(
			$wpdb->prepare( 'SELECT status FROM %i WHERE id = %d', DB::carts(), $cart_id )
		);
		return in_array( $status, [ 'active', 'checkout_started' ], true );
	}

	public function get_settings_fields(): array {
		return [
			[
				'key'     => 'minutes_after_email',
				'label'   => __( 'Wait this many minutes after email is entered', 'cartcue-sales-automation' ),
				'type'    => 'number',
				'default' => 30,
			],
		];
	}

	public function get_test_data(): array {
		return [
			'trigger'        => $this->get_slug(),
			'cart_id'        => 0,
			'customer_id'    => 0,
			'customer_email' => get_option( 'admin_email', '' ),
			'cart_total'     => wc_price( 49.00 ),
			'_is_test'       => true,
		];
	}

	public function register_hooks(): void {
		// Cart + email capture handled by CartAbandonedTrigger.
	}

	/**
	 * Mark checkout started on a cart row (called from CartAbandonedTrigger).
	 */
	public static function mark_checkout_started( int $cart_id ): void {
		if ( $cart_id < 1 ) {
			return;
		}

		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE %i SET checkout_started_at = %s, status = 'checkout_started'
				 WHERE id = %d AND checkout_started_fired = 0 AND status IN ('active','checkout_started')",
				DB::carts(),
				current_time( 'mysql' ),
				$cart_id
			)
		);
	}

	public function process_checkout_started(): void {
		global $wpdb;

		$workflows = $this->plugin->runner->get_active_workflows_for_trigger( $this->get_slug() );
		if ( empty( $workflows ) ) {
			return;
		}

		$min_minutes = 30;
		foreach ( $workflows as $wf ) {
			$m           = (int) ( $wf['trigger_settings']['minutes_after_email'] ?? 30 );
			$min_minutes = min( $min_minutes, max( 5, $m ) );
		}

		$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $min_minutes * MINUTE_IN_SECONDS ) );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$carts = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM %i
				 WHERE checkout_started_fired = 0
				   AND checkout_started_at IS NOT NULL
				   AND checkout_started_at <= %s
				   AND email != ''
				   AND status IN ('active','checkout_started')
				 ORDER BY checkout_started_at ASC LIMIT 200",
				DB::carts(),
				$cutoff
			),
			ARRAY_A
		) ?: [];

		foreach ( $carts as $cart ) {
			foreach ( $workflows as $wf ) {
				$wf_minutes = (int) ( $wf['trigger_settings']['minutes_after_email'] ?? 30 );
				$wf_cutoff  = gmdate( 'Y-m-d H:i:s', time() - ( $wf_minutes * MINUTE_IN_SECONDS ) );
				if ( $cart['checkout_started_at'] > $wf_cutoff ) {
					continue;
				}

				$this->plugin->runner->trigger(
					(int) $wf['id'],
					[
						'trigger'        => $this->get_slug(),
						'cart_id'        => (int) $cart['id'],
						'customer_id'    => (int) $cart['user_id'],
						'customer_email' => $cart['email'],
						'cart_total'     => $cart['total'],
					]
				);
			}

			// phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->update(
				DB::carts(),
				[ 'checkout_started_fired' => 1 ],
				[ 'id' => $cart['id'] ],
				[ '%d' ],
				[ '%d' ]
			);
		}
	}
}
