<?php

namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use App\Helpers\AuditLogger;

class UserController extends Controller
{
    // Display all users
    public function index()
    {
        $users = User::all();
        $roles = Role::all();
        return view('users.index', compact('users', 'roles'));
    }

    // Store a new user
    public function store(Request $request)
    {
    $request->validate([
    'first_name'  => 'required|string|max:255',
    'last_name'   => 'required|string|max:255',
    'email'       => 'required|email|unique:users,email',
    'password'    => 'required|string|min:1|confirmed',
    'roles'       => 'required|array',
    'roles.*'     => 'exists:roles,id',
    ]);

        $user = User::create([
            'first_name' => $request->first_name,
            'last_name'  => $request->last_name,
            'email'     => $request->email,
            'password' => Hash::make($request->password),

        ]);

        // Assign roles if needed
        // $user->roles()->sync($request->roles);
        $user->roles()->sync($request->roles);

        AuditLogger::log('user', $user->id, 'created', null, [
            'id' => $user->id,
            'name' => trim(($user->first_name ?? '') . ' ' . ($user->last_name ?? '')),
            'email' => $user->email,
            'roles' => $user->roles()->pluck('name')->toArray(),
        ]);

        return redirect()->route('users.index')->with('message', 'User added successfully!');
    }

    // Update an existing user
    public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);
        $before = [
            'id' => $user->id,
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'roles' => $user->roles()->pluck('name')->toArray(),
        ];

        $request->validate([
            'first_name'  => 'required|string|max:255',
            'last_name'   => 'required|string|max:255',
            'email'       => 'required|email|unique:users,email,' . $user->id,
            'password'    => 'nullable|string|min:1|confirmed',
            'roles'       => 'nullable|array',
            'roles.*'     => 'exists:roles,id',
        ]);

        $user->first_name = $request->first_name;
        $user->last_name  = $request->last_name;
        $user->email      = $request->email;

        // Update password if provided
        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        $user->save();

        // Always sync roles (even if empty array to remove all roles)
        $user->roles()->sync($request->roles ?? []);

        AuditLogger::log('user', $user->id, 'updated', $before, [
            'id' => $user->id,
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'roles' => $user->roles()->pluck('name')->toArray(),
        ]);

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

    // Delete a user
    public function destroy($id)
    {
        try {
            $user = User::findOrFail($id);
            $before = [
                'id' => $user->id,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
                'roles' => $user->roles()->pluck('name')->toArray(),
            ];
            
            // Check if user has folder permissions
            $hasPermissions = \DB::table('folder_user_permissions')
                ->where('user_id', $id)
                ->exists();
                
            if ($hasPermissions) {
                AuditLogger::log('user', $user->id, 'delete_blocked', $before, [
                    'reason' => 'User has folder permissions assigned',
                ]);

                return redirect()->route('users.index')
                    ->with('error', 'Cannot delete user. This user has folder permissions assigned. Please remove all folder permissions first.');
            }
            
            // Remove user's roles first (Spatie roles are safe to detach)
            $user->roles()->detach();
            
            // Now delete the user
            $user->delete();

            AuditLogger::log('user', $id, 'deleted', $before, null);
            
            return redirect()->route('users.index')
                ->with('success', 'User deleted successfully!');
                
        } catch (\Illuminate\Database\QueryException $e) {
            // Handle foreign key constraint violations
            if ($e->getCode() == 23000) {
                return redirect()->route('users.index')
                    ->with('error', 'Cannot delete user. This user has related data in the system. Please remove all related records first.');
            }
            
            return redirect()->route('users.index')
                ->with('error', 'An error occurred while deleting the user.');
        }
    }
}
