<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtAuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        helper('jwt_helper');
        $header = $request->getHeaderLine('Authorization');

        if (!$header || !preg_match('/Bearer\s(\S+)/', $header, $matches)) {
            return service('response')->setJSON(['status' => 401, 'message' => 'Token required'])->setStatusCode(401);
        }

        $decodedToken = validateJWT($matches[1]);

        if (!$decodedToken) {
            return service('response')->setJSON(['status' => 401, 'message' => 'Invalid or expired token'])->setStatusCode(401);
        }

        // Extract date info from token
        $userId = $decodedToken['data']->id ?? null;
        $lastLogin = $decodedToken['data']->last_login_datetime ?? null;
        $role = $decodedToken['data']->role_id ?? 'agent';

        // Role-based restriction (if $arguments are passed)
        if ($arguments && isset($role)) {
            $allowedRoles = array_map('strtolower', array_map('trim', $arguments));
            $userRole = strtolower(trim($role));
        
            if (!in_array($userRole, $allowedRoles)) {
                return service('response')->setJSON([
                    'status' => 401, 
                    'message' => 'Access denied. You do not have permission.'
                ])->setStatusCode(401);
            }
        }

        if ($userId && $lastLogin) {

            $lastLoginDate = date('Y-m-d', strtotime($lastLogin));
            $todayDate = date('Y-m-d');

            if ($lastLoginDate !== $todayDate) {

                $attendanceModel = new \App\Models\StaffAttendanceModel();

                // Find today's (previous) attendance record (yesterday)
                $attendance = $attendanceModel
                    ->where('staff_id', $userId)
                    ->where('DATE(login_datetime)', $lastLoginDate)
                    ->first();

                if ($attendance && !$attendance['logout_datetime']) {
                    $attendanceModel->update($attendance['id'], [
                        'logout_datetime' => date('Y-m-d H:i:s')
                    ]);
                }

                log_message('info', sprintf(
                    'Auto logout triggered for Staff ID: %s. Previous login date: %s, Current date: %s, Logout time updated at: %s',
                    $userId,
                    $lastLoginDate,
                    $todayDate,
                    date('Y-m-d H:i:s')
                ));

                return service('response')->setJSON([
                    'status' => 403,
                    'message' => 'Session expired, please login again'
                ])->setStatusCode(403);
            }
        }

        return;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No action needed
    }
}
