# Granular Permissions System for Station Module - Design Document

## Overview

This document outlines the design for a comprehensive, hierarchical permission system for the FuelPlus Station module. The system enables fine-grained access control where users can have different permission levels for different resources (Pumps, Tanks, Nozzles, Shifts, Reports).

---

## 1. Permission Hierarchy Diagram

### Mermaid Diagram - Permission Structure

```mermaid
graph TB
    subgraph Station_Module
        subgraph Pumps
            P_VIEW[View Pumps]
            P_CREATE[Create Pump]
            P_EDIT[Edit Pump]
            P_UPDATE[Update Pump Status]
            P_DELETE[Delete Pump]
        end
        
        subgraph Tanks
            T_VIEW[View Tanks]
            T_CREATE[Create Tank]
            T_EDIT[Edit Tank]
            T_UPDATE[Update Tank Level]
            T_ADJUST[Tank Adjustment]
            T_DELETE[Delete Tank]
        end
        
        subgraph Nozzles
            N_VIEW[View Nozzles]
            N_CREATE[Create Nozzle]
            N_EDIT[Edit Nozzle]
            N_CALIBRATE[Calibrate Nozzle]
            N_DELETE[Delete Nozzle]
        end
        
        subgraph Shifts
            S_VIEW[View Shifts]
            S_CREATE[Create Shift]
            S_EDIT[Edit Shift]
            S_START[Start Shift]
            S_CLOSE[Close Shift]
            S_APPROVE[Approve Shift]
            S_DELETE[Delete Shift]
        end
        
        subgraph Reports
            R_VIEW[View Reports]
            R_SALES[Sales Reports]
            R_FINANCIAL[Financial Reports]
            R_EXPORT[Export Reports]
            R_ANALYTICS[Analytics]
        end
        
        subgraph WorkPeriods
            WP_VIEW[View Work Periods]
            WP_MANAGE[Manage Work Periods]
        end
        
        subgraph CashCollection
            CC_VIEW[View Collections]
            CC_CREATE[Create Collection]
            CC_APPROVE[Approve Collection]
        end
        
        subgraph Licenses
            L_VIEW[View Licenses]
            L_MANAGE[Manage Licenses]
        end
    end
    
    P_VIEW --> P_CREATE
    P_CREATE --> P_EDIT
    P_EDIT --> P_UPDATE
    P_UPDATE --> P_DELETE
    
    T_VIEW --> T_CREATE
    T_CREATE --> T_EDIT
    T_EDIT --> T_UPDATE
    T_UPDATE --> T_ADJUST
    T_ADJUST --> T_DELETE
    
    R_VIEW --> R_SALES
    R_SALES --> R_FINANCIAL
    R_FINANCIAL --> R_EXPORT
    R_EXPORT --> R_ANALYTICS
```

### Permission Categories by Module

| Module | Permissions |
|--------|-------------|
| **Stations** | view, create, edit, delete, manage_settings |
| **Pumps** | view, create, edit, update_status, delete |
| **Tanks** | view, create, edit, update_level, adjust, delete |
| **Nozzles** | view, create, edit, calibrate, delete |
| **Shifts** | view, create, edit, start, close, approve, delete |
| **Work Periods** | view, manage |
| **Reports** | view, sales, financial, export, analytics |
| **Cash Collections** | view, create, approve, delete |
| **Fuel Requests** | view, create, approve, delete |
| **Maintenance** | view, create, update, delete |
| **Licenses** | view, manage |
| **Users** | view, create, edit, assign_role, delete |

### Permission Action Types

| Action | Description |
|--------|-------------|
| `view` | View list and details |
| `create` | Create new records |
| `edit` | Edit existing records |
| `update` | Update specific attributes (e.g., status) |
| `delete` | Delete records |
| `approve` | Approve actions (shifts, collections) |
| `export` | Export data |
| `manage` | Full CRUD + settings |

---

## 2. Database Schema Design

### Entity Relationship Diagram

```mermaid
erDiagram
    Users ||--o{ UserRoles : has
    Roles ||--o{ RolePermissions : has
    Users ||--o{ UserPermissions : has
    
    Roles {
        bigint id PK
        string name "unique: e.g., station_manager, pump_operator"
        string description
        string guard_name "web, api"
        bigint company_id "nullable: null for global roles"
        boolean is_system "true for system roles"
        timestamps
    }
    
    Permissions {
        bigint id PK
        string name "e.g., pumps.view, pumps.create"
        string description
        string module "e.g., pumps, tanks, shifts"
        string guard_name "web, api"
        timestamps
    }
    
    UserRoles {
        bigint user_id PK, FK
        bigint role_id PK, FK
        bigint company_id "nullable: for company-specific role assignment"
        bigint station_id "nullable: for station-specific role assignment"
        timestamps
    }
    
    RolePermissions {
        bigint role_id PK, FK
        bigint permission_id PK, FK
        timestamps
    }
    
    UserPermissions {
        bigint user_id PK, FK
        bigint permission_id PK, FK
        boolean is_denied "true if this is a denied permission"
        timestamps
    }
```

### Migration Files Structure

#### 2.1 Permissions Table Migration

**File:** `database/migrations/2026_02_25_000001_create_permissions_table.php`

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('permissions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique(); // e.g., 'pumps.view', 'pumps.create'
            $table->string('description')->nullable();
            $table->string('module'); // e.g., 'pumps', 'tanks', 'shifts'
            $table->string('guard_name')->default('web');
            $table->unsignedInteger('sort_order')->default(0);
            $table->timestamps();
            
            $table->index(['module', 'name']);
        });
    }
};
```

#### 2.2 Roles Table Migration

**File:** `database/migrations/2026_02_25_000002_create_roles_table.php`

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique(); // e.g., 'station_manager', 'pump_operator'
            $table->string('display_name'); // e.g., 'Station Manager'
            $table->string('description')->nullable();
            $table->string('guard_name')->default('web');
            $table->unsignedBigInteger('company_id')->nullable();
            $table->boolean('is_system')->default(false);
            $table->timestamps();
            
            $table->foreign('company_id')
                ->references('id')
                ->on('companies')
                ->onDelete('cascade');
            
            $table->index('company_id');
        });
    }
};
```

#### 2.3 Role Permissions Pivot Table Migration

**File:** `database/migrations/2026_02_25_000003_create_role_permissions_table.php`

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('role_permissions', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('permission_id');
            $table->timestamps();
            
            $table->primary(['role_id', 'permission_id']);
            
            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');
            
            $table->foreign('permission_id')
                ->references('id')
                ->on('permissions')
                ->onDelete('cascade');
        });
    }
};
```

#### 2.4 User Roles Pivot Table Migration

**File:** `database/migrations/2026_02_25_000004_create_user_roles_table.php`

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('user_roles', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('company_id')->nullable();
            $table->unsignedBigInteger('station_id')->nullable();
            $table->timestamp('assigned_at')->useCurrent();
            $table->unsignedBigInteger('assigned_by')->nullable();
            $table->timestamps();
            
            $table->primary(['user_id', 'role_id', 'company_id', 'station_id']);
            
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
            
            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');
            
            $table->foreign('company_id')
                ->references('id')
                ->on('companies')
                ->onDelete('cascade');
            
            $table->foreign('station_id')
                ->references('id')
                ->on('stations')
                ->onDelete('cascade');
            
            $table->foreign('assigned_by')
                ->references('id')
                ->on('users')
                ->onDelete('set null');
            
            $table->index(['company_id', 'station_id']);
        });
    }
};
```

#### 2.5 User Permissions Pivot Table Migration

**File:** `database/migrations/2026_02_25_000005_create_user_permissions_table.php`

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('user_permissions', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('permission_id');
            $table->boolean('is_denied')->default(false); // For explicit denies
            $table->timestamps();
            
            $table->primary(['user_id', 'permission_id']);
            
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
            
            $table->foreign('permission_id')
                ->references('id')
                ->on('permissions')
                ->onDelete('cascade');
        });
    }
};
```

---

## 3. Permission Seeder - Initial Permissions

**File:** `database/seeders/PermissionSeeder.php`

```php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PermissionSeeder extends Seeder
{
    public function run(): void
    {
        $permissions = [
            // Station permissions
            ['name' => 'stations.view', 'description' => 'View stations list and details', 'module' => 'stations', 'sort_order' => 1],
            ['name' => 'stations.create', 'description' => 'Create new stations', 'module' => 'stations', 'sort_order' => 2],
            ['name' => 'stations.edit', 'description' => 'Edit station details', 'module' => 'stations', 'sort_order' => 3],
            ['name' => 'stations.delete', 'description' => 'Delete stations', 'module' => 'stations', 'sort_order' => 4],
            ['name' => 'stations.manage_settings', 'description' => 'Manage station settings', 'module' => 'stations', 'sort_order' => 5],
            
            // Pump permissions
            ['name' => 'pumps.view', 'description' => 'View pumps list and details', 'module' => 'pumps', 'sort_order' => 10],
            ['name' => 'pumps.create', 'description' => 'Create new pumps', 'module' => 'pumps', 'sort_order' => 11],
            ['name' => 'pumps.edit', 'description' => 'Edit pump details', 'module' => 'pumps', 'sort_order' => 12],
            ['name' => 'pumps.update_status', 'description' => 'Update pump status', 'module' => 'pumps', 'sort_order' => 13],
            ['name' => 'pumps.delete', 'description' => 'Delete pumps', 'module' => 'pumps', 'sort_order' => 14],
            
            // Tank permissions
            ['name' => 'tanks.view', 'description' => 'View tanks list and details', 'module' => 'tanks', 'sort_order' => 20],
            ['name' => 'tanks.create', 'description' => 'Create new tanks', 'module' => 'tanks', 'sort_order' => 21],
            ['name' => 'tanks.edit', 'description' => 'Edit tank details', 'module' => 'tanks', 'sort_order' => 22],
            ['name' => 'tanks.update_level', 'description' => 'Update tank fuel level', 'module' => 'tanks', 'sort_order' => 23],
            ['name' => 'tanks.adjust', 'description' => 'Make tank adjustments', 'module' => 'tanks', 'sort_order' => 24],
            ['name' => 'tanks.delete', 'description' => 'Delete tanks', 'module' => 'tanks', 'sort_order' => 25],
            
            // Nozzle permissions
            ['name' => 'nozzles.view', 'description' => 'View nozzles list and details', 'module' => 'nozzles', 'sort_order' => 30],
            ['name' => 'nozzles.create', 'description' => 'Create new nozzles', 'module' => 'nozzles', 'sort_order' => 31],
            ['name' => 'nozzles.edit', 'description' => 'Edit nozzle details', 'module' => 'nozzles', 'sort_order' => 32],
            ['name' => 'nozzles.calibrate', 'description' => 'Calibrate nozzles', 'module' => 'nozzles', 'sort_order' => 33],
            ['name' => 'nozzles.delete', 'description' => 'Delete nozzles', 'module' => 'nozzles', 'sort_order' => 34],
            
            // Shift permissions
            ['name' => 'shifts.view', 'description' => 'View shifts list and details', 'module' => 'shifts', 'sort_order' => 40],
            ['name' => 'shifts.create', 'description' => 'Create new shifts', 'module' => 'shifts', 'sort_order' => 41],
            ['name' => 'shifts.edit', 'description' => 'Edit shift details', 'module' => 'shifts', 'sort_order' => 42],
            ['name' => 'shifts.start', 'description' => 'Start a shift', 'module' => 'shifts', 'sort_order' => 43],
            ['name' => 'shifts.close', 'description' => 'Close a shift', 'module' => 'shifts', 'sort_order' => 44],
            ['name' => 'shifts.approve', 'description' => 'Approve/reconcile shifts', 'module' => 'shifts', 'sort_order' => 45],
            ['name' => 'shifts.delete', 'description' => 'Delete shifts', 'module' => 'shifts', 'sort_order' => 46],
            
            // Work Period permissions
            ['name' => 'work_periods.view', 'description' => 'View work periods', 'module' => 'work_periods', 'sort_order' => 50],
            ['name' => 'work_periods.manage', 'description' => 'Manage work periods', 'module' => 'work_periods', 'sort_order' => 51],
            
            // Reports permissions
            ['name' => 'reports.view', 'description' => 'View reports', 'module' => 'reports', 'sort_order' => 60],
            ['name' => 'reports.sales', 'description' => 'View sales reports', 'module' => 'reports', 'sort_order' => 61],
            ['name' => 'reports.financial', 'description' => 'View financial reports', 'module' => 'reports', 'sort_order' => 62],
            ['name' => 'reports.export', 'description' => 'Export reports', 'module' => 'reports', 'sort_order' => 63],
            ['name' => 'reports.analytics', 'description' => 'View analytics', 'module' => 'reports', 'sort_order' => 64],
            
            // Cash Collection permissions
            ['name' => 'cash_collections.view', 'description' => 'View cash collections', 'module' => 'cash_collections', 'sort_order' => 70],
            ['name' => 'cash_collections.create', 'description' => 'Create collection requests', 'module' => 'cash_collections', 'sort_order' => 71],
            ['name' => 'cash_collections.approve', 'description' => 'Approve cash collections', 'module' => 'cash_collections', 'sort_order' => 72],
            ['name' => 'cash_collections.delete', 'description' => 'Delete cash collections', 'module' => 'cash_collections', 'sort_order' => 73],
            
            // Fuel Request permissions
            ['name' => 'fuel_requests.view', 'description' => 'View fuel requests', 'module' => 'fuel_requests', 'sort_order' => 80],
            ['name' => 'fuel_requests.create', 'description' => 'Create fuel requests', 'module' => 'fuel_requests', 'sort_order' => 81],
            ['name' => 'fuel_requests.approve', 'description' => 'Approve fuel requests', 'module' => 'fuel_requests', 'sort_order' => 82],
            ['name' => 'fuel_requests.delete', 'description' => 'Delete fuel requests', 'module' => 'fuel_requests', 'sort_order' => 83],
            
            // User Management permissions
            ['name' => 'users.view', 'description' => 'View users', 'module' => 'users', 'sort_order' => 90],
            ['name' => 'users.create', 'description' => 'Create users', 'module' => 'users', 'sort_order' => 91],
            ['name' => 'users.edit', 'description' => 'Edit user details', 'module' => 'users', 'sort_order' => 92],
            ['name' => 'users.assign_role', 'description' => 'Assign roles to users', 'module' => 'users', 'sort_order' => 93],
            ['name' => 'users.delete', 'description' => 'Delete users', 'module' => 'users', 'sort_order' => 94],
            
            // Role Management permissions
            ['name' => 'roles.view', 'description' => 'View roles', 'module' => 'roles', 'sort_order' => 100],
            ['name' => 'roles.manage', 'description' => 'Manage roles and permissions', 'module' => 'roles', 'sort_order' => 101],
            
            // License permissions
            ['name' => 'licenses.view', 'description' => 'View licenses', 'module' => 'licenses', 'sort_order' => 110],
            ['name' => 'licenses.manage', 'description' => 'Manage licenses', 'module' => 'licenses', 'sort_order' => 111],
            
            // Maintenance permissions
            ['name' => 'maintenance.view', 'description' => 'View maintenance requests', 'module' => 'maintenance', 'sort_order' => 120],
            ['name' => 'maintenance.create', 'description' => 'Create maintenance requests', 'module' => 'maintenance', 'sort_order' => 121],
            ['name' => 'maintenance.update', 'description' => 'Update maintenance status', 'module' => 'maintenance', 'sort_order' => 122],
            ['name' => 'maintenance.delete', 'description' => 'Delete maintenance requests', 'module' => 'maintenance', 'sort_order' => 123],
        ];
        
        DB::table('permissions')->insert($permissions);
    }
}
```

---

## 4. Implementation Approach

### 4.1 Laravel Models

#### Permission Model

**File:** `app/Models/Permission.php`

```php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Permission extends Model
{
    protected $fillable = [
        'name',
        'description',
        'module',
        'guard_name',
        'sort_order',
    ];
    
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'role_permissions')
            ->withTimestamps();
    }
    
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_permissions')
            ->withTimestamps()
            ->withPivot('is_denied');
    }
    
    public function scopeForModule($query, string $module)
    {
        return $query->where('module', $module);
    }
}
```

#### Role Model

**File:** `app/Models/Role.php`

```php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Role extends Model
{
    protected $fillable = [
        'name',
        'display_name',
        'description',
        'guard_name',
        'company_id',
        'is_system',
    ];
    
    protected $casts = [
        'is_system' => 'boolean',
    ];
    
    public function permissions(): BelongsToMany
    {
        return $this->belongsToMany(Permission::class, 'role_permissions')
            ->withTimestamps();
    }
    
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_roles')
            ->withTimestamps()
            ->withPivot('company_id', 'station_id', 'assigned_at', 'assigned_by');
    }
    
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }
    
    public function givePermissionTo(Permission $permission)
    {
        return $this->permissions()->syncWithoutDetaching($permission);
    }
    
    public function revokePermission(Permission $permission)
    {
        return $this->permissions()->detach($permission);
    }
}
```

#### Updated User Model

**File:** `app/Models/User.php` (additions)

```php
// Add these methods to the existing User model

use Illuminate\Database\Eloquent\Relations\BelongsToMany;

public function roles(): BelongsToMany
{
    return $this->belongsToMany(Role::class, 'user_roles')
        ->withTimestamps()
        ->withPivot('company_id', 'station_id', 'assigned_at', 'assigned_by');
}

public function permissions(): BelongsToMany
{
    return $this->belongsToMany(Permission::class, 'user_permissions')
        ->withTimestamps()
        ->withPivot('is_denied');
}

/**
 * Check if user has a specific permission
 */
public function hasPermission(string $permission): bool
{
    // Check direct user permissions first (including denies)
    $directPermission = $this->permissions()
        ->where('name', $permission)
        ->first();
    
    if ($directPermission) {
        // If explicitly denied, return false
        if ($directPermission->pivot->is_denied) {
            return false;
        }
        // If explicitly granted, return true
        return true;
    }
    
    // Check role permissions
    foreach ($this->roles as $role) {
        if ($role->permissions()->where('name', $permission)->exists()) {
            return true;
        }
    }
    
    // Fall back to user_type check for backward compatibility
    return $this->hasPermissionByUserType($permission);
}

/**
 * Fallback check using user_type
 */
protected function hasPermissionByUserType(string $permission): bool
{
    $permissionMap = [
        'super_admin' => '*', // All permissions
        'admin' => [
            'stations.view', 'stations.create', 'stations.edit', 'stations.delete',
            'pumps.view', 'pumps.create', 'pumps.edit', 'pumps.update_status', 'pumps.delete',
            'tanks.view', 'tanks.create', 'tanks.edit', 'tanks.update_level', 'tanks.adjust', 'tanks.delete',
            'nozzles.view', 'nozzles.create', 'nozzles.edit', 'nozzles.calibrate', 'nozzles.delete',
            'shifts.view', 'shifts.create', 'shifts.edit', 'shifts.start', 'shifts.close', 'shifts.approve', 'shifts.delete',
            'reports.view', 'reports.sales', 'reports.financial', 'reports.export', 'reports.analytics',
            'users.view', 'users.create', 'users.edit', 'users.assign_role', 'users.delete',
            'roles.view', 'roles.manage',
        ],
        'company_owner' => [
            'stations.view', 'stations.create', 'stations.edit',
            'pumps.view', 'pumps.create', 'pumps.edit', 'pumps.update_status',
            'tanks.view', 'tanks.create', 'tanks.edit', 'tanks.update_level', 'tanks.adjust',
            'nozzles.view', 'nozzles.create', 'nozzles.edit', 'nozzles.calibrate',
            'shifts.view', 'shifts.create', 'shifts.edit', 'shifts.start', 'shifts.close', 'shifts.approve',
            'reports.view', 'reports.sales', 'reports.financial', 'reports.export',
            'cash_collections.view', 'cash_collections.create', 'cash_collections.approve',
            'users.view', 'users.create', 'users.edit', 'users.assign_role',
            'licenses.view', 'licenses.manage',
        ],
        'station_manager' => [
            'stations.view',
            'pumps.view', 'pumps.edit', 'pumps.update_status',
            'tanks.view', 'tanks.edit', 'tanks.update_level',
            'nozzles.view', 'nozzles.edit',
            'shifts.view', 'shifts.create', 'shifts.edit', 'shifts.start', 'shifts.close', 'shifts.approve',
            'reports.view', 'reports.sales',
            'cash_collections.view', 'cash_collections.create',
            'fuel_requests.view', 'fuel_requests.create',
            'maintenance.view', 'maintenance.create', 'maintenance.update',
        ],
        'staff' => [
            'pumps.view',
            'tanks.view',
            'nozzles.view',
            'shifts.view', 'shifts.start', 'shifts.close',
            'reports.view',
        ],
    ];
    
    $allowedPermissions = $permissionMap[$this->user_type] ?? [];
    
    if ($allowedPermissions === '*') {
        return true;
    }
    
    return in_array($permission, $allowedPermissions);
}

/**
 * Check if user has any of the given permissions
 */
public function hasAnyPermission(array $permissions): bool
{
    foreach ($permissions as $permission) {
        if ($this->hasPermission($permission)) {
            return true;
        }
    }
    return false;
}

/**
 * Check if user has all of the given permissions
 */
public function hasAllPermissions(array $permissions): bool
{
    foreach ($permissions as $permission) {
        if (!$this->hasPermission($permission)) {
            return false;
        }
    }
    return true;
}

/**
 * Assign role to user
 */
public function assignRole(Role $role, ?int $companyId = null, ?int $stationId = null): self
{
    $this->roles()->attach($role->id, [
        'company_id' => $companyId,
        'station_id' => $stationId,
        'assigned_at' => now(),
        'assigned_by' => auth()->id(),
    ]);
    
    return $this;
}

/**
 * Remove role from user
 */
public function removeRole(Role $role): self
{
    $this->roles()->detach($role->id);
    
    return $this;
}
```

### 4.2 Middleware for Permission Checking

#### Permission Middleware

**File:** `app/Http/Middleware/CheckPermission.php`

```php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, string $permission): Response
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }
        
        $user = Auth::user();
        
        // Split permission string by | for OR logic
        $permissions = explode('|', $permission);
        
        // Check if user has ANY of the permissions (OR logic)
        if (str_starts_with($permission, 'any:')) {
            $permissions = explode('|', substr($permission, 4));
            if ($user->hasAnyPermission($permissions)) {
                return $next($request);
            }
        }
        // Check if user has ALL permissions (AND logic)
        elseif (str_starts_with($permission, 'all:')) {
            $permissions = explode('|', substr($permission, 4));
            if ($user->hasAllPermissions($permissions)) {
                return $next($request);
            }
        }
        // Single permission check
        else {
            if ($user->hasPermission($permission)) {
                return $next($request);
            }
        }
        
        // Permission denied
        if ($request->expectsJson() || $request->is('api/*')) {
            return response()->json([
                'message' => 'You do not have permission to perform this action.',
                'required_permission' => $permission,
            ], 403);
        }
        
        return back()->with('error', 'You do not have permission to access this resource.');
    }
}
```

#### Register the middleware in `bootstrap/app.php` or create a service provider:

```php
// In AppServiceProvider or dedicated PermissionServiceProvider

use Illuminate\Support\Facades\Gate;

public function boot(): void
{
    // Register permission gates for convenience
    Gate::define('permission', function ($user, string $permission) {
        return $user->hasPermission($permission);
    });
}
```

### 4.3 Controller-Level Authorization Examples

```php
<?php

namespace App\Http\Controllers\Station;

use App\Http\Controllers\Controller;
use App\Models\Pump;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class PumpController extends Controller
{
    public function __construct()
    {
        // Apply middleware to all methods
        $this->middleware('permission:pumps.view')->only(['index', 'show']);
        $this->middleware('permission:pumps.create')->only(['store', 'create']);
        $this->middleware('permission:pumps.edit')->only(['edit', 'update']);
        $this->middleware('permission:pumps.delete')->only(['destroy']);
        $this->middleware('permission:pumps.update_status')->only(['updateStatus']);
    }
    
    public function index()
    {
        // Gate authorization example
        if (Gate::denies('permission', 'pumps.view')) {
            abort(403, 'You cannot view pumps.');
        }
        
        $pumps = Pump::all();
        return view('pumps.index', compact('pumps'));
    }
    
    public function store(Request $request)
    {
        $this->authorize('permission', 'pumps.create');
        
        // Or use policy
        $this->authorize('create', Pump::class);
        
        // Create pump logic
    }
    
    public function update(Request $request, Pump $pump)
    {
        // Using Gate with resource check
        Gate::authorize('permission', 'pumps.edit');
        
        // Update pump logic
    }
    
    public function updateStatus(Request $request, Pump $pump)
    {
        // Separate permission for status updates
        // This allows users to view/edit pumps but NOT change status
        if (Gate::denies('permission', 'pumps.update_status')) {
            return response()->json([
                'message' => 'You cannot change pump status.'
            ], 403);
        }
        
        // Update status logic
    }
}
```

### 4.4 Laravel Policies

**File:** `app/Policies/PumpPolicy.php`

```php
<?php

namespace App\Policies;

use App\Models\Pump;
use App\Models\User;

class PumpPolicy
{
    /**
     * Determine whether the user can view any pumps.
     */
    public function viewAny(User $user): bool
    {
        return $user->hasPermission('pumps.view');
    }

    /**
     * Determine whether the user can view the pump.
     */
    public function view(User $user, Pump $pump): bool
    {
        return $user->hasPermission('pumps.view');
    }

    /**
     * Determine whether the user can create pumps.
     */
    public function create(User $user): bool
    {
        return $user->hasPermission('pumps.create');
    }

    /**
     * Determine whether the user can update the pump.
     */
    public function update(User $user, Pump $pump): bool
    {
        return $user->hasPermission('pumps.edit');
    }

    /**
     * Determine whether the user can update pump status.
     */
    public function updateStatus(User $user, Pump $pump): bool
    {
        return $user->hasPermission('pumps.update_status');
    }

    /**
     * Determine whether the user can delete the pump.
     */
    public function delete(User $user, Pump $pump): bool
    {
        return $user->hasPermission('pumps.delete');
    }
}
```

---

## 5. Blade Directives for UI Elements

### 5.1 Custom Blade Directive Registration

**File:** `app/Providers/PermissionServiceProvider.php`

```php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class PermissionServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        // @canany directive
        Blade::directive('canany', function ($expression) {
            return "<?php if (\\Illuminate\\Support\\Facades\\Auth::user()->hasAnyPermission({$expression})): ?>";
        });
        
        Blade::directive('endcanany', function () {
            return '<?php endif; ?>';
        });
        
        // @cannot directive (opposite of @can)
        Blade::directive('cannot', function ($expression) {
            return "<?php if (!\\Illuminate\\Support\\Facades\\Auth::user()->hasPermission({$expression})): ?>";
        });
        
        Blade::directive('endcannot', function () {
            return '<?php endif; ?>';
        });
        
        // @hasexactrole directive
        Blade::directive('hasexactrole', function ($expression) {
            return "<?php if (\\Illuminate\\Support\\Facades\\Auth::user()->hasExactRole({$expression})): ?>";
        });
        
        Blade::directive('endhasexactrole', function () {
            return '<?php endif; ?>';
        });
    }
}
```

### 5.2 Usage Examples in Blade Templates

```blade
{{-- Show/Hide entire section based on permission --}}
@can('pumps.view')
    <div class="pumps-section">
        <h3>Pumps</h3>
        <table>
            {{-- Pump list --}}
        </table>
    </div>
@endcan

{{-- Show different UI based on permissions --}}
@can('pumps.create')
    <a href="{{ route('pumps.create') }}" class="btn btn-primary">Add Pump</a>
@else
    <button class="btn btn-disabled" disabled>Add Pump</button>
@endcan

{{-- Show edit button only if user can edit --}}
@can('pumps.edit')
    <a href="{{ route('pumps.edit', $pump->id) }}" class="btn btn-sm btn-warning">Edit</a>
@endcan

{{-- Show delete button only if user can delete --}}
@can('pumps.delete')
    <form action="{{ route('pumps.destroy', $pump->id) }}" method="POST">
        @csrf
        @method('DELETE')
        <button type="submit" class="btn btn-sm btn-danger" 
                onclick="return confirm('Are you sure?')">Delete</button>
    </form>
@endcan

{{-- Special case: Can view but NOT update status --}}
@can('pumps.view')
    <div class="pump-details">
        <h4>{{ $pump->name }}</h4>
        <p>Status: {{ $pump->status }}</p>
        
        {{-- Status toggle only for users with update_status permission --}}
        @can('pumps.update_status')
            <button onclick="togglePumpStatus({{ $pump->id }})">Change Status</button>
        @else
            <span class="text-muted">Status changes require approval</span>
        @endcan
    </div>
@endcan

{{-- Multiple permissions with OR logic --}}
@canany('shifts.approve', 'shifts.close')
    <div class="shift-actions">
        @can('shifts.approve')
            <button onclick="approveShift({{ $shift->id }})">Approve</button>
        @endcan
        @can('shifts.close')
            <button onclick="closeShift({{ $shift->id }})">Close</button>
        @endcan
    </div>
@endcanany

{{-- Reports export button --}}
@can('reports.export')
    <button onclick="exportReport()">Export Report</button>
@endcan

{{-- Or deny access entirely --}}
@cannot('reports.export')
    <div class="alert alert-info">
        Contact your administrator to request report export access.
    </div>
@endcannot
```

---

## 6. Role Management UI

### 6.1 API Endpoints for Role Management

```php
<?php

// routes/api.php or routes/web.php

Route::middleware(['auth:sanctum', 'permission:roles.view'])->group(function () {
    // Role listing
    Route::get('/roles', [RoleController::class, 'index']);
    Route::get('/roles/{role}', [RoleController::class, 'show']);
    
    // Role management (requires roles.manage permission)
    Route::middleware('permission:roles.manage')->group(function () {
        Route::post('/roles', [RoleController::class, 'store']);
        Route::put('/roles/{role}', [RoleController::class, 'update']);
        Route::delete('/roles/{role}', [RoleController::class, 'destroy']);
        
        // Permission assignment
        Route::post('/roles/{role}/permissions', [RoleController::class, 'assignPermissions']);
        Route::delete('/roles/{role}/permissions/{permission}', [RoleController::class, 'revokePermission']);
    });
});

Route::middleware(['auth:sanctum', 'permission:users.assign_role'])->group(function () {
    // User role assignment
    Route::post('/users/{user}/roles', [UserRoleController::class, 'assign']);
    Route::delete('/users/{user}/roles/{role}', [UserRoleController::class, 'revoke']);
});
```

---

## 7. File Locations Summary

| Component | File Path |
|-----------|-----------|
| Permission Model | `app/Models/Permission.php` |
| Role Model | `app/Models/Role.php` |
| User Model (updates) | `app/Models/User.php` |
| CheckPermission Middleware | `app/Http/Middleware/CheckPermission.php` |
| PermissionServiceProvider | `app/Providers/PermissionServiceProvider.php` |
| Permission Seeder | `database/seeders/PermissionSeeder.php` |
| Role Seeder | `database/seeders/RoleSeeder.php` |
| Pump Policy | `app/Policies/PumpPolicy.php` |
| Tank Policy | `app/Policies/TankPolicy.php` |
| Nozzle Policy | `app/Policies/NozzlePolicy.php` |
| Shift Policy | `app/Policies/ShiftPolicy.php` |
| Permission Migrations | `database/migrations/2026_02_25_00000X_*.php` |
| Role Controller | `app/Http/Controllers/Admin/RoleController.php` |
| Permission Resources | `resources/views/admin/permissions/` |

---

## 8. Implementation Roadmap

### Phase 1: Database & Models (Day 1)
- [ ] Create migration files
- [ ] Create Permission and Role models
- [ ] Update User model with relationships and methods
- [ ] Run migrations
- [ ] Run permission seeder

### Phase 2: Authorization Layer (Day 2)
- [ ] Create CheckPermission middleware
- [ ] Register Blade directives
- [ ] Create Laravel policies for each resource
- [ ] Update existing controllers with permission checks

### Phase 3: Role Management (Day 3)
- [ ] Create Role CRUD controller
- [ ] Create role management views
- [ ] Create user role assignment interface

### Phase 4: Testing & Integration (Day 4)
- [ ] Test permission checks
- [ ] Test Blade directives
- [ ] Test API endpoints
- [ ] Verify backward compatibility with user_type

---

## 9. Backward Compatibility

The system maintains backward compatibility with the existing `user_type` field through the `hasPermissionByUserType()` method in the User model. This ensures:
- Existing users with `user_type = 'admin'` continue to have access
- Super admins have all permissions by default
- Gradual migration to the new permission system is possible

---

## 10. Example Use Cases from Requirements

### Use Case 1: User can VIEW pumps but CANNOT change pump status
```
User Role: Pump Viewer
Permissions:
- pumps.view ✓
- pumps.create ✗
- pumps.edit ✗
- pumps.update_status ✗
- pumps.delete ✗
```

### Use Case 2: User can VIEW pumps but CANNOT EDIT or UPDATE pumps
```
User Role: Pump Observer
Permissions:
- pumps.view ✓
- pumps.create ✗
- pumps.edit ✗
- pumps.update_status ✗
- pumps.delete ✗
```

### Use Case 3: User can ADD stations but cannot DELETE them
```
User Role: Station Creator
Permissions:
- stations.view ✓
- stations.create ✓
- stations.edit ✓
- stations.delete ✗
```

### Use Case 4: User can VIEW reports but cannot EXPORT them
```
User Role: Report Viewer
Permissions:
- reports.view ✓
- reports.sales ✓
- reports.financial ✓
- reports.export ✗
- reports.analytics ✗
```

---

This design provides a comprehensive, scalable, and maintainable permission system for the FuelPlus Station module with granular control over every action.
