<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PermissionController extends ApiController
{
    /**
     * Display a listing of permissions with pagination and search
     */
    public function index(Request $request)
    {
        $perPage = $request->get('per_page', 50);
        $search = $request->get('search');
        $module = $request->get('module');

        // Sample permissions structure
        $permissions = [
            // Student Management
            ['id' => 1, 'name' => 'View Students', 'slug' => 'students.view', 'module' => 'students', 'description' => 'View student list'],
            ['id' => 2, 'name' => 'Create Student', 'slug' => 'students.create', 'module' => 'students', 'description' => 'Add new student'],
            ['id' => 3, 'name' => 'Edit Student', 'slug' => 'students.edit', 'module' => 'students', 'description' => 'Update student details'],
            ['id' => 4, 'name' => 'Delete Student', 'slug' => 'students.delete', 'module' => 'students', 'description' => 'Remove student'],

            // Teacher Management
            ['id' => 5, 'name' => 'View Teachers', 'slug' => 'teachers.view', 'module' => 'teachers', 'description' => 'View teacher list'],
            ['id' => 6, 'name' => 'Create Teacher', 'slug' => 'teachers.create', 'module' => 'teachers', 'description' => 'Add new teacher'],
            ['id' => 7, 'name' => 'Edit Teacher', 'slug' => 'teachers.edit', 'module' => 'teachers', 'description' => 'Update teacher details'],
            ['id' => 8, 'name' => 'Delete Teacher', 'slug' => 'teachers.delete', 'module' => 'teachers', 'description' => 'Remove teacher'],

            // Class Management
            ['id' => 9, 'name' => 'View Classes', 'slug' => 'classes.view', 'module' => 'classes', 'description' => 'View class list'],
            ['id' => 10, 'name' => 'Manage Classes', 'slug' => 'classes.manage', 'module' => 'classes', 'description' => 'Full class management'],

            // Exam Management
            ['id' => 11, 'name' => 'View Exams', 'slug' => 'exams.view', 'module' => 'exams', 'description' => 'View exam list'],
            ['id' => 12, 'name' => 'Create Exam', 'slug' => 'exams.create', 'module' => 'exams', 'description' => 'Create new exam'],
            ['id' => 13, 'name' => 'Publish Results', 'slug' => 'exams.publish', 'module' => 'exams', 'description' => 'Publish exam results'],

            // Fee Management
            ['id' => 14, 'name' => 'View Fees', 'slug' => 'fees.view', 'module' => 'fees', 'description' => 'View fee transactions'],
            ['id' => 15, 'name' => 'Collect Fees', 'slug' => 'fees.collect', 'module' => 'fees', 'description' => 'Collect fee payments'],
            ['id' => 16, 'name' => 'Fee Reports', 'slug' => 'fees.reports', 'module' => 'fees', 'description' => 'Generate fee reports'],

            // Attendance
            ['id' => 17, 'name' => 'Mark Attendance', 'slug' => 'attendance.mark', 'module' => 'attendance', 'description' => 'Mark student attendance'],
            ['id' => 18, 'name' => 'View Attendance', 'slug' => 'attendance.view', 'module' => 'attendance', 'description' => 'View attendance reports'],

            // Library
            ['id' => 19, 'name' => 'Manage Library', 'slug' => 'library.manage', 'module' => 'library', 'description' => 'Full library management'],
            ['id' => 20, 'name' => 'Issue Books', 'slug' => 'library.issue', 'module' => 'library', 'description' => 'Issue and return books'],

            // Transport
            ['id' => 21, 'name' => 'Manage Transport', 'slug' => 'transport.manage', 'module' => 'transport', 'description' => 'Manage transport system'],

            // Hostel
            ['id' => 22, 'name' => 'Manage Hostel', 'slug' => 'hostel.manage', 'module' => 'hostel', 'description' => 'Manage hostel system'],

            // Communication
            ['id' => 23, 'name' => 'Send SMS', 'slug' => 'communication.sms', 'module' => 'communication', 'description' => 'Send SMS notifications'],
            ['id' => 24, 'name' => 'Send Email', 'slug' => 'communication.email', 'module' => 'communication', 'description' => 'Send email notifications'],

            // Reports
            ['id' => 25, 'name' => 'View Reports', 'slug' => 'reports.view', 'module' => 'reports', 'description' => 'Access all reports'],
            ['id' => 26, 'name' => 'Export Reports', 'slug' => 'reports.export', 'module' => 'reports', 'description' => 'Export reports to PDF/Excel'],

            // Settings
            ['id' => 27, 'name' => 'View Settings', 'slug' => 'settings.view', 'module' => 'settings', 'description' => 'View system settings'],
            ['id' => 28, 'name' => 'Manage Settings', 'slug' => 'settings.manage', 'module' => 'settings', 'description' => 'Modify system settings'],

            // User Management
            ['id' => 29, 'name' => 'View Users', 'slug' => 'users.view', 'module' => 'users', 'description' => 'View user list'],
            ['id' => 30, 'name' => 'Manage Users', 'slug' => 'users.manage', 'module' => 'users', 'description' => 'Full user management'],

            // Role Management
            ['id' => 31, 'name' => 'View Roles', 'slug' => 'roles.view', 'module' => 'roles', 'description' => 'View roles'],
            ['id' => 32, 'name' => 'Manage Roles', 'slug' => 'roles.manage', 'module' => 'roles', 'description' => 'Create and manage roles'],
        ];

        // Apply filters
        if ($search) {
            $permissions = array_filter($permissions, function($perm) use ($search) {
                return stripos($perm['name'], $search) !== false ||
                       stripos($perm['slug'], $search) !== false;
            });
        }

        if ($module) {
            $permissions = array_filter($permissions, function($perm) use ($module) {
                return $perm['module'] === $module;
            });
        }

        // Group by module
        $groupedPermissions = [];
        foreach ($permissions as $permission) {
            $groupedPermissions[$permission['module']][] = $permission;
        }

        return $this->successResponse([
            'permissions' => array_values($permissions),
            'grouped_by_module' => $groupedPermissions,
            'total' => count($permissions),
            'modules' => array_unique(array_column($permissions, 'module')),
            'message' => 'Permissions will be fetched from database once permissions table is created',
        ]);
    }

    /**
     * Store a newly created permission
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:permissions,slug',
            'module' => 'required|string',
            'description' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        // TODO: Create in database
        return $this->successResponse(
            [
                'id' => rand(100, 999),
                'name' => $request->name,
                'slug' => $request->slug,
                'module' => $request->module,
                'description' => $request->description,
            ],
            'Permission will be created in database once permissions table is created',
            201
        );
    }

    /**
     * Display the specified permission
     */
    public function show($id)
    {
        // TODO: Fetch from database
        return $this->successResponse([
            'id' => $id,
            'name' => 'Sample Permission',
            'slug' => 'sample.permission',
            'module' => 'sample',
            'roles_count' => 0,
        ]);
    }

    /**
     * Update the specified permission
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|string|max:255',
            'slug' => 'sometimes|string|max:255|unique:permissions,slug,' . $id,
            'module' => 'sometimes|string',
            'description' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        // TODO: Update in database
        return $this->successResponse(
            ['id' => $id, 'updated' => true],
            'Permission will be updated in database once permissions table is created'
        );
    }

    /**
     * Remove the specified permission
     */
    public function destroy($id)
    {
        // TODO: Delete from database
        return $this->successResponse(
            null,
            'Permission will be deleted from database once permissions table is created'
        );
    }

    /**
     * Get available modules
     */
    public function modules()
    {
        $modules = [
            'students' => 'Student Management',
            'teachers' => 'Teacher Management',
            'classes' => 'Class Management',
            'exams' => 'Exam Management',
            'fees' => 'Fee Management',
            'attendance' => 'Attendance Management',
            'library' => 'Library Management',
            'transport' => 'Transport Management',
            'hostel' => 'Hostel Management',
            'communication' => 'Communication',
            'reports' => 'Reports',
            'settings' => 'System Settings',
            'users' => 'User Management',
            'roles' => 'Role Management',
        ];

        return $this->successResponse($modules);
    }
}
