<?php

namespace auctionforge\inc;

use Elementor\Core\App\Modules\ImportExport\Import;
use auctionforge\inc\abs\Importer;
use auctionforge\inc\model\Lot;

class InstanceDB {

    private $wpdb;

    private static $_instance = null;

    private function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
    }

    protected function __clone() {
        // restricts cloning of the object
    }

    static public function getInstance() {
        if(is_null(self::$_instance))
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    static public function getInstanceDB() {
        return self::getInstance()->DB();
    }

    public function DB() {
        return $this->wpdb;
    }
    
    public function wp_insert_rows_custom($row_arrays, $wp_table_name, $masks)
    {
        $db = InstanceDB::getInstanceDB();
        $query = "INSERT INTO " . $db->prefix . $wp_table_name . " (";
        $count = count($row_arrays) - 1;
        /** @var Lot $row */
        $columns = array_keys($row_arrays[0]->buildFields());
        $placeHolders = "(" . implode(",", $masks) . ")";
        $query .= implode(",", $columns) . ") VALUES ";
        foreach ($row_arrays as $key => $row) {
            $values = $row->buildFields();
            $sqlChunk = $db->prepare($placeHolders, $values);
            $query .= $sqlChunk;
            if ($key < $count) {
                $query .= ",";
            }
        }
        return $db->query($query);
    }

    public static function unlockTable()
    {
        $db = InstanceDB::getInstanceDB();
        $sql = "UNLOCK TABLES;";
        $db->query($sql);
    }
}