<?php

namespace App\Models;

use CodeIgniter\Model;

class GenericModel extends Model
{
    protected $table = '';
    protected $primaryKey = 'id';
    protected $allowedFields = [];

    public function setTable(string $table)
    {
        $this->table = $table;

        $db = \Config\Database::connect();
        $fields = [];
        try {
            $res = $db->query("SHOW COLUMNS FROM `" . $db->escapeString($table) . "`");
            $cols = $res->getResultArray();
            foreach ($cols as $c) {
                $fields[] = $c['Field'];
                if ($c['Key'] === 'PRI') $this->primaryKey = $c['Field'];
            }
        } catch (\Throwable $e) {
            // biarkan kosong jika gagal
        }

        $this->allowedFields = $fields;
        return $this;
    }

    /**
     * Ambil daftar semua tabel dari database aktif.
     */
    public function getAllTables(): array
    {
        $db = \Config\Database::connect();
        return $db->listTables();
    }

    /**
     * (Opsional) Ambil jumlah record tiap tabel.
     */
    public function getTableCounts(): array
    {
        $db = \Config\Database::connect();
        $tables = $db->listTables();
        $result = [];

        foreach ($tables as $t) {
            try {
                $count = $db->table($t)->countAllResults();
                $result[$t] = $count;
            } catch (\Throwable $e) {
                $result[$t] = 0;
            }
        }

        return $result;
    }

    public function getTableFields(string $table): array
    {
        $db = \Config\Database::connect();
        $fields = [];
        try {
            $query = $db->query("SHOW COLUMNS FROM `" . $db->escapeString($table) . "`");
            foreach ($query->getResultArray() as $col) {
                $fields[] = $col['Field'];
            }
        } catch (\Throwable $e) {
            // jika gagal, kembalikan kosong
        }
        return $fields;
    }
    public function getTableMeta(string $table): array
    {
        $db = \Config\Database::connect();
        $fields = [];
        try {
            $query = $db->query("SHOW COLUMNS FROM `" . $db->escapeString($table) . "`");
            foreach ($query->getResultArray() as $col) {
                $fields[] = [
                    'name' => $col['Field'],
                    'type' => $col['Type'],
                    'key'  => $col['Key']
                ];
            }
        } catch (\Throwable $e) {
            // biarkan kosong jika gagal
        }
        return $fields;
    }

    public function getTableData(string $table)
    {
        return $this->db->table($table)->get()->getResultArray();
    }

    public function updateData($table, $id, $data)
    {
        $pk = $this->getPrimaryKey($table); // ambil primary key
        return $this->db->table($table)->where($pk, $id)->update($data);
    }

    public function hasField(string $table, string $fieldName): bool
    {
        $fields = $this->db->getFieldNames($table);
        return in_array($fieldName, $fields);
    }
}
