<?php

namespace App\Controllers\View;

use App\Models\ConfigurationModel;
use CodeIgniter\Controller;

class ConfigurationController extends Controller
{
    protected $configModel;

    public function __construct()
    {
        $this->configModel = new ConfigurationModel();
    }

    // Method to load configuration management page
    public function index()
    {
        helper('url');
        return view('configuration/configuration_view', [
            'configEndpoint' => site_url('api/configuration'),
        ]);
    }

    public function addConfig()
    {
        // Retrieve POST data
        $configKey = $this->request->getPost('config_key');
        $configValue = $this->request->getPost('config_value');

        // Validate inputs (optional)
        if ($configKey && $configValue) {
            // Save to the database
            $this->configModel->save([
                'config_key' => $configKey,
                'config_value' => $configValue,
            ]);

            // Redirect to the configuration view page
            return redirect()->to('/configuration/configuration_view')->with('success', 'Configuration added.');
        }

        // If validation fails, reload the form with input
        return redirect()->back()->withInput()->with('error', 'Please fill in all required fields.');
    }

    
    // Method to edit an existing configuration
    public function editConfig($id)
    {
        $config = $this->configModel->find($id);

        if (strtolower($this->request->getMethod()) === 'post') {
            $key = trim((string) $this->request->getPost('config_key'));
            $value = trim((string) $this->request->getPost('config_value'));

            $this->configModel->update($id, [
                'config_key' => $key,
                'config_value' => $value
            ]);
            return redirect()->to('/configuration/configuration_view')->with('success', 'Configuration updated.');
        }
        return view('configuration/configuration_edit', ['config' => $config]);
    }

    public function deleteConfig($id)
    {
        if ($this->configModel->find($id)) {
            $this->configModel->delete($id);
            return redirect()->to('/configuration/configuration_view')->with('success', 'Configuration deleted successfully.');
        }

        return redirect()->to('/configuration/configuration_view')->with('error', 'Configuration not found.');
    }

    public function listData()
    {
        $rows = $this->configModel
            ->orderBy('id', 'ASC')
            ->findAll();

        $configs = array_map(static function ($row) {
            if (!is_array($row)) {
                return [];
            }
            return [
                'id'           => (int) ($row['id'] ?? 0),
                'config_key'   => (string) ($row['config_key'] ?? ''),
                'config_value' => (string) ($row['config_value'] ?? ''),
            ];
        }, $rows ?? []);

        return $this->response->setJSON(['configs' => $configs]);
    }
}
