<?php

namespace App\Controllers;

use App\Models\SetupModel;
use App\Validation\SetupValidation;
use CodeIgniter\Config\Services;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;

class SetupController extends ResourceController
{
    protected $helpers = ['form', 'custom'];
    protected $model;
    protected SetupValidation $validation;
    public function __construct()
    {
        $this->model = new SetupModel();
        $this->validation = new SetupValidation();
    }

    public function new()
    {
        $data = $this->model->getData(1);
        return view('backend/settings', ['setup' => $data]);
    }




    public function edit($id = null)
    {
        $data = $this->model->getData(1);
        return view('backend/edit_settings', ['setup' => $data, 'id' => $id]);
    }
    public function update($id = null)
    {
        $validator = Services::validation($this->validation);
        $validator->setRuleGroup('validateSetupOnUpdate');
        if ($validator->withRequest($this->request)->run()) {
            $valid_data = $validator->getValidated();
            $update = $this->model->update($id, $valid_data);
            if ($update) {
                return redirect('settings')
                    ->with('success', 'Settings was updated successfully');
            }
            return redirect()->back()
                ->withInput()
                ->with('fail', 'Failed to update setings');
        }
        $data = $this->model->getData(1);
        return view('backend/edit_settings', ['setup' => $data, 'id' => $id, 'validation' => $validator->getErrors()]);
    }
}
