<?php

namespace App\Models;

use CodeIgniter\Model;

class Crud extends Model
{

    var $data = array();

    public function __construct()
    {
        $this->data['path'] = PATH;
        $this->data['template'] = TEMPLATE;
    }

    public
    function ExecuteSQL($Query, $view = false)
    {
        $db = db_connect();
        $records = $db->query($Query)->getResult('array');
        if ($view)
            echo $db->getLastQuery() . "<hr>";
        $db->close();
        return $records;
    }

    public
    function AddRecord($table, $records, $view = false)
    {
        $db = db_connect();
        $db->db_debug = false;
        $builder = $db->table($table);
        $builder->insert($records);
        if ($view) {
            $QUERY = $db->getLastQuery() . ";<br>";
            // $Main = new Main();
            //  $Main->SendEmail('info@orixestech.com', 'Umrah Furas :: Insert Query Error', $QUERY);
            echo $QUERY;
        }
        $insertID = $db->insertID();
        $db->close();
        return $insertID;
    }

    public
    function DeleteRecord($table, $where)
    {
        $db = db_connect();
        $builder = $db->table($table);
        if (count($where) > 0) {
            $builder->where($where);
        }
        $builder->delete();
        $db->close();

        return true;
    }

    public
    function SingleRecord($table, $wheres = array(), $view = false)
    {
        $db = db_connect();
        $builder = $db->table($table);

        $builder->select('*');
        if (count($wheres) > 0) {
            $builder->where($wheres);
        }
        $query = $builder->get();
        $record = (array)$query->getRowArray();
        if (!is_array($record)) {
            $record = array();
        }
        //print_r($record);
        //$record = $query->getRowArray();
        if ($view) echo $db->getLastQuery() . "<hr>";

        $db->close();
        return $record;
    }

    public
    function UpdateRecord($table, $records, $where)
    {
        $db = db_connect();
        $builder = $db->table($table);
        if (count($where) > 0) {
            $builder->where($where);
        }
        $builder->update($records);
        // echo $db->getLastQuery() . "<hr>";


        $db->close();
        return true;
    }


}
