<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\AdminModel;
use App\Models\RoleModel;
use App\Models\ChurchModel;
use App\Models\AdminChurchModel;
use App\Models\AdminRoleModel;

class AdminsController extends BaseController
{
    public function index()
    {
        // ... (Logika untuk menampilkan daftar admin dengan filter akan kita buat nanti)
        $adminModel = new AdminModel();
        
        $data = [
            'admins' => $adminModel->select('admins.*, roles.name as role_name')
                                   ->join('admin_roles', 'admin_roles.admin_id = admins.id', 'left')
                                   ->join('roles', 'roles.id = admin_roles.role_id', 'left')
                                   ->paginate(10),
            'pager' => $adminModel->pager,
            'pageTitle' => lang('Admin/Admins.pageTitle'),
        ];
        return view('backend/admins/index', $data);
    }

    public function new()
    {
        $data = [
            'roles' => (new RoleModel())->findAll(),
            'churches' => (new ChurchModel())->where('is_active', 1)->findAll(),
            'pageTitle' => lang('Admin/Admins.newAdmin'),
        ];
        return view('backend/admins/new', $data);
    }

    public function create()
    {
        $rules = [
            'name'  => 'required|string|max_length[100]',
            'email' => 'required|valid_email|is_unique[admins.email]',
            'password' => 'required|min_length[8]',
            'password_confirm' => 'required|matches[password]',
            'role_id' => 'required|is_natural_no_zero',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $db = \Config\Database::connect();
        $db->transStart();

        // --- Tetap gunakan Model untuk tabel dengan auto-increment ---
        $adminModel = new AdminModel();
        $adminId = $adminModel->insert([
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'password' => $this->request->getPost('password'), // Model akan hash otomatis
        ]);
        
        // Jika pembuatan admin gagal, hentikan
        if (!$adminId) {
            $db->transRollback();
            return redirect()->back()->withInput()->with('error', 'Failed to create admin record.');
        }

        // --- PERBAIKAN: Gunakan Query Builder untuk tabel pivot ---
        // Ini lebih aman untuk tabel dengan primary key komposit.
        $db->table('admin_roles')->insert([
            'admin_id' => $adminId,
            'role_id'  => $this->request->getPost('role_id')
        ]);
        // --- AKHIR PERBAIKAN ---

        $churchIds = $this->request->getPost('church_ids') ?? [];
        if (!empty($churchIds)) {
            // syncChurches sudah menggunakan Query Builder (insertBatch), jadi ini aman.
            (new AdminChurchModel())->syncChurches($adminId, $churchIds);
        }

        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->withInput()->with('error', 'Failed to create admin.');
        }

        return redirect()->to(route_to('admin.admins.index'))->with('success', lang('Admin/Admins.createSuccess'));
    }
    
    public function edit($id = null)
    {
        $adminModel = new AdminModel();
        $admin = $adminModel->find($id);
        if (!$admin) {
            return redirect()->back()->with('error', lang('Admin/Admins.errorNotFound'));
        }

        $data = [
            'admin' => $admin,
            'roles' => (new RoleModel())->findAll(),
            'churches' => (new ChurchModel())->where('is_active', 1)->findAll(),
            'currentRole' => (new AdminRoleModel())->where('admin_id', $id)->first()['role_id'] ?? null,
            'currentChurches' => array_column((new AdminChurchModel())->where('admin_id', $id)->findAll(), 'church_id'),
            'pageTitle' => lang('Admin/Admins.editAdmin', [$admin->name]),
        ];
        return view('backend/admins/edit', $data);
    }
    
    public function update($id = null)
    {
        $adminModel = new AdminModel();
        $admin = $adminModel->find($id);
        if (!$admin) {
            return redirect()->route('admin.admins.index')->with('error', lang('Admin/Admins.errorNotFound'));
        }

        $rules = [
            'name'  => 'required|string|max_length[100]',
            'email' => "required|valid_email|is_unique[admins.email,id,{$id}]",
            'role_id' => 'required|is_natural_no_zero',
        ];

        if (!empty($this->request->getPost('password'))) {
            $rules['password'] = 'required|min_length[8]';
            $rules['password_confirm'] = 'required|matches[password]';
        }

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $db = \Config\Database::connect();
        $db->transStart();

        $adminData = [
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
        ];
        $adminModel->update($id, $adminData);

        $passwordPost = $this->request->getPost('password');
        if (!empty($passwordPost)) {
            $adminModel->update($id, ['password' => $passwordPost]);
        }

        
        // 1. Hapus role lama
        $db->table('admin_roles')->where('admin_id', $id)->delete();
        // 2. Insert role baru
        $db->table('admin_roles')->insert([
            'admin_id' => $id,
            'role_id'  => $this->request->getPost('role_id')
        ]);
        // --- AKHIR PERBAIKAN ---
        
        $adminChurchModel = new AdminChurchModel();
        $churchIds = $this->request->getPost('church_ids') ?? [];
        $adminChurchModel->syncChurches($id, $churchIds);
        
        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->withInput()->with('error', 'Failed to update admin.');
        }

        return redirect()->to(route_to('admin.admins.index'))->with('success', lang('Admin/Admins.updateSuccess'));
    }

    
    public function delete($id = null)
    {
        $adminModel = new AdminModel();
        $admin = $adminModel->find($id);
        if (!$admin) {
            return redirect()->route('admin.admins.index')->with('error', lang('Admin/Admins.errorNotFound'));
        }

        // Jangan izinkan Super Admin menghapus dirinya sendiri
        if ($id == session()->get('user_id')) {
            return redirect()->back()->with('error', 'You cannot delete your own account.');
        }

        if ($adminModel->delete($id)) {
            return redirect()->to(route_to('admin.admins.index'))->with('success', lang('Admin/Admins.deleteSuccess'));
        }

        return redirect()->to(route_to('admin.admins.index'))->with('error', 'Failed to delete admin.');
    }
}