<?php
/**
 * Channels Controller
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handles channels related AJAX endpoints.
 */
class Channels_Controller {
	/**
	 * Delete a channel and its related data.
	 */
	public static function handle_delete_channel(): void {
		check_ajax_referer( Plugin_Constants::NONCE_MAIN, 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Permission denied', 'multi-channel-for-woocommerce' ) ) );
		}

		$channel_id = isset( $_POST['channel_id'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['channel_id'] ) ) : 0;
		if ( $channel_id <= 0 ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid channel ID', 'multi-channel-for-woocommerce' ) ) );
		}

		try {
			$handler = new \MOMCS_Sync\Includes\Common\Handlers\Dashboard_Handler();
			$handler->delete_channel( $channel_id );
			wp_send_json_success();
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}
}
