<?php

namespace CCDN\Helpers\DB;

use CCDN\Helpers\Exception\CCDNRuntimeException;
use db;
use mysqli_result;

class Model
{
    /**
     * @var db
     */
    private $db;

    /**
     * @var string
     */
    private $prefix;

    public function __construct()
    {
        global $db;
        $this->db = $db;
        $this->prefix = PREFIX;

    }

    /**
     * @return string
     */
    public function getPrefix()
    {
        return $this->prefix;
    }

    public function getDb()
    {
        return $this->db;
    }

    /**
     * @param string $table
     * @param array $data
     * @param array $where
     *
     * @return bool
     */
    public function update($table, $data, $where)
    {
        $fields = [];
        foreach ($data as $key => $datum) {
            $fields[] = "`{$key}`='{$datum}'";
        }
        $fields = implode(',', $fields);

        $whereKey = key($where);
        $whereSql = "`{$whereKey}`='{$where[$whereKey]}'";
        $table = trim($table, '`');

        return $this->query("UPDATE `{$table}` SET {$fields} WHERE {$whereSql}");
    }

    /**
     * @param string $sql
     * @return bool|mysqli_result
     */
    public function query($sql)
    {
        $result = $this->db->query($sql, false);
        $this->checkError();
        return $result;
    }

    /**
     * Check Data base errors
     */
    private function checkError()
    {
        if (!empty($this->db->query_errors_list)) {
            $dbError = '';
            foreach ($this->db->query_errors_list as $key => $item) {
                $dbError .= ' Error  #' . $key . ' ' . implode("\n", $item);
            }
            throw new CCDNRuntimeException($dbError);
        }
    }

    /**
     * @param string $table
     * @param array $data
     *
     * @return bool
     */
    public function insert($table, $data)
    {
        $table = trim($table, '`');
        $fields = implode('`, `', array_keys($data));
        $values = implode("', '", array_values($data));
        return $this->query("INSERT INTO `{$table}` (`{$fields}`) VALUES ('{$values}')");
    }

    /**
     * @param string $sql
     * @param bool $multiple
     *
     * @return array
     */
    public function select($sql, $multiple = false)
    {
        if ($multiple) {
            $this->db->query($sql, false);
            $rows = [];
            while ($row = $this->db->get_row()) {
                $rows[] = $row;
            }
            $this->checkError();
            $this->db->free();
            return $rows;
        }

        $this->db->query($sql, false);
        $data = $this->db->get_row();
        $this->checkError();
        $this->db->free();

        return $data;
    }

    /**
     * @param string $table
     * @param array $where
     * @return bool|mysqli_result
     */
    public function delete($table, $where)
    {
        $table = trim($table, '`');
        $whereKey = key($where);
        $whereSql = "`{$whereKey}`='{$where[$whereKey]}'";
        return $this->query("DELETE FROM `{$table}` WHERE {$whereSql}");
    }

    /**
     * @param string $table
     *
     * @return bool|mysqli_result
     */
    public function deleteTable($table)
    {
        $table = trim($table, '`');
        return $this->query("DROP TABLE IF EXISTS `{$table}`");
    }
}
