<?php

namespace EDPW\Core\Models;


defined( 'ABSPATH' ) or die();

class CustomBlocks extends BaseModel {
	/**
	 * Table name.
	 * @var string
	 */
	const TABLE_NAME = 'edpw_custom_blocks';

	/**
	 * Table primary key.
	 */
	const PRIMARY_KEY = 'id';

	/**
	 * Field list.
	 * @var array
	 */
	public static array $fields = [
		'title'         => '%s',
		'title_content' => '%s',
		'block_id'      => '%s',
		'content'       => '%s',
		'category'      => '%s',
	];

	/**
	 * run table creation query
	 */
	public static function create() {
		$create_table_query = "CREATE TABLE {table} (
				 `id` int(11) NOT NULL AUTO_INCREMENT,
                 `title` varchar(255) DEFAULT NULL,
    			 `title_content` longtext DEFAULT NULL,
                 `block_id` varchar(255) DEFAULT NULL,
                 `content` longtext DEFAULT NULL,
                 `category` varchar(255) DEFAULT NULL,
                 PRIMARY KEY (`id`)
			){charset_collate};";
		self::executeQuery( $create_table_query );
	}

	/**
	 * Save Custom Block.
	 *
	 * @param array $data Data.
	 *
	 * @return int
	 */
	public static function saveCustomBlock( $data ) {
		if ( ! is_array( $data ) ) {
			return 0;
		}
		$save_data = [
			'title'    => ! empty( $data['title'] ) ? $data['title'] : '',
			//'title_content' => ! empty( $data['title_content'] ) ? $data['title_content'] : '',
			//'block_id'      => ! empty( $data['block_id'] ) ? $data['block_id'] : '',
			'content'  => ! empty( $data['content'] ) ? $data['content'] : '',
			'category' => ! empty( $data['category'] ) ? $data['category'] : ''
		];
		$id        = self::insert( $save_data );
		if ( $id > 0 ) {
			$update_data = [
				'block_id'      => 'save_block_' . $id,
				'title_content' => '<div class="edpw-block-media-container edpw-relative edpw-group">
                    <i class="edpw edpw-drag edpw-icon edpw-text-sm"></i>
                    <i class="edpw edpw-custom-block edpw-icon edpw-text-2xl"></i>
                    <div id="save_block_' . $id . '" class="edpw-action-container edpw-absolute edpw-bottom-8 edpw-flex edpw-w-full edpw-bg-gray-100 edpw-bg-opacity-75 edpw-justify-center edpw-items-center edpw-space-x-2 ">
                    </div>
                </div>'
			];
			self::update( $update_data, [ 'id' => $id ] );
		}

		return $id;
	}
}