<?php

namespace App\Core;

class Request
{
    private array $get;
    private array $post;
    private array $server;
    private array $files;

    public function __construct()
    {
        $this->get = $this->sanitize($_GET);
        $this->post = $this->sanitize($_POST);
        $this->server = $_SERVER;
        $this->files = $_FILES;
    }

    public function path(): string
    {
        $path = $this->server['REQUEST_URI'] ?? '/';
        return explode('?', $path)[0];
    }

    public function method(): string
    {
        return $this->server['REQUEST_METHOD'] ?? 'GET';
    }

    public function get(string $key, $default = null) { return $this->get[$key] ?? $default; }
    public function post(string $key, $default = null) { return $this->post[$key] ?? $default; }
    public function input(string $key, $default = null) { return $this->post[$key] ?? ($this->get[$key] ?? $default); }
    public function all(): array { return array_merge($this->get, $this->post); }

    public function isAjax(): bool
    {
        return isset($this->server['HTTP_X_REQUESTED_WITH']) && $this->server['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
    }

    private function sanitize(array $data): array
    {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $data[$key] = $this->sanitize($value);
            } else {
                $data[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
            }
        }
        return $data;
    }
}
