<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\ChurchModel;

class ChurchesController extends BaseController
{
    public function index()
    {
        $churchModel = new ChurchModel();
        $data = [
            'churches'  => $churchModel->paginate(10), // Model akan handle orderBy
            'pager'     => $churchModel->pager,
            'pageTitle' => lang('Admin/Churches.pageTitle'),
        ];
        return view('backend/churches/index', $data);
    }

    public function new()
    {
        $data = [ 'pageTitle' => lang('Admin/Churches.newChurch') ];
        return view('backend/churches/new', $data);
    }

    public function create()
    {
        $rules = $this->getValidationRules();
        unset($rules['id']);

        $postData = $this->request->getPost();
        $postData['is_active'] = isset($postData['is_active']) ? 1 : 0;

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

        (new ChurchModel())->save($this->validator->getValidated());
        return redirect()->to(route_to('admin.churches.index'))->with('success', lang('Admin/Churches.createSuccess'));
    }
    
    public function edit($id = null)
    {
        $church = (new ChurchModel())->find($id);
        if (!$church) {
            return redirect()->back()->with('error', lang('Admin/Churches.errorNotFound'));
        }
        $data = [
            'church'    => $church,
            'pageTitle' => lang('Admin/Churches.editChurch', [$church->name]),
        ];
        return view('backend/churches/edit', $data);
    }
    
    public function update($id = null)
    {
        $postData = $this->request->getPost();
        $postData['id'] = $id; 
        $postData['is_active'] = isset($postData['is_active']) ? 1 : 0;

        $rules = $this->getValidationRules($id); 

        if (!$this->validateData($postData, $rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }
        
        $dataToSave = [
            'name'       => $postData['name'],
            'city'       => $postData['city'],
            'region'     => $postData['region'],
            'is_gka'     => (int)$postData['is_gka'],
            'sort_order' => (int)$postData['sort_order'],
            'is_active'  => (int)$postData['is_active'],
        ];

        //(new ChurchModel())->update($id, $dataToSave);
        $db = \Config\Database::connect();
        $builder = $db->table('churches');
        $builder->where('id', $id);
        $builder->update($dataToSave);
        
        return redirect()->to(route_to('admin.churches.index'))->with('success', lang('Admin/Churches.updateSuccess'));
    }

    public function delete($id = null)
    {
        try {
            (new ChurchModel())->delete($id);
        } catch (\Exception $e) {
            return redirect()->to(route_to('admin.churches.index'))->with('error', $e->getMessage());
        }
        return redirect()->to(route_to('admin.churches.index'))->with('success', lang('Admin/Churches.deleteSuccess'));
    }

    private function getValidationRules(int $id = null): array
    {
        return [
            'id'         => 'permit_empty|is_natural_no_zero',
            'name'       => "required|string|max_length[150]|is_unique[churches.name,id,{id}]",
            'city'       => 'permit_empty|string|max_length[100]',
            'region'     => 'permit_empty|string|max_length[100]',
            'is_gka'     => 'required|in_list[0,1]',
            'sort_order' => 'required|is_natural',
            'is_active'  => 'required|in_list[0,1]',
        ];
    }    

}