<?php

namespace lib\Core\Http;

class Request extends Http
{
  private array $_datas = [];
  public function __construct(array $params = [])
  {
    parent::__construct();
    $this->_datas = array_merge($_GET, $_POST, $params);
  }

  public function all(): array
  {
    return $this->_datas;
  }

  public function get(?string $key = null, $default = null): mixed
  {
    if ($key === null) {
      return $this->all();
    }
    return $this->_datas[$key] ?? $default;
  }

  public function only(array $keys): array
  {
    return array_intersect_key($this->_datas, array_flip($keys));
  }

  public function has(string $key): bool
  {
    return array_key_exists($key, $this->_datas);
  }

  /**
   * Validator 연동
   */
  //사용예:
  //   $request = new Request();

  // $validation = $request->validate([
  //     'username' => 'required|alpha_numeric|min[4]',
  //     'email' => 'required|email',
  //     'password' => 'required|min[6]'
  // ]);

  // if ($validation !== true) {
  //     // 에러 처리
  //     print_r($validation);
  // } else {
  //     // 통과
  //     echo "유효성 검사 통과!";
  // }
  public function validate(array $rules, array $messages = []): bool|array
  {
    $validator = new Validator();
    $validator->setData($this->all())->setRules($rules)->setMessages($messages);

    if (!$validator->run()) {
      return $validator->errors();
    }

    return true;
  }
}
