<?php

namespace App\Models;

use CodeIgniter\Model;

class Common_model extends Model
{
    public function __construct()
    {
        parent::__construct();
        // ❌ NO $this->db connection here
    }

    /* ================= INSERT ================= */
    public function insertData(string $table, array $data)
    {
        if (empty($table) || empty($data)) {
            return false;
        }

        $this->db->table($table)->insert($data);
        return $this->db->insertID();
    }

    /* ================= SELECT ================= */
    public function getData(
        string $table,
        string $fields = '*',
        array $where = [],
        array $whereIn = [],
        string $orderBy = '',
        $limit = null
    ) {
        $builder = $this->db->table($table)->select($fields);

        if (!empty($where)) {
            $builder->where($where);
        }

        if (!empty($whereIn)) {
            foreach ($whereIn as $column => $values) {
                $builder->whereIn($column, $values);
            }
        }

        if (!empty($orderBy)) {
            $builder->orderBy($orderBy);
        }

        if (!empty($limit)) {
            $builder->limit($limit);
        }

        return $builder->get()->getResultArray();
    }

    /* ================= UPDATE ================= */
    public function updateData(string $table, array $data, array $where)
    {
        if (empty($table) || empty($data) || empty($where)) {
            return false;
        }

        return $this->db->table($table)
                        ->where($where)
                        ->update($data);
    }

    /* ================= DELETE ================= */
    public function deleteData(string $table, array $where)
    {
        if (empty($table) || empty($where)) {
            return false;
        }

        return $this->db->table($table)
                        ->where($where)
                        ->delete();
    }

    /* ================= COUNT ================= */
    public function countTable(string $table, array $where = [])
    {
        $builder = $this->db->table($table);

        if (!empty($where)) {
            $builder->where($where);
        }

        return $builder->countAllResults();
    }
}
