<?php

namespace App\Http\Controllers;

use App\Enums\BulkActionEnum;
use App\Enums\FileKey;
use App\Enums\StatusEnum;
use App\Http\Requests\UserStoreRequest;
use App\Models\Role;
use App\Models\User;
use App\Traits\Fileable;
use App\Traits\ModelAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Inertia\Inertia;

class StuffController extends Controller
{
    use Fileable, ModelAction;

    public function index(Request $request)
    {
        $key = $request->get('key');
        $search = $request->get('search');
        $status = $request->get('status');
        $page = $request->get('page', 1);

        // --- User Query ---
        $userQuery = User::query();
        if ($key === "user-search") {
            if (!empty($search)) {
                $userQuery->where(function ($q) use ($search) {
                    $q->where("name", "like", "%{$search}%")
                        ->orWhere("email", "like", "%{$search}%");
                });
            }

            if ($status !== null) {
                $userQuery->where("status", $status);
            }
        }

        // --- Role Query ---
        $roleQuery = Role::query();
        if ($key === "role-search") {
            if (!empty($search)) {
                $roleQuery->where(function ($q) use ($search) {
                    $q->where("name", "like", "%{$search}%")
                        ->orWhere("email", "like", "%{$search}%");
                });
            }

            if ($status !== null) {
                $roleQuery->where("status", $status);
            }
        }

        return Inertia::render("Stuffs", [
            "users" => $userQuery->with('role')->latest()->paginate(paginateNumber(), ['*'], 'usersPage')
                ->withQueryString(),
            "roles" => $roleQuery->with('createdBy')->latest()->paginate(paginateNumber(), ['*'], 'rolesPage')
                ->withQueryString(),
            "allRoles" => Role::where('status', '1')->get(['id', 'name']),
            "rolePermissions" => config('settings.role_permissions'),
            "statusEnum" => StatusEnum::toArray(),
            "filters" => $request->only(["key", "search", "status"]),
        ]);
    }


    public function store(UserStoreRequest $request)
    {
        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => $request->input('password'),
            'status' => $request->input('status'),
            'role_id' => $request->input('role_id') == '0' ? null : $request->input('role_id'),
        ]);

        if ($request->hasFile('profile_image')) {
            $oldFile = $user->files()->where('type', FileKey::AVATAR->value)->first();
            $this->saveFile(
                $user,
                $this->storeFile(
                    file: $request->file('profile_image'),
                    location: config("settings")['file_path']['profile']['user']['path'],
                    removeFile: @$oldFile
                )
                ,
                FileKey::AVATAR->value
            );

        }

        return redirect()->back()->with('success', 'User saved');


    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:users,id',
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $request->id,
            'status' => 'required',
            'role_id' => 'nullable|exists:roles,id',
        ]);

        $user = User::findOrFail($request->input('id'));

        $user->update([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'status' => $request->input('status'),
            'role_id' => $request->input('role_id') == '0' ? null : $request->input('role_id'),
        ]);

        if ($request->hasFile('profile_image')) {
            $oldFile = $user->files()->where('type', FileKey::AVATAR->value)->first();
            $this->saveFile(
                $user,
                $this->storeFile(
                    file: $request->file('profile_image'),
                    location: config("settings")['file_path']['profile']['user']['path'],
                    removeFile: @$oldFile
                ),
                FileKey::AVATAR->value
            );
        }

        return redirect()->back()->with('success', 'User updated successfully');
    }

    public function statusUpdate(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:users,id',
            'status' => 'required',
        ]);

        try {
            $workspace = User::findOrFail($request->id);
            $workspace->status = $request->status;
            $workspace->save();

            return back()->with('success', 'User status updated successfully');
        } catch (\Exception $e) {
            return back()->with('error', 'User status did not change');

        }
    }

    public function delete(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:users,id'
        ]);

        $user = User::findOrFail($request->input('id'));
        $user->delete();

        return redirect()->route('user.access-control.index')->with('success', 'User Deleted');

    }

    public function bulk(Request $request)
    {
        $validated = $request->validate([
            'action' => ['required', Rule::in(BulkActionEnum::values())],
            'ids' => 'required|array',
            'ids.*' => 'integer'
        ]);

        $query = User::whereIn('id', $validated['ids']);

        match (BulkActionEnum::from($validated['action'])) {
            BulkActionEnum::ACTIVATE => $query->update(['status' => StatusEnum::true->status()]),
            BulkActionEnum::INACTIVATE => $query->update(['status' => StatusEnum::false->status()]),
            BulkActionEnum::DELETE => $query->delete(),
        };

        return back()->with('success', "Bulk {$validated['action']} completed.");
    }


    public function login(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:users,id'
        ]);

        $user = User::findOrFail($request->input('id'));

        Auth::guard('web')->loginUsingId($user->id);

        return redirect()->route('user.home')
            ->with(response_status("Successfully logged in as a $user->name"));





    }
}
