<?php

namespace App;

class Request
{
    private $method;
    private $path;
    private $data;
    private $headers;

    public function __construct()
    {
        $this->method = $_SERVER['REQUEST_METHOD'];
        $this->path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $this->headers = function_exists('getallheaders') ? getallheaders() : [];

        if ($this->method === 'POST' || $this->method === 'PUT') {
            $input = file_get_contents('php://input');
            $this->data = json_decode($input, true) ?? [];
        } else {
            $this->data = $_GET;
        }
    }

    public function getMethod()
    {
        return $this->method;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function get($key, $default = null)
    {
        return $this->data[$key] ?? $default;
    }

    public function getAll()
    {
        return $this->data;
    }

    public function getHeader($key, $default = null)
    {
        return $this->headers[$key] ?? $default;
    }

    public function validate($rules)
    {
        $errors = [];
        foreach ($rules as $field => $rule) {
            if ($rule === 'required' && empty($this->data[$field])) {
                $errors[$field] = "Field '$field' is required";
            }
        }
        return $errors;
    }
}