<?php

namespace App\Http\Controllers;

use App\Models\Role;
use App\Models\User;
use App\Models\Roles;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UsersController extends Controller
{
    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'fullName' => 'required|string',
            'role_id' => 'required|exists:roles,id',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8',
            'etat' => 'nullable|string',
            'phone' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 400);
        }

        if (User::where('email', $request->email)->whereNull('deleted_at')->exists()) {
            return response()->json(['message' => 'User email already exists.'], Response::HTTP_CONFLICT);
        }

        $data = $request->only('fullName', 'role_id', 'email', 'password', 'etat', 'fonction', 'double_auth', 'phone');
        $data['password'] = Hash::make($request->password);



        $user = User::create($data);

        return response()->json(['message' => 'User registered successfully.', 'data' => $user], 201);
    }

    // Update a user
    public function update(Request $request, $id)
    {
        $user = User::find($id);

        if (!$user) {
            return response()->json(['message' => 'User not found.'], 404);
        }

        $validator = Validator::make($request->all(), [
            'fullName' => 'required|string',
            'role_id' => 'required|exists:roles,id',
            'email' => 'required|email|unique:users,email,' . $id,
            'etat' => 'required|string',
            'phone' => 'required|string',
            'image' => 'nullable'
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 400);
        }

        $user->fill($request->only('fullName', 'role_id', 'email', 'etat', 'fonction', 'double_auth', 'phone'));

        $user->save();

        return response()->json(['message' => 'User updated successfully.', 'data' => $user], 200);
    }

    // Get a single user by ID
    public function get($id)
    {
        $user = User::with('role')->where('id', $id)->whereNull('deleted_at')->first();

        if (!$user) {
            return response()->json(['message' => 'No User found.'], 404);
        }

        return response()->json(['message' => 'User retrieved successfully.', 'data' => $user], 200);
    }

    // Search for users
    public function search()
    {
        $users = User::with('role')->whereNull('deleted_at')->orderBy('created_at', 'desc')->get();

        return response()->json(['message' => 'Users retrieved successfully.', 'data' => $users], 200);
    }

    // Soft delete a user
    public function destroy($id)
    {
        $user = User::find($id);

        if (!$user) {
            return response()->json(['message' => 'User not found.'], 404);
        }

        $user->deleted_at = now();
        $user->save();

        return response()->json(['message' => 'User deleted successfully.'], 200);
    }

    // Get the current user's profile
    public function getUserProfile(Request $request)
    {
        $user = $request->user()->load('role');
        return response()->json(['message' => 'Current user data.', 'data' => $user], 200);
    }

    // Update the current user's profile
    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'fullName' => 'required|string',
            'email' => 'required|email|unique:users,email,' . $user->id,
            'phone' => 'required|string',
            'image' => 'nullable',

        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 400);
        }

        $user->fill($request->only('fullName', 'email', 'phone'));
        $user->double_auth = $request->double_auth;

        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('users', 'public');
            $user->image = $path;
        }

        $user->save();

        return response()->json(['message' => 'User updated successfully.', 'data' => $user], 200);
    }

    // Change the current user's password
    public function changePassword(Request $request)
    {
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'current' => 'required|string',
            'newPass' => 'required|string|min:8',
            'confirmNewPass' => 'required|string|min:8'
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 400);
        }
        if ($request->newPass !== $request->confirmNewPass) {
            return response()->json(['message' => 'The confirmation password does not match.'], 400);
        }

        if (!Hash::check($request->current, $user->password)) {
            return response()->json(['message' => 'Current password is incorrect.'], 401);
        }

        $user->password = Hash::make($request->newPass);
        $user->save();

        return response()->json(['message' => 'Password changed successfully.'], 200);
    }





    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'fullName' => 'required|string',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8',
            'phone' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 400);
        }
        if (User::where('email', $request->email)->whereNull('deleted_at')->exists()) {
            return response()->json(['message' => 'User email already exists.'], Response::HTTP_CONFLICT);
        }

        $clientRole = Roles::where('name', 'Client')->whereNull('deleted_at')->first();

        $data = $request->only('fullName', 'email', 'password', 'phone');
        $data['password'] = Hash::make($request->password);
        $data['role_id'] = $clientRole->id;
        $data['double_auth'] = 1;

        $user = User::create($data);

        return response()->json(['message' => 'User registered successfully.', 'data' => $user], 201);
    }
}
