<?php

namespace App\Controllers;

use Config\Services;
use CodeIgniter\Controller;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Exceptions\ValidationException;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */
abstract class BaseController extends Controller
{
    /**
     * Instance of the main Request object.
     *
     * @var CLIRequest|IncomingRequest
     */
    protected $request;


    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['form', 'url', 'jwt', 'common_helper'];

    /**
     * Be sure to declare properties for any property fetch you initialized.
     * The creation of dynamic property is deprecated in PHP 8.2.
     */
    protected $webdocdb;
    protected $rsadb;
    protected $insdb;
    protected $session;
    protected $validation;

    /**
     * @return void
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        // Preload any models, libraries, etc, here.

        $this->session = \Config\Services::session();
        $this->webdocdb = \Config\Database::connect();
        $this->rsadb = \Config\Database::connect('rsadb');
        $this->insdb = \Config\Database::connect('insdb');
        
        $this->validation =  \Config\Services::validation();
    }


    public function getApiResponse(array $responseBody, int $code = ResponseInterface::HTTP_OK)
    {
        $message = $responseBody['message'];
        $statusCode = $responseBody['statusCode'];
        unset($responseBody['message'], $responseBody['statusCode']);
        return $this
            ->response
            ->setStatusCode($code)
            ->setJSON(
                [
                    'statusCode' => $statusCode,
                    'statusMessage' => (is_array($message)) ? $message : [$message],
                    'count' => empty($responseBody) ? 0 : (isset($responseBody['data']) && is_array($responseBody['data']) ? ((sizeof($responseBody['data']) < 1) ? 0 : count($responseBody['data'])) : count($responseBody)),
                    'payLoad' => empty($responseBody) ? NULL : (($responseBody['data']) ?? $responseBody),
                ]
            );
    }

    /**
     * Checks both fields in a request to get its content
     */
    public function getApiRequestInput(IncomingRequest $request)
    {
        $input = $request->getPost();
        if (empty($input)) {
            //convert request body to associative array
            $input = json_decode($request->getBody(), true);
        }
        return $input;
    }

    public function getApiGetRequestInput(IncomingRequest $request)
    {
        $input = $request->getGet();
        if (empty($input)) {
            //convert request body to associative array
            $input = json_decode($request->getBody(), true);
        }
        return $input;
    }

    /**
     * Checks both fields in a request to get its content
     * [use Config\Services;]
     */
    public function validateApiRequest($input, array $rules, array $messages = [])
    {
        $this->validator = Services::Validation()->setRules($rules);
        // If you replace the $rules array with the name of the group
        if (is_string($rules)) {
            $validation = config('Validation');

            // If the rule wasn't found in the \Config\Validation, we
            // should throw an exception so the developer can find it.
            if (!isset($validation->$rules)) {
                throw ValidationException::forRuleNotFound($rules);
            }

            // If no error message is defined, use the error message in the Config\Validation file
            if (!$messages) {
                $errorName = $rules . '_errors';
                $messages = $validation->$errorName ?? [];
            }

            $rules = $validation->$rules;
        }
        return $this->validator->setRules($rules, $messages)->run($input);
    }
}
