<?php

class TablePage extends PageBase {

	const PAGE_NAME = "ai2media";

	private $send_action = "create-post-action";
	private $remove_action = "remove-record-action";
	private $remove_all_action = "clear-table-action";
	private $update_data_action = "update-data-action";

	static function get_shared() {
		return parent::get_shared();
	}

	function show(): void {
		Ai2MediaDataTable::getShared()->prepare_items();
		?>
        <h2>Ai2Media</h2>
        <form id='checkbox-form' method='post'>
            <input type="hidden" name="action" value="">
            <input type="hidden" name="<?php echo Ai2MediaDataTable::CHECKBOX_ACTION ?>" value="">
            <div id="data-buttons">
                <button type='submit' id="update-data-button" name='action' value="update-data-action">
                    <?php _e("Update data", "a2m")?>
                </button>
                <button type='button' id="create-post-button">
                    <?php _e("Create post", "a2m")?>
                </button>
                <button type='button' id="remove-record-button">
                    <?php _e("Remove", "a2m")?>
                </button>
                <button type='button' id="clear-table-button">
                    <?php _e("Clear table", "a2m")?>
                </button>
            </div>
        </form>
		<?php
		Ai2MediaDataTable::getShared()->display();
	}

	function buttons_handler() {
		$is_checkboxes_pressed = isset( $_POST[ Ai2MediaDataTable::CHECKBOX_ACTION ] );
		$is_post               = isset( $_POST["action"] );

		if ( $is_post && $_POST["action"] == $this->send_action && $is_checkboxes_pressed ) {
			$this->add_records_to_post();
		} else if ( $is_post && $_POST["action"] == $this->remove_action && $is_checkboxes_pressed ) {
			$this->remove_records();
		} else if ( $is_post && $_POST["action"] == $this->remove_all_action ) {
			$this->remove_all_records();
		} else if ($is_post && $_POST["action"] == $this->update_data_action) {
            $this->update_data_table();
        }
	}

////  Button actions  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	private function add_records_to_post(): void {
		global $wpdb;
		$db_name = $wpdb->prefix . Ai2MediaDataTable::DB_NAME;

		$jsonString         = stripslashes( $_POST["checkbox-select-action"] );
		$chosen_records_ids = json_decode( $jsonString );
		$ids_placeholders   = implode( ',', array_fill( 0, count( $chosen_records_ids ), '%d' ) );

		$query = $wpdb->prepare( "SELECT * FROM $db_name WHERE ID IN ($ids_placeholders)", ...$chosen_records_ids );

		$chosen_data = $wpdb->get_results( $query );
		foreach ( $chosen_data as $record ) {
			if ( ! post_exists( $record->title ) ) {
				$new_post_data = array(
					'post_title'   => sanitize_text_field( $record->title ),
					'post_content' => $record->summary . "\n\n" . $record->text,
					'post_status'  => 'draft',
					'post_type'    => 'post',
				);
				$post_id       = wp_insert_post( $new_post_data );
				$ws_id         = get_option( SettingsPage::WS_OPTION_NAME );
				add_post_meta( $post_id, WsIdField::KEY, $ws_id );
			}
		}
	}

	private function remove_records() {
		global $wpdb;
		$db_name = $wpdb->prefix . Ai2MediaDataTable::DB_NAME;

		$jsonString         = stripslashes( $_POST[Ai2MediaDataTable::CHECKBOX_ACTION] );
		$chosen_records_ids = json_decode( $jsonString );
		$placeholders       = implode( ",", array_fill( 0, count( $chosen_records_ids ), "%d" ) );

		$query = $wpdb->prepare( "DELETE FROM $db_name WHERE id IN ($placeholders)", ...$chosen_records_ids );
		$wpdb->query( $query );
	}

	private function remove_all_records() {
		global $wpdb;
		$db_name = $wpdb->prefix . Ai2MediaDataTable::DB_NAME;

		$wpdb->query( "TRUNCATE TABLE $db_name" );
	}

    private function update_data_table() {
        if ( $this->check_settings() ) {
//            Ai2Media_Service::update_data(); // подумать нужно ли обновление каждый раз или нет
            $data = Ai2MediaService::get_data();
            Ai2MediaDataHandler::save_data_to_db( $data );
        }
    }


////  Validation  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	private function check_settings(): bool {
		$token         = get_option( SettingsPage::TOKEN_OPTION_NAME );
		$ws            = get_option( SettingsPage::WS_OPTION_NAME );
		$error_message = __("To import data, you need to fill %s (A2media->Settings).", "a2m");

		if ( $token == null ) {
			$error_message = sprintf( $error_message, __("User token", "a2m"));
		} elseif ( $ws == null ) {
			$error_message = sprintf( $error_message, __("Workspace ID", "a2m") );
		} else {
			return true;
		}


		$notice = new Notice( $error_message, "error", false );
		$notice->show();

		return false;

	}
}