<?php 
namespace App\Filters;

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

class UserPermissionFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // 1. Check if user is logged in
        if (!session('logged_user')) {
            return redirect()->to('/login')->with('error', 'Please login first');
        }

        // 2. Get required permission from arguments
        if (empty($arguments)) {
            throw new \RuntimeException('No permission specified for this route');
        }
        $requiredPermission = $arguments[0];

        // 3. Check permission
        if (!$this->hasUserPermission(session('user_id'), $requiredPermission)) {
            return redirect()->back()->with('error', 'You do not have permission to access this resource');
        }
    }

    protected function hasUserPermission($userId, $permissionModule)
    {
        $db = \Config\Database::connect();
        
        // Get the permission ID
        $permission = $db->table('permissions')
            ->select('id')
            ->where('module', $permissionModule)
            ->get()
            ->getRow();

        if (!$permission) {
            return false; // Permission doesn't exist
        }

        // Check user_permissions table
        return $db->table('user_permissions')
            ->where('user_id', $userId)
            ->where('permission_id', $permission->id)
            ->where('is_allowed', 1) // Only allowed permissions
            ->countAllResults() > 0;
    }

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