<?php

namespace GemBoards\hooks;

use GemBoards\entities\CardAssignee;
use GemBoards\Entities\Notification;
use GemBoards\Entities\TaskAttachment;
use GemBoards\Utils\Helper;
use GemBoardsPro\Entities\TaskChecklist;
use GemBoardsPro\Entities\TaskChecklistGroup;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // if accessed directly, exit


class Card {

	public static function init() {
		$self = new self();

		add_action( 'gemboards/card/deleted', [ $self, 'delete_other_tables_data' ], 10, 2 );
	}

	public function delete_other_tables_data( int $card_id, \GemBoards\Entities\Card $card ) {
		$task_id = $card->get_task_id();
		if ( $task_id ) {
			wp_delete_post( $task_id, true );
		}

		global $wpdb;

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query( 'START TRANSACTION' );

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->prefix}gemboards_card_assignees WHERE card_id = %d", $card_id
			)
		);
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->prefix}gemboards_task_attachments WHERE task_id = %d", $task_id
			)
		);

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->prefix}gemboards_notifications WHERE object_type = 'task' AND object_id = %d", $task_id
			)
		);

		if ( Helper::has_pro() ) {
			$wpdb->query(
				$wpdb->prepare(
					"DELETE FROM {$wpdb->prefix}gemboards_pro_task_checklists WHERE card_id = %d", $card_id
				)
			);

			$wpdb->query(
				$wpdb->prepare(
					"DELETE FROM {$wpdb->prefix}gemboards_pro_task_checklist_groups WHERE card_id = %d", $card_id
				)
			);
		}

		$wpdb->query( 'COMMIT' );
		// phpcs:enable

		( new \GemBoards\Entities\Card() )->clear_cache();
		( new CardAssignee() )->clear_cache();
		( new TaskChecklistGroup() )->clear_cache();
		( new TaskChecklist() )->clear_cache();
		( new TaskAttachment() )->clear_cache();
		( new Notification() )->clear_cache();
	}

}
