<?php

namespace App\Http\Controllers;

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

class ProfilController extends Controller
{
    /**
     * Konstruktor untuk memastikan hanya user yang login yang bisa akses
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Menampilkan profil diri sendiri dan daftar user berdasarkan role
     */
    public function index()
    {
        $currentUser = Auth::user();

        // LOGIKA FILTER USER BERDASARKAN ROLE
        if ($currentUser->role === 'super admin') {
            $users = User::where('id', '!=', $currentUser->id)->get();
        } elseif ($currentUser->role === 'admin') {
            $users = User::where('role', 'user')->get();
        } else {
            $users = collect();
        }

        return view('profil', [
            'user'  => $currentUser,
            'users' => $users
        ]);
    }

    /**
     * UPDATE PROFIL SENDIRI (Termasuk Foto)
     */
    public function update(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'foto'         => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
            'username'     => 'required|string|unique:users,username,' . $user->id,
            'nama_lengkap' => 'required|string|min:3', 
            'password'     => 'nullable|min:6',
        ], [
            'foto.image'            => 'File yang diunggah harus berupa gambar.',
            'foto.mimes'            => 'Foto harus format: jpg, jpeg, atau png.',
            'foto.max'              => 'Ukuran foto maksimal adalah 2MB.',
            'username.required'     => 'Username tidak boleh kosong.',
            'username.unique'       => 'Username sudah digunakan oleh pengguna lain.',
            'nama_lengkap.required' => 'Nama lengkap wajib diisi.',
            'nama_lengkap.min'      => 'Nama lengkap minimal harus 3 karakter.',
            'password.min'          => 'Password baru minimal harus 6 karakter.',
        ]);

        // Cek jika tidak ada perubahan sama sekali
        if (!$request->hasFile('foto') && 
            $request->username === $user->username && 
            $request->nama_lengkap === $user->nama_lengkap && 
            !$request->filled('password')) {
            return back()->with('info', 'Tidak ada perubahan pada profil Anda.');
        }

        // Handle Upload Foto menggunakan helper function
        if ($request->hasFile('foto')) {
            $this->handleUpload($request, $user);
        }

        $user->username = $request->username;
        $user->nama_lengkap = $request->nama_lengkap;

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

        $user->save();
        return back()->with('success', 'Profil Anda berhasil diperbarui!');
    }

    /**
     * TAMBAH USER BARU (Oleh Admin/Super Admin)
     */
    public function store(Request $request)
    {
        $currentUser = Auth::user();

        $request->validate([
            'username'     => 'required|string|unique:users,username', 
            'nama_lengkap' => 'required|string|min:3', 
            'role'         => 'required|in:admin,user,super admin',
            'password'     => 'required|min:4',
        ], [
            'username.required' => 'Username wajib diisi.',
            'username.unique'   => 'Username sudah terdaftar! Gunakan username lain.',
            'nama_lengkap.min'  => 'Nama minimal 3 karakter.',
        ]);

        if ($currentUser->role === 'admin' && $request->role !== 'user') {
            return back()->with('error', 'Admin hanya boleh menambahkan user dengan role User.');
        }

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

        return back()->with('success', 'User baru berhasil ditambahkan!');
    }

    /**
     * UPDATE DATA USER LAIN (Oleh Admin/Super Admin)
     */
    public function updateOther(Request $request, $id)
    {
        $targetUser = User::findOrFail($id);
        $currentUser = Auth::user();

        if ($currentUser->role === 'admin' && $targetUser->role !== 'user') {
            return back()->with('error', 'Anda tidak memiliki akses untuk mengubah data ini.');
        }

        $request->validate([
            'foto'         => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
            'username'     => 'required|string|unique:users,username,' . $id,
            'nama_lengkap' => 'required|string|min:3',
            'role'         => 'required|in:admin,user,super admin',
        ], [
            'username.unique' => 'Gagal! Username ini sudah dimiliki user lain.',
        ]);

        // Handle Upload Foto jika admin mengganti foto user lain
        if ($request->hasFile('foto')) {
            $this->handleUpload($request, $targetUser);
        }

        $targetUser->username = $request->username;
        $targetUser->nama_lengkap = $request->nama_lengkap;
        
        if ($currentUser->role === 'super admin') {
            $targetUser->role = $request->role;
        }

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

        $targetUser->save();
        return back()->with('success', 'Data user berhasil diubah!');
    }

    /**
     * HAPUS USER
     */
    public function destroy($id)
    {
        $targetUser = User::findOrFail($id);
        $currentUser = Auth::user();

        if ($currentUser->id == $id) {
            return back()->with('error', 'Anda tidak bisa menghapus akun sendiri!');
        }

        if ($currentUser->role === 'admin' && $targetUser->role !== 'user') {
            return back()->with('error', 'Anda tidak memiliki otoritas menghapus role ' . $targetUser->role);
        }

        // Hapus file foto dari server saat user dihapus
        if ($targetUser->foto && File::exists(public_path('foto_profil/' . $targetUser->foto))) {
            File::delete(public_path('foto_profil/' . $targetUser->foto));
        }

        $targetUser->delete();
        return back()->with('success', 'User berhasil dihapus.');
    }

    /**
     * HELPER FUNCTION: Logika Upload Gambar
     * Digunakan agar kode update dan updateOther tetap bersih
     */
    private function handleUpload(Request $request, $user)
    {
        $path = public_path('foto_profil');

        // Buat folder jika belum ada
        if (!File::isDirectory($path)) {
            File::makeDirectory($path, 0777, true, true);
        }

        // Hapus foto lama jika ada
        if ($user->foto && File::exists($path . '/' . $user->foto)) {
            File::delete($path . '/' . $user->foto);
        }

        // Simpan file baru
        $file = $request->file('foto');
        $namaFile = time() . '_' . hexdec(uniqid()) . '.' . $file->getClientOriginalExtension();
        $file->move($path, $namaFile);
        
        // Update field foto di objek user
        $user->foto = $namaFile;
    }
}