<?php

class Ai2MediaDataHandler {

	static function create_db() {
		global $wpdb;
		$charset_collate = $wpdb->get_charset_collate();
		$table_name      = $wpdb->prefix . Ai2MediaDataTable::DB_NAME;
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

		$sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        title text NOT NULL,
        text text NOT NULL,
        summary text NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

		dbDelta( $sql );
	}

	static function delete_db() {
		global $wpdb;
		$table_name = $wpdb->prefix . Ai2MediaDataTable::DB_NAME;

		$sql = "DROP TABLE IF EXISTS $table_name";
		$wpdb->query( $sql );
	}


	static function save_data_to_db( $data ) {
		if ( $data === null ) {
			self::notify_user_about_error();
			return;
		}

		global $wpdb;
		$table_name           = $wpdb->prefix . Ai2MediaDataTable::DB_NAME;
		$existing_titles      = $wpdb->get_col( "SELECT title FROM $table_name" );
		$added_records_number = 0;

		foreach ( $data as $key => $obj ) {
			$data = $obj->data->d;
			foreach ( $data as $item ) {
				if ( ! in_array( $item->title, $existing_titles ) ) {
					$is_success = $wpdb->insert(
						$table_name,
						array(
							'title'   => $item->title,
							'text'    => $item->text,
							'summary' => $item->summary
						)
					);
					if ( $is_success ) {
						$added_records_number += 1;
					}
				}
			}
		}
		self::notify_user_about_new_records( $added_records_number );
	}


	private static function notify_user_about_new_records( int $new_records_number ) {
		if ( $new_records_number != 0 ) {
			$message = sprintf(__("%s of new records have been added to the table.", "a2m"), $new_records_number);
			$notice  = new Notice( $message, "success", true );
			$notice->show();
		}
	}

	private static function notify_user_about_error() {
		$error_message = __("You have entered a non-existent token or workspace ID.
		Check your data (A2media -> Settings).", "a2m");

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