<?php

namespace App\Models;

use CodeIgniter\Model;

class AdminChurchModel extends Model
{
    protected $table            = 'admin_churches';
    // CI4 hanya mendukung 1 primary key, jadi kita set manual
    protected $primaryKey       = ['admin_id', 'church_id']; 
    protected $useAutoIncrement = false;
    protected $returnType       = 'array';

    protected $allowedFields    = ['admin_id', 'church_id'];

    // Tidak menggunakan timestamps
    protected $useTimestamps = false;

    /**
     * Ambil daftar church_id yang dapat diakses oleh admin tertentu
     */
    public function getChurchIdsByAdmin($adminId): array
    {
        return $this->where('admin_id', $adminId)
                    ->findAll();
    }

    /**
     * Cek apakah admin memiliki akses ke gereja tertentu
     */
    public function hasAccessToChurch($adminId, $churchId): bool
    {
        return $this->where('admin_id', $adminId)
                    ->where('church_id', $churchId)
                    ->countAllResults() > 0;
    }

    /**
     * Simpan ulang semua akses gereja untuk admin tertentu
     */
    public function syncChurches(int $adminId, array $churchIds)
    {
        
        $this->where('admin_id', $adminId)->delete();
       
        $dataToInsert = [];
        foreach ($churchIds as $churchId) {
            $dataToInsert[] = [
                'admin_id'  => $adminId,
                'church_id' => $churchId
            ];
        }

        if (!empty($dataToInsert)) {
            $builder = $this->db->table($this->table);
            $builder->insertBatch($dataToInsert);
        }
    }
}
