<?php
/**
 * WooCommerce coupon hooks → sync queue.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Hooks;

defined( 'ABSPATH' ) || exit;

use StoreSheet\Queue\SyncQueue;

class CouponHooks {

	private SyncQueue $queue;

	public function __construct( SyncQueue $queue ) {
		$this->queue = $queue;
	}

	public function init(): void {
		// Coupons are still post-type based (not HPOS-affected).
		add_action( 'save_post_shop_coupon', array( $this, 'on_coupon_saved' ), 10, 2 );
		add_action( 'before_delete_post', array( $this, 'on_coupon_deleted' ), 10, 2 );
	}

	/**
	 * @param int      $post_id
	 * @param \WP_Post $post
	 */
	public function on_coupon_saved( int $post_id, \WP_Post $post ): void {
		// Skip auto-saves and revisions.
		if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
			return;
		}

		if ( 'publish' !== $post->post_status ) {
			return;
		}

		if ( $this->is_sync_enabled() ) {
			$this->queue->enqueue_coupon( $post_id );
		}
	}

	/**
	 * @param int      $post_id
	 * @param \WP_Post $post
	 */
	public function on_coupon_deleted( int $post_id, \WP_Post $post ): void {
		if ( 'shop_coupon' !== $post->post_type ) {
			return;
		}

		// Row removal is handled by the Pro add-on (see `storesheet_resource_deleted`).
		do_action( 'storesheet_resource_deleted', 'coupon', $post_id );

		storesheet()->log( "Coupon {$post_id} deleted.", 'info' );
	}

	private function is_sync_enabled(): bool {
		$settings = get_option( 'storesheet_settings', array() );
		return ! empty( $settings['sync_coupons'] ) && ! empty( $settings['spreadsheet_id'] );
	}
}
