<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class VerifyAppSignature implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Get the header sent by the Flutter app
        $clientSignature = $request->getHeaderLine('App-Signature');

        // Load the server's expected signature from the .env
        $validSignature = getenv('APP_SIGNATURE');

        // Check if signature is valid
        if ($clientSignature !== $validSignature) {
            return service('response')
                ->setStatusCode(403)
                ->setJSON([
                    'status' => false,
                    'message' => 'Forbidden: Invalid App Signature',
                ]);
        }

        // allow request to proceed
    }

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