<?php
/**
 * Created by PhpStorm.
 * User: Pritom
 * Date: 5/16/2024
 * Time: 2:10 PM
 */

namespace Flyerimage\Core\Database;

use Flyerimage\App\Constants\ITables;
use Flyerimage\Core\Util\Helper;
use Illuminate\Database\Migrations\Migration;

class MigrationBase extends Migration {
    public $fileName = "";
    protected $table = "";
    protected $columns = [];
    protected $queries = [];
    protected $engine = "InnoDB";
    protected $collation = "utf8mb4_unicode_ci";
    protected $charset = "utf8mb4";

    public static $table_prefix = "fiV102030858_";

    public function runMigration() {
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        global $wpdb;

        if ($this->table == ITables::$FLYER_MIGRATION) {
            if (!$this->checkIfTableExists()) {
                $sql = sprintf("CREATE TABLE `%s` (\n", $this->table_name($this->table));
                $sql .= implode(", ", $this->columns);
                $sql .= sprintf("\n) ENGINE=%s DEFAULT CHARSET=%s COLLATE=%s", $this->engine, $this->charset, $this->collation);
				// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
                dbDelta($sql);
            }
        }
        else if (!$this->checkIfFileExecuted()) {
            $this->executeColumns();
            $this->executeRawQueries();
            
			$table_name = esc_sql( $this->table_name( ITables::$FLYER_MIGRATION ) );
			$wpdb->query(
				$wpdb->prepare(
					"INSERT INTO `{$table_name}` (`name`) VALUES (%s)",
					$this->fileName
				)
			);
        }
    }

    protected function table_name($table) {
        global $wpdb;
        return sprintf("%s%s%s", $wpdb->prefix, MigrationBase::$table_prefix, $table);
    }

    private function checkIfTableExists() {
        global $wpdb;
        $db_name = $wpdb->dbname;
        $table_name = $this->table_name($this->table);
		$result = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM information_schema.tables WHERE table_schema = %s AND table_name = %s LIMIT 1",
				$db_name,
				$table_name
			)
		);

        return !is_null($result);
    }

    private function checkIfFileExecuted() {
        global $wpdb;
        $table_name = esc_sql($this->table_name(ITables::$FLYER_MIGRATION));
        $sql = $wpdb->prepare(
            "SELECT * FROM `{$table_name}` WHERE `name` = %s LIMIT 1",
            $this->fileName
        );
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $result = $wpdb->get_row($sql);        
        return !is_null($result);
    }

    private function executeColumns() {
        if (count($this->columns) > 0) {
            if ($this->checkIfTableExists()) {}
            else {
                $sql = sprintf("CREATE TABLE `%s` (\n", $this->table_name($this->table));
                $sql .= implode(", ", $this->columns);
                $sql .= sprintf("\n) ENGINE=%s DEFAULT CHARSET=%s COLLATE=%s", $this->engine, $this->charset, $this->collation);
                dbDelta($sql);
            }
        }
    }

    private function executeRawQueries() {
        if (count($this->queries) > 0) {
            global $wpdb;
            foreach ($this->queries as $sql) {
				// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
                $wpdb->query($sql);
            }
        }
    }
}