<?php 
namespace App\Filters;

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

class NewPermissionsFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // 1. Check if user is logged in
        if (!session('logged_user')) {
            session()->setTempdata('error', 'Your session has expired. Please login again.', 3);
            return redirect()->to('/');
        }

        // Get user group
        $authloginModel = new \App\Models\AuthLoginModel();
        $userData = $authloginModel->getUserDetails(session('logged_user'));
        $gID = $userData->group_id;

        // 2. Get required permission
        $router = service('router');
        $requiredPermission = $this->generatePermissionString(
            $router->controllerName(),
            $router->methodName()
        );

        // 3. Check permission
        $hasPerm = $this->hasPermission($gID, $requiredPermission);
        
        if (!$hasPerm) {
            session()->setFlashdata('warning', 'Access denied');
            return redirect()->to(previous_url());
        }
    }

    protected function generatePermissionString($controllerName, $methodName)
    {
        // Handle module controllers (e.g., "\Modules\Sales\Controllers\Transactions")
        if (strpos($controllerName, 'Modules\\') === 0) {
            $parts = explode('\\', $controllerName);
            $controller = end($parts); // Gets "Transactions"
        } 
        // Handle app controllers (e.g., "\App\Controllers\Settings")
        else {
            $parts = explode('\\', $controllerName);
            $controller = end($parts); // Gets "Settings"
        }

        // Remove "Controller" suffix if present
        $controller = preg_replace('/Controller$/', '', $controller);
        
        return $controller . '.' . $methodName;
    }

     protected function hasPermission($groupId, $permissionModule)
    {
        $db = \Config\Database::connect();
        
        // 1. Get the current permission and verify module match
        $currentPermission = $db->table('permissions')
            ->select('id, parent_id, module')
            ->where('module', $permissionModule)
            ->get()
            ->getRow();

        if (!$currentPermission) {
            return false;
        }

        // 2. Get all valid permission IDs (current + children if parent)
        $validPermissionIds = [$currentPermission->id];
        
        if (empty($currentPermission->parent_id)) {
            $children = $db->table('permissions')
                ->select('id, module')
                ->where('parent_id', $currentPermission->id)
                ->get()
                ->getResult();
            
            foreach ($children as $child) {
                $validPermissionIds[] = $child->id;
            }
        }

        // 3. Check if group has any valid permission for this module
        $hasPermission = $db->table('user_group_permissions ugp')
            ->join('permissions p', 'ugp.permission_id = p.id')
            ->where('ugp.group_id', $groupId)
            ->whereIn('ugp.permission_id', $validPermissionIds)
            ->where('p.module', $permissionModule) // Strict module match
            ->countAllResults() > 0;

        return $hasPermission;
    }
    

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