<?php

namespace Easymailing\App\Core\Log;

class LogDatabase
{

	const TABLE_NAME = 'easymailing_logs';

	public static function getTableName(): string
	{
		global $wpdb;
		return $wpdb->prefix . self::TABLE_NAME;
	}

	public static function createTable(): void
	{
		global $wpdb;

		$table_name = self::getTableName();

		$table_exists = $wpdb->get_var($wpdb->prepare(
			"SHOW TABLES LIKE %s",
			$table_name
		));

		if ($table_exists) {
			$wpdb->query("DROP TABLE IF EXISTS {$table_name}");
		}

		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table_name} (
        id BIGINT(20) NOT NULL AUTO_INCREMENT,
        type VARCHAR(50) NOT NULL,
        date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
        url TEXT DEFAULT NULL,
        status VARCHAR(255) DEFAULT NULL,
        body TEXT DEFAULT NULL,
        response TEXT DEFAULT NULL,
        message TEXT NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
	}


	public static function deleteTable(): void
	{
		global $wpdb;

		$sql = "DROP TABLE IF EXISTS {self::getTableName()}";
		$wpdb->query($sql);
	}
}
