<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use Firebase\JWT\JWT; // Import JWT library
use Firebase\JWT\Key;
class AuthMiddleware {
    protected $ci;
    public $algorithm=''; 
    public function __construct() {
        $this->ci =& get_instance();
    }

    public function verifyToken() {
        $header = $this->ci->input->get_request_header('Authorization');
        $token = null;
        if (!$header) {
            $this->ci->output
                ->set_status_header(400)
                ->set_output(json_encode(['status'=>400,'message' => 'Unauthorized Token','data'=>array()]));
            return false;
        }
         else {
           // Verify the token
            $key = 'alskdjfh123';
            $algorithm = 'HS256';
            try {
                // extract the token from the header
                if(!empty($header)) {
                    if (preg_match('/Bearer\s(\S+)/', $header, $matches)) {
                        $token = $matches[1];
                    }
                }
                $decoded = JWT::decode($token, new Key($key, 'HS256'));
                $email = $decoded->email;
                // Authentication successful
                return $email;
            } catch (Exception $e) {
                $this->ci->output
                ->set_status_header(400)
                ->set_output(json_encode(['status'=>400,'message' => 'Authentication failed','data'=>array()]));
                return false;
            }
        }
    }
}
