<?php

namespace App\Http\Controllers;

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

class AdminDashboardUserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $users = User::where('role','user')->paginate(10);
        return view('awa.pages.users.index', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
        {
            $user = new User();

            return view('awa.pages.users.create', compact('user'));
        }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
{
    $data = $request->validate([
        'name'     => 'required|string|max:255',
        'email'    => 'required|email|unique:users,email',
        'password' => 'required|confirmed|min:6',
        // no "image" validation here now
        'avatar_file' => 'nullable',
    ]);

    if ($request->hasFile('avatar_file')) {
        $file     = $request->file('avatar_file');
        $filename = time() . '_' . $file->getClientOriginalName();
        $dest     = public_path('avatars');

        if (! is_dir($dest)) {
            mkdir($dest, 0755, true);
        }

        $file->move($dest, $filename);

        // Save final URL/path in avatar_url column
        $data['avatar_url'] = asset("avatars/{$filename}");
    }

    unset($data['avatar_file']); // not a DB column

    $data['password'] = bcrypt($data['password']);
    $data['role']     = 'user';

    User::create($data);

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



    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        //
    } 

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
       // abort_if($user->role!=='user',404);
       $user = User::findOrFail($id);
        return view('awa.pages.users.create', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     */
   public function update(Request $request, $id)
{
    $rules = [
        'name'       => 'required|string|max:255',
        'email'      => 'required|email',
        'avatar_url' => 'nullable|image|max:2048',
    ];

    // On edit: password is optional, no confirmation check
    if ($request->filled('password')) {
        $rules['password'] = 'nullable|min:6';   // ⬅️ removed "confirmed"
    }

    $data = $request->validate($rules);

    // Only set password if user actually typed something
    if ($request->filled('password')) {
        $data['password'] = bcrypt($request->input('password'));
    }

    // Handle avatar upload
    if ($request->hasFile('avatar_url')) {
        $file     = $request->file('avatar_url');
        $filename = time() . '_' . $file->getClientOriginalName();
        $dest     = public_path('avatars');

        if (! is_dir($dest)) {
            mkdir($dest, 0755, true);
        }

        $file->move($dest, $filename);
        $data['avatar_url'] = asset("avatars/{$filename}");
    }

    $user = User::findOrFail($id);
    $user->update($data);

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


    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id , Request $request)
    {

        $user = User::findOrFail($id);

        if ($user->avatar_url) {
        File::delete(public_path().'/avatars'.$user->avatar_url);
        }
        $user->delete();
        return back()->with('success','User deleted.');
    }
}
