<?php


namespace Groundhogg\DB;

use Groundhogg\Base_Object;
use Groundhogg\Classes\Note;

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

class Notes extends DB {
	public function get_db_suffix() {
		return 'gh_notes';
	}

	public function get_primary_key() {
		return 'ID';
	}

	public function get_db_version() {
		return '2.0';
	}

	public function get_object_type() {
		return 'note';
	}

	public function create_object( $object ) {
		return new Note( $object ); // TODO: Change the autogenerated stub
	}

	/**
	 * Option to add additional actions following construct.
	 */
	protected function add_additional_actions() {
		parent::add_additional_actions();
		add_action( 'groundhogg/owner_deleted', [ $this, 'owner_deleted' ], 10, 2 );
		add_action( "groundhogg/contact/merged", [ $this, 'objects_merged' ], 10, 2 );
		add_action( "groundhogg/object_merged", [ $this, 'objects_merged' ], 10, 2 );
	}

	/**
	 * When two objects are merged
	 * Change all of "other's" associations to "orig"
	 *
	 * @param $orig  Base_Object
	 * @param $other Base_Object
	 */
	public function objects_merged( $orig, $other ) {
		$this->update( [
			'object_type' => $other->_get_object_type(),
			'object_id'   => $other->get_id()
		], [
			'object_id' => $orig->get_id()
		] );
	}


	public function owner_deleted( $prev, $new ) {
		$this->update( [
			'user_id' => $prev,
		], [
			'user_id' => $new,
		] );
	}

	/**
	 * Protect notes
	 *
	 * @param array  $data
	 * @param string $ORDER_BY
	 * @param bool   $from_cache
	 *
	 * @return array|array[]|bool|int|object|object[]|null
	 */
	public function query( $data = [], $ORDER_BY = '', $from_cache = true ) {

		// ONly show notes belonging to the current user
		if ( current_user_can( 'view_notes' ) && ! current_user_can( 'view_others_notes' ) ) {
			$data['user_id'] = get_current_user_id();
			$data['context'] = 'user';
		}

		return parent::query( $data, $ORDER_BY, $from_cache ); // TODO: Change the autogenerated stub
	}

	/**
	 * Get columns and formats
	 *
	 * @access  public
	 * @since   2.1
	 */
	public function get_columns() {
		return array(
			'ID'           => '%d',
			'object_id'    => '%d',
			'object_type'  => '%s',
			'timestamp'    => '%d',
			'context'      => '%s',
			'user_id'      => '%d',
			'summary'      => '%s',
			'content'      => '%s',
			'date_created' => '%s',
			'type'         => '%s',
		);
	}

	/**
	 * Get default column values
	 *
	 * @access  public
	 * @since   2.1
	 */
	public function get_column_defaults() {

		return array(
			'ID'           => 0,
			'object_id'    => 0,
			'timestamp'    => time(),
			'object_type'  => '',
			'context'      => 'user',
			'user_id'      => get_current_user_id(),
			'summary'      => '',
			'content'      => '',
			'type'         => 'note',
			'date_created' => current_time( 'mysql', true ),
		);
	}

	/**
	 * Create the table
	 *
	 * @access  public
	 * @since   2.1
	 */
	public function create_table() {

		global $wpdb;

		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

		$sql = "CREATE TABLE " . $this->table_name . " (
		ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        object_id bigint(20) unsigned NOT NULL,
        object_type VARCHAR({$this->get_max_index_length()}) NOT NULL,    
        user_id bigint(20) unsigned NOT NULL,
        context VARCHAR(50) NOT NULL,    
        type VARCHAR(50) NOT NULL,    
        summary text NOT NULL,
        content longtext NOT NULL,
        timestamp bigint(12) unsigned NOT NULL,
        date_created datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        PRIMARY KEY (ID)
		) {$this->get_charset_collate()};";

		dbDelta( $sql );

		update_option( $this->table_name . '_db_version', $this->version );
	}

	/**
	 * Rename gh_contactnotes to gh_notes
	 * change contact_id to object_id
	 * Add new object_type column
	 * Set the object type to contact because up to this point all notes where for contacts.
	 */
	public function update_2_4_6() {

		global $wpdb;

		$old_table_name = $wpdb->prefix . 'gh_contactnotes';

		$wpdb->query( "ALTER TABLE $old_table_name RENAME TO {$this->table_name};" );
		$wpdb->query( "ALTER TABLE {$this->table_name} CHANGE contact_id object_id bigint(20) unsigned NOT NULL ;" );
		$wpdb->query( "ALTER TABLE {$this->table_name} ADD object_type VARCHAR({$this->get_max_index_length()}) NOT NULL;" );
		$wpdb->query( "UPDATE {$this->table_name} SET object_type = 'contact' WHERE object_type = ''; " );
	}

	/**
	 * Update the note type to the default
	 */
	public function update_2_5_5() {
		global $wpdb;

		$wpdb->query( "UPDATE $this->table_name SET type = 'note' WHERE type = ''" );
	}
}
