<?php

namespace App\Controller;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Laminas\Diactoros\ResponseFactory;
use App\Service\TelegramService;
use GuzzleHttp\Client;

class AuthController
{
    private $responseFactory;
    private $config;
    private $telegramService;
    private $httpClient;

    public function __construct(ResponseFactory $responseFactory, array $config)
    {
        $this->responseFactory = $responseFactory;
        $this->config = $config;
        $this->telegramService = new TelegramService($config);
        $this->httpClient = new Client();
    }

    public function login(Request $request, Response $response, $args): Response
    {
        $data = $this->parseRequestBody($request); // Assuming this method parses JSON correctly
        $password = $data['password'] ?? '';
        
        if ($this->authenticate($password)) {
            $this->updateAuthJson(true);
            $response = $response->withStatus(204);
        } else {
            $this->updateAuthJson(false);
            $responseData = ['status' => 'error', 'message' => 'Authentication failed'];
            $response = $response->withStatus(401); // Unauthorized status code
        }
        
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json');
    }

    public function logout(Request $request, Response $response, $args): Response
    {
        $this->updateAuthJson(false);
        $data = [
            'success' => true, 
            'message' => 'Logout successful'
        ];

        $response->getBody()->write(json_encode($data));
        return $response->withHeader('Content-Type', 'application/json');
    }
    

    public function checkAuth(Request $request, Response $response, $args): Response
    {
        $isAuthenticated = $this->checkAuthStatus();
        $data = ['isAuthenticated' => $isAuthenticated];

        $response->getBody()->write(json_encode($data));
        return $response->withHeader('Content-Type', 'application/json');
    }

    private function authenticate(string $password): bool
    {
        return $password === $this->config['PASSWORD'];
    }

    private function updateAuthJson(bool $isAuthenticated): void
    {
        $authFile = __DIR__ . '/../../data/auth.json';
        $timestamp = time();

        $authData = [
            'auth' => $isAuthenticated,
            'timestamp' => $isAuthenticated ? $timestamp + 900 : $timestamp // 15 minutes
        ];

        file_put_contents($authFile, json_encode($authData, JSON_PRETTY_PRINT));
    }

    private function checkAuthStatus(): bool
    {
        $authFile = __DIR__ . '/../../data/auth.json';
        if (!file_exists($authFile)) {
            return false;
        }

        $authData = json_decode(file_get_contents($authFile), true);
        if ($authData['auth'] && (time() <= $authData['timestamp'])) {
            return true;
        }

        $this->updateAuthJson(false);
        return false;
    }

    private function parseRequestBody(Request $request): array
    {
        $rawData = $request->getBody()->getContents();
        return json_decode($rawData, true) ?? [];
    }
}
