<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;

use App\Models\UserRole;
use Auth;

use App\Models\User;
use App\Models\App;

class UsersController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $users = User::where('status', true)->get();

        $profiles = App::where('status', true)->where("published", true)->get();

        return Inertia::render('Users/Index', ['users' => $users,'profiles' => $profiles]);

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'string',
                'email' => 'string|max:50',
                'password' => 'string|max:50',
                'profiles' => 'array|nullable',
            ]);

            if (User::where('email', $validated['email'])->where('status', true)->exists()) {
                return redirect()->back()->with(['error', 'Email already used!']);
            }

            $user = new User();

            $user->name = $validated['name'] ?? '';
            $user->email = $validated['email'] ?? '';
            $user->password = bcrypt($validated['password']) ?? '';

            if (isset($validated['profiles'])) {
                $commaSeparated = implode(',', array_column($validated['profiles'], 'id'));
                
                $user->managed_profiles = $commaSeparated;
            }

            $user->save();

            $data = [];
            if (isset($request->roles)) {
                foreach ($request->roles as $key => $value) {
                    $data[$key] = $value ?? false;
                }

                $user->roles()->create($data);
            }
            

            return redirect()->route('users.index')->with('success', 'User created succesfully!');
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage(), 'status' => 500], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $users = User::where('status', true)->get();
        $selected_user = User::with('roles')->where('status', true)->findOrFail($id);

        $selected_profiles = $selected_user->managed_profiles;
        $selected_profiles = explode(',', $selected_profiles);
        
        $selected_profiles = App::where('status', true)->where("published", true)->whereIn('id', $selected_profiles)->get();
        $selected_user->managed_profiles = $selected_profiles;

        $profiles = App::where('status', true)->where("published", true)->get();

        return Inertia::render('Users/Update', ['users' => $users, 'selected_user' => $selected_user,'profiles' => $profiles]);

    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        try {
            $validated = $request->validate([
                'name' => 'string',
                'email' => 'string|max:50',
                'password' => 'string|max:50|nullable',
                'profiles' => 'array|nullable',
            ]);

            $user = User::with('roles')->find($id);

            $user->name = $validated['name'] ?? '';
            $user->email = $user->email ?? '';

            if (isset($validated['password'])) {
                $user->password = bcrypt($validated['password']) ?? $user->password;
            }

            if (isset($validated['profiles'])) {
                $commaSeparated = implode(',', array_column($validated['profiles'], 'id'));

                $user->managed_profiles = $commaSeparated;
            }

            $user->save();

            $user->roles()->delete();

            $data = [];
            if (isset($request->roles)) {
                foreach ($request->roles as $key => $value) {
                    $data[$key] = $value ?? false;
                }

                $user->roles()->create($data);
            }

            session()->flash('success', 'User updated successfully!');
            return Inertia::location('/admin/dashboard');
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage(), 'status' => 500], 500);
        }
    }

    public function GetRoles()
    {
        $roles = UserRole::where('user_id', Auth::user()->id)->first();

        return response()->json(['data' => ['roles'=>$roles,'email' => Auth::user()->email],'status' => 200], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            $user = User::find($id);
            $user->status = false;

            if ($user->save()) {
                session()->flash('message', 'User deleted successfully!');
                return Inertia::location('/admin/users');
            }

            return redirect()->back()->withErrors(['error' => 'Could not delete user!']);
        } catch (Exception $e) {

        }
    }
}
