<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\School_setting;

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;


class SettingsController extends Controller
{
    // Display settings page
    public function index()
    {
        $settings = School_setting::whereNotIn('setting_key', ['school_logo', 'exam_controller_sign'])->get();
        $logo = School_setting::where('setting_key','school_logo')->first(); // Fetch all settings
        $controller_signature = School_setting::where('setting_key','exam_controller_sign')->first(); // Fetch all settings
          return view('settings.index', compact('settings','logo','controller_signature'));
    }

    // Update settings
    public function update(Request $request)
    {
        
        if ($request->hasFile('school_logo')) {
            $logo = School_setting::where('setting_key', 'school_logo')->first();

            // Delete the previous logo file if it exists
            if ($logo && $logo->setting_value && \Storage::disk('public')->exists($logo->setting_value)) {
                \Storage::disk('public')->delete($logo->setting_value);
            }


            // Save the new logo file
            
            $filename= $request->file('school_logo') ? $request->file('school_logo')->store('school_settings', 'public') : null;

            // Update or create the school_logo setting
            School_setting::updateOrCreate(
            ['setting_key' => 'school_logo'],
            ['setting_value' => $filename]
            );
        }
                // Handle exam_controller_sign upload
        if ($request->hasFile('exam_controller_sign')) {
            $signature = School_setting::where('setting_key', 'exam_controller_sign')->first();

            // Delete previous signature if it exists
            if ($signature && $signature->setting_value && \Storage::disk('public')->exists($signature->setting_value)) {
                \Storage::disk('public')->delete($signature->setting_value);
            }

            // Save the new signature
            $signature_filename = $request->file('exam_controller_sign')->store('school_settings', 'public');

            // Update or create signature setting
            School_setting::updateOrCreate(
                ['setting_key' => 'exam_controller_sign'],
                ['setting_value' => $signature_filename]
            );
        }


        
        foreach ($request->settings as $key => $value) {
            School_setting::where('setting_key', $key)->update(['setting_value' => $value]);
        }

        return redirect()->route('settings.index')->with('success', 'Settings updated successfully!');
    }

    public function role_permissions()
    {
        // Fetch all roles and permissions
        $roles = Role::all();
        $permissions = Permission::all();

        return view('settings.role-permissions', compact('roles', 'permissions'));
    }

    public function updateRolePermissions(Request $request)
    {
        // Validate permissions array
        $validated = $request->validate([
            'permissions.*' => 'array', // Validate each role's permissions as an array
            'permissions.*.*' => 'exists:permissions,name', // Ensure the permission names exist in the permissions table
        ]);
    
        // Iterate through each role and its permissions
        foreach ($validated['permissions'] as $roleId => $permissionNames) {
            $role = Role::find($roleId); // Find the role by ID
    
            if ($role) {
                // Fetch the permission objects by name (instead of by ID)
                $permissions = Permission::whereIn('name', $permissionNames)->get();
    
                // Sync the permissions for this role
                $role->syncPermissions($permissions);
            }
        }
    
        // Redirect back with a success message
        return redirect()->route('settings.role-permissions')
                         ->with('success', 'Permissions updated successfully!');
    }

    
    public function store_role(Request $request)
    {
         // Validate the request
        $request->validate([
            'roleName' => 'required|string|max:255|unique:roles,name',
         ]);

        // Create the role
        $role = Role::create(['name' => $request->roleName,'guard_name '=>'web']);

        // Assign permissions to the role if provided
        if ($request->permissions) {
            $role->syncPermissions($request->permissions);
        }

        return redirect()->route('settings.role-permissions')->with('success', 'Role created successfully!');
    }
    


}
