<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\PasswordRequest;
use App\Http\Requests\ProfileSettingRequest;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class ProfileSettingsController extends Controller
{
    public function index()
    {
        $data['pageTitle'] = __('Profile Settings');
        $data['previousBreadcrumb'] = __('Dashboard');
        $data['breadcrumb'] = __('Profile Settings');
        $data['profileSettingsMenuActive'] = 'active';
        $data['user'] = User::where('id', auth()->id())->first();
        return view('user.profile.index', $data);
    }

    public function update(ProfileSettingRequest $request)
    {
        try {
            $data = User::where('id', decrypt($request->updateId))->where('role', auth()->id())->first();
            $data['name'] = $request->name;
            $data['email'] = $request->email;
            $data['phone'] = $request->phone;
            $data['dob'] = $request->dob;
            $data['city'] = $request->city;
            $data['state'] = $request->state;
            $data['address'] = $request->address;
            $data['gender'] = $request->gender;
            if ($request->hasFile('picture')) {
                $data['picture'] = singleFileUpload($request->file('picture'), 'uploads/users', $data->picture);
            }
            $data->save();
            return response()->json(['status' => 'success', 'message' => 'Updated successfully!', 'data' => []], 200);
        } catch (Exception $e) {
            Log::error($e);
            return response()->json(['status' => 'error', 'message' => 'Something Went Wrong', 'data' => []], 200);
        }
    }

    public function passwordUpdate(PasswordRequest $request)
    {
        try {
            $data = User::where('id', decrypt($request->updateId))
                ->where('role', auth()->id())
                ->first();
            if ($data && Hash::check($request->current_password, $data->password)) {
                $data->password = Hash::make($request->new_password);
                $data->save();
                return response()->json(['status' => 'success', 'message' => 'Password Updated successfully!', 'data' => []], 200);
            }
            return response()->json(['status' => 'error', 'message' => 'Current Password Does not Match', 'data' => []], 200);
        } catch (Exception $e) {
            Log::error($e);
            return response()->json(['status' => 'error', 'message' => 'Something Went Wrong', 'data' => []], 200);
        }
    }
}
