<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Config\Services;
class SignedUrlFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $secretKey = 'your-secret-key'; // Change this to your secret key
        $expires = $request->getGet('expires');
        $signature = $request->getGet('signature');
        
        if (!$expires || !$signature) {
            return Services::response()->setStatusCode(403)->setBody('Forbidden');
        }
        
        if (time() > $expires) {
            $body = view('expired_link');
            return Services::response()->setStatusCode(403)->setBody($body);
        }
        
        $queryParams = $request->getGet();
        unset($queryParams['signature']);
        $route = $request->getPath();
        $expectedSignature = hash_hmac('sha256', $route . '?' . http_build_query($queryParams), $secretKey);
        
        if (!hash_equals($expectedSignature, $signature)) {
            return Services::response()->setStatusCode(403)->setBody('Invalid signature');
        }
        
        return true; // Allow the request
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do nothing here
    }
}


