<?php

require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/response.php';

class ApiAuth
{

    /**
     * Validate API Key
     */
    public static function validateApiKey()
    {
        $headers = self::getHeaders();

        if (!isset($headers['X-API-KEY'])) {
            Response::error("API key missing", 401);
        }

        if ($headers['X-API-KEY'] !== API_KEY) {
            Response::error("Invalid API key", 403);
        }
    }



    /**
     * Get Employee ID from header
     */
    public static function employeeId()
    {
        $headers = self::getHeaders();

        if (isset($headers['X-EMPLOYEE-ID'])) {
            return (int)$headers['X-EMPLOYEE-ID'];
        }

        return null;
    }



    /**
     * Get Client IP
     */
    public static function ip()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        }

        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }

        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }



    /**
     * Get headers safely
     */
    private static function getHeaders()
    {
        if (function_exists('getallheaders')) {
            return getallheaders();
        }

        $headers = [];

        foreach ($_SERVER as $name => $value) {

            if (substr($name, 0, 5) == 'HTTP_') {

                $key = str_replace(
                    ' ',
                    '-',
                    ucwords(
                        strtolower(
                            str_replace('_', ' ', substr($name, 5))
                        )
                    )
                );

                $headers[$key] = $value;
            }
        }

        return $headers;
    }

}