<?php

/**
 * Smart Reporting Package
 * Version 9.0.0
 * Author : Webuccino
 * All copyrights are preserved to Webuccino
 * URL : https://mysqlreports.com/
 */
class Writer {

    private $table;
    private $primary_key;
    private $db_handler;
    private $data;
    private static $connection = "";

    public function __construct($table, array $data, $dashboard_connection, $primary_key = "") {
        $this->table = $table;
        $this->primary_key = $primary_key;
        $this->data = $data;
      $this->db_handler = $dashboard_connection;
      
        self::$connection = $dashboard_connection;
    }

    /* insert one new record in a table */

    public function insert() {

        $fields = array_keys($this->data);
        $placeholders = "(";
        $parameters = array();
        foreach ($this->data as $value) {
            $placeholders .= "?,";
            $parameters[] = $value;
        }
        $placeholders .= ")";
        $placeholders = str_replace(",)", ")", $placeholders);
        $query = "insert into `" . $this->table . "`(`" . implode("`,`", $fields) . "`)VALUES $placeholders";
        return $this->db_handler->command($query, $parameters);
    }

    /* update one new record in a table */

    public function update($primary_key_value, $primary_key_name = "id") {
        $fields = array_keys($this->data);
        $placeholders = "";
        $parameters = array();
        foreach ($this->data as $key => $value) {
            $placeholders .= " `$key` = ? ,";
            $parameters[] = $value;
        }
        $placeholders .= ")";
        $placeholders = str_replace(",)", "", $placeholders);
        $query = "UPDATE  `" . $this->table . "` SET $placeholders where `$primary_key_name` = $primary_key_value ";

        if ($this->db_handler->command($query, $parameters) || $this->db_handler->command($query, $parameters) === 0)
            return $primary_key_value;
        else
            return false;
    }

    public function delete_by_id($id, $id_column) {
        $query = "delete  FROM `" . $this->table . "` WHERE `" . $id_column . "` = ?";
        $parameters = array($id);
        $result = $this->db_handler->command($query, $parameters);
        if ($result || $result === 0)
            return true;
        else
            return false;
    }
    
    public static function log($log_array){
         $fields = array_keys($log_array);
        $placeholders = "(";
        $parameters = array();
        foreach ($log_array as $value) {
            $placeholders .= "?,";
            $parameters[] = $value;
        }
        $placeholders .= ")";
        $placeholders = str_replace(",)", ")", $placeholders);
        $query = "insert into `" .tables_prefix.table_log . "`(`" . implode("`,`", $fields) . "`)VALUES $placeholders";
       // return  self::$connection->command($query, $parameters);
    }

}
