<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\MemberKelompokTani;
use App\Models\KelompokTani;

class UserSettingController extends Controller
{
    public function index()
    {
        $userLogin = Auth::user();

        if ($userLogin->role === 'super_admin') {
            $users = User::with(['kelompokTani'])->get();
            $kelompokTani = KelompokTani::all();
        } elseif ($userLogin->role === 'admin') {
            $adminKelompok = MemberKelompokTani::where('user_id', $userLogin->id)->first();
            $userIds = MemberKelompokTani::where('kelompok_tani_id', $adminKelompok->kelompok_tani_id)
                        ->pluck('user_id');
            $users = User::whereIn('id', $userIds)->with('kelompokTani')->get();
            $kelompokTani = [];
        } else {
            $users = User::where('id', $userLogin->id)->with('kelompokTani')->get();
            $kelompokTani = [];
        }

        return view('admin.usersetting', [
            'users' => $users,
            'kelompokTani' => $kelompokTani,
            'title' => 'Data User'
        ]);
    }

    public function store(Request $request)
    {
        $userLogin = Auth::user();

        if (!in_array($userLogin->role, ['admin', 'super_admin'])) {
            abort(403, 'Tidak punya izin');
        }

        $rules = [
            'name'     => 'required|string|max:255',
            'username' => 'required|string|max:255|unique:users,username',
            'password' => 'required|string|min:6',
            'role'     => 'required|string|in:admin,user'
        ];

        if ($userLogin->role === 'super_admin') {
            $rules['kelompok_tani_id'] = 'required|exists:kelompok_tani,id';
        }

        $request->validate($rules);

        $newUser = User::create([
            'name'     => $request->name,
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'role'     => $request->role,
        ]);

        if ($userLogin->role === 'super_admin') {
            $kelompokTaniId = $request->kelompok_tani_id;
        } else {
            $adminKelompok = MemberKelompokTani::where('user_id', $userLogin->id)->first();
            if (!$adminKelompok) {
                return redirect()->back()->with('error', 'Admin belum terdaftar di kelompok tani.');
            }
            $kelompokTaniId = $adminKelompok->kelompok_tani_id;
        }

        MemberKelompokTani::create([
            'user_id' => $newUser->id,
            'kelompok_tani_id' => $kelompokTaniId,
            'role' => $request->role
        ]);

        return redirect()->back()->with('success', 'User berhasil ditambahkan.');
    }

    public function update(Request $request, $id)
    {
        $userLogin = Auth::user();
        $user = User::findOrFail($id);

        $loginKelompok = MemberKelompokTani::where('user_id', $userLogin->id)->first();
        $targetKelompok = MemberKelompokTani::where('user_id', $user->id)->first();

        if ($user->role === 'super_admin' && $userLogin->id !== $user->id) {
            abort(403, 'Tidak diizinkan mengubah akun super admin.');
        }

        if ($userLogin->role !== 'super_admin' &&
            ($userLogin->id !== $user->id && $loginKelompok->kelompok_tani_id !== $targetKelompok->kelompok_tani_id)) {
            abort(403, 'Tidak diizinkan mengedit user di luar kelompok.');
        }

        $rules = [
            'name'     => 'required|string|max:255',
            'username' => 'required|string|max:255|unique:users,username,' . $user->id,
            'password' => 'nullable|string|min:6',
            'role'     => 'required|string|in:admin,user'
        ];

        if ($userLogin->role === 'super_admin') {
            $rules['kelompok_tani_id'] = 'required|exists:kelompok_tani,id';
        }

        $request->validate($rules);

        $data = [
            'name'     => $request->name,
            'username' => $request->username,
            'role'     => $request->role,
        ];

        if ($request->filled('password')) {
            $data['password'] = Hash::make($request->password);
        }

        $user->update($data);

        if ($targetKelompok) {
            $targetKelompok->role = $request->role;

            if ($userLogin->role === 'super_admin') {
                $targetKelompok->kelompok_tani_id = $request->kelompok_tani_id;
            }

            $targetKelompok->save();
        }

        return redirect()->route('usersetting.index')->with('success', 'User berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $userLogin = Auth::user();
        $user = User::findOrFail($id);

        if ($userLogin->id === $user->id) {
            return redirect()->back()->with('error', 'Kamu tidak bisa menghapus akunmu sendiri.');
        }
        if ($userLogin->role === 'admin' && $user->role === 'admin') {
            return back()->with('error', 'Admin tidak boleh menghapus sesama admin.');
        }

        $loginKelompok = MemberKelompokTani::where('user_id', $userLogin->id)->first();
        $targetKelompok = MemberKelompokTani::where('user_id', $user->id)->first();

        if ($user->role === 'super_admin') {
            abort(403, 'Tidak diizinkan menghapus akun super admin.');
        }

        if ($userLogin->role !== 'super_admin') {
            if (!$loginKelompok || !$targetKelompok ||
                $loginKelompok->kelompok_tani_id !== $targetKelompok->kelompok_tani_id) {
                abort(403, 'Tidak diizinkan menghapus user di luar kelompok.');
            }
        }

        $user->delete();

        return redirect()->route('usersetting.index')->with('success', 'User berhasil dihapus.');
    }
}