<?php

namespace App\Models;

use CodeIgniter\Model;

class SeminarModel extends Model
{
    protected $table = 'seminars';
    protected $primaryKey = 'seminar_id';
    protected $allowedFields = ['seminar_key', 'seminar_title', 'seminar_link', 'seminar_status', 'seminar_date_updated'];

    public function __construct()
    {
        parent::__construct();
        $this->db = \Config\Database::connect();
    }

    public function addParent(array $data): int|bool
    {
        $this->db->table($this->table)->insert($data);
        if ($this->db->affectedRows() > 0) {
            return $this->db->insertID();
        }
        return false;
    }

    public function getAllParent(): array|bool
    {
        $query = $this->db->table($this->table)
            ->select('*')
            ->orderBy('seminar_id', 'DESC')
            ->get();

        return $query->getResultArray() ?: false;
    }

    public function getAllParentForSite(): array|bool
    {
        $query = $this->db->table($this->table)
            ->select('*')
            ->where('seminar_status', 1)
            ->orderBy('seminar_id', 'DESC')
            ->get();

        return $query->getResultArray() ?: false;
    }

    public function getAllTopParentForSite(): array|bool
    {
        $query = $this->db->table($this->table)
            ->select('*')
            ->where('seminar_status', 1)
            ->get();

        $data = $query->getResultArray();
        if (empty($data)) {
            return false;
        }

        return array_filter($data, fn($value) => !empty($value['article_like']));
    }

    public function getParentByKey(string $param): array|bool
    {
        $query = $this->db->table($this->table)
            ->select('*')
            ->where('seminar_key', $param)
            ->get();

        return $query->getRowArray() ?: false;
    }

    public function getParentByTitle(string $param): array|bool
    {
        $query = $this->db->table($this->table)
            ->select('*')
            ->like('judgement_title', $param)
            ->join('categories', 'categories.category_key = judgements.judgement_category_key')
            ->get();

        return $query->getRowArray() ?: false;
    }

    public function getParentByCategoryKey(string $param): array|bool
    {
        $query = $this->db->table($this->table)
            ->select('*')
            ->where('judgement_category_key', $param)
            ->orderBy('seminar_id', 'DESC')
            ->get();

        return $query->getResultArray() ?: false;
    }

    public function updateParentByKey(string $param, array $data): bool
    {
        return $this->db->table($this->table)
            ->where('seminar_key', $param)
            ->update($data);
    }

    public function deleteParentByKey(string $param): bool
    {
        $result = $this->db->table($this->table)
            ->where('seminar_key', $param)
            ->delete();

        return $this->db->affectedRows() > 0;
    }
}