<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
// use Spatie\Permission\Models\Role;
use App\Models\Role;
use Carbon\Carbon;
use DB;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    // public function __construct()
    // {
    //     $this->middleware('permission:view users')->only(['index', 'show']);
    //     $this->middleware('permission:create users')->only(['create', 'store']);
    //     $this->middleware('permission:edit users')->only(['edit', 'update']);
    //     $this->middleware('permission:delete users')->only(['destroy']);
    // }


   
    public function index(Request $request)
    {
        $query = Admin::orderBy('created_at', 'desc');
        
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('name', 'like', '%' . $search . '%')
                    ->orWhere('email', 'like', '%' . $search . '%');
        }
        $users = $query->paginate(10);

        if ($request->ajax()) {
            return view('admin.users.ajax', compact('users'))->render();
        }
        return view('admin.users.list', compact('users'));
    }


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // dd(Admin::all());
        $currentAdmin = auth()->user();
        // dd($currentAdmin);
        return view('admin.users.create', [
            'users' => Admin::all(),
            'roles' => Role::all(),
            'currentAdmin' => $currentAdmin
        ]);

    
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // $request->validate([
        //     'name' => 'required|string',
        //     'email' => 'required|email|unique:admins',
        //     'password' => 'required|min:8',
        //     'role' => 'required'
        // ]);

         $rules = [
            'name' => 'required|regex:/^[a-zA-Z\s]+$/',
            'email' => 'required|email|unique:admins',
            'password' => 'required|min:8',
            'role' => 'required',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif',
                                                                                   
        ];

        $messages = [
            'name.required' => 'Name is required.',
            'name.regex' => 'Name accept only character.',
            'email.required' => 'Email is required.',
            'password.required' => 'Password is required.',
            'role.required' => 'Role is required.',
            'image.image' => 'The uploaded file must be an image.',
            'image.mimes' => 'Only jpeg, png, jpg, and gif formats are allowed.',
           

        ];

        $validation = Validator::make($request->all(), $rules, $messages);
        if ($validation->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ], 200);
        }

        // DB::beginTransaction();
        try{
        

                $adminImage = null;

                if ($image = $request->file('image')) {
                    $adminImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
                    $image->move(public_path('storage/user'), $adminImage);
                }
                
                $admin = Admin::create([
                    'name'  => $request->name,
                    'email' => $request->email,
                    'image' => $adminImage,
                    'password' => bcrypt($request->password),
                    'role_id' => $request->role,
                    'status'  => 1,
                ]);

                // $admin->assignRole($request->role);
                // DB::commit();
                return response()->json([
                    'success' => true
                ]);
            }
            catch (\Exception $e) {
                // DB::rollback();
                // something went wrong
                return $e;
            }

        // return redirect()->back()->with('success', 'Admin user created successfully.');
    }

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


    public function edit($id)
    {
        $editadmin  = Admin::findOrFail(base64_decode($id)); 
        $roles      = Role::all();
        return view('admin.users.edit', compact('editadmin','roles'));
    }

 

    public function update(Request $request)
{
    $id = base64_decode($request->id);

    $rules = [
        'name'  => 'required|regex:/^[a-zA-Z\s]+$/',
        'image' => 'nullable|image|mimes:jpeg,png,jpg,gif',
        'email' => 'required|email|unique:admins,email,'.$id,
        'role' => 'required',
    ];

    $messages = [
       'name.required' => 'Name is required.',
        'name.regex' => 'Name accept only character.',
        'image.image' => 'The uploaded file must be an image.',
        'image.mimes' => 'Only jpeg, png, jpg, and gif formats are allowed.',
        'email.required' => 'Email is required.',
        'role.required' => 'Role is required.',
    ];

        $validation = Validator::make($request->all(), $rules, $messages);
        if ($validation->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ], 200);
        }

    try {
        $user = Admin::findOrFail($id);

        $user->name  = $request->name;
        $user->status = $request->status;
        $user->email = $request->email;
        $user->role_id  = $request->role;


        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            $file = $request->file('image');
            $filename = 'img_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('storage/user'), $filename);

            // Remove old image
            if ($user->image && file_exists(public_path('storage/user/' . $user->image))) {
                unlink(public_path('storage/user/' . $user->image));
            }

            $user->image = $filename;
        }

        $user->save();

        return response()->json([
            'success' => true,
            'message' => 'User updated successfully.'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'errors' => ['server' => [$e->getMessage()]]
        ]);
    }
}



    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function userStatus(Request $request)
    {
        $admin_id=base64_decode($request->id);
        $type = base64_decode($request->type);
    
        if($type == 'disable')
        { 
            $user = Admin::find($admin_id);
            $user->status = '0';
            $user->save();
            
            return response()->json([
                'success'=>true,
                'type' => $type,
                'message'=>'Status change successfully.'
            ]);
        }
        elseif($type == 'enable')
        {   
            $user = Admin::find($admin_id);
            $user->status = '1';
            $user->save();
        
            return response()->json([
                'success'=>true,
                'type' => $type,
                'message'=>'Status change successfully.'
            ]);
        }
    }


}
