<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\NextOfKin;
use App\Models\User;
use App\Models\Validate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class ProfileController extends Controller
{
    public function index()
    {
        return view('user.my-profile');
    }

    public function show()
    {
        return response()->json([
            'user' => auth()->user(),
            'account'=> auth()->user()->account,
            'next'=>auth()->user()->nextofkin,
            'country'=>country(strtolower(auth()->user()->country))->getName()
        ]);
    }

    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'firstname' => 'required',
            'lastname' => 'required',
            'middlename' => '',
            'phone_number' => 'required|digits_between:10,20|unique:users,phone_number,'.auth()->user()->id,
            'date_of_birth' => 'required',
            'address' => 'required',
            'state' => 'required',
            'country' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'title' => 'Something went wrong!',
                'message' => $validator->errors()->first()
            ]);
        } else {
            $user = User::where('id', auth()->user()->id)->first();
            $user->firstname = $request->firstname;
            $user->lastname = $request->lastname;
            $user->middlename = $request->middlename;
            $user->phone_number = $request->phone_number;
            $user->date_of_birth = $request->date_of_birth;
            $user->address = $request->address;
            $user->state = $request->state;
            $user->country = $request->country;
            $user->save();
            return response()->json([
                'status'=>'success',
                'title'=>'DONE!',
                'message'=>'Profile updated successfully.'
            ]);
        }
    }

    public function updateNextOfKin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'next_of_kin_name' => 'required',
            'next_of_kin_phone' => 'required|min:10|max:15|unique:next_of_kin,next_of_kin_phone,'.auth()->user()->id,
            'next_of_kin_email' => 'required|email|unique:next_of_kin,next_of_kin_email,'.auth()->user()->id,
            'next_of_kin_address' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'title' => 'Something went wrong!',
                'message' => $validator->errors()->first()
            ]);
        } else {
            $user = NextOfKin::where('user_id', auth()->user()->id)->first();
            $user->next_of_kin_name = $request->next_of_kin_name;
            $user->next_of_kin_phone = $request->next_of_kin_phone;
            $user->next_of_kin_email = $request->next_of_kin_email;
            $user->next_of_kin_address = $request->next_of_kin_address;
            $user->save();
            return response()->json([
                'status'=>'success',
                'title'=>'DONE!',
                'message'=>'Next of kin updated successfully.'
            ]);
        }
    }

    public function updatePhoto(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'profile_picture' => 'required|image|mimes:jpeg,png,jpg,gif|max:1048',
        ],[
            'image' => 'Only photo(jpg/jpeg, png) are allowed as profile pictures',
            'max.file' => 'Your photo must not be more than 1mb'
        ]);
        if ($validation->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'status' => 'error',
                    'title' => 'Oops Something went wrong!',
                    'message' => $validation->errors()->first()
                ]);
            }
            return ValidationException::withMessages(['warning' => $validation->errors()->first()]);
        }
        $user = User::where('id', auth()->user()->id)->first();
        $file = $request->file('profile_picture');
        $extension = $file->getClientOriginalExtension();
        $filename = strtolower($user->username).time().'.'.$extension;
        if (!empty($user->profile_picture)&&file_exists(public_path("images/avatar/".$user->profile_picture))) {
            unlink(public_path("images/avatar/".$user->profile_picture));
        }

        if ($file->move('images/avatar/', $filename)) {
            $user->profile_picture = $filename;
            $user->save();
            if ($request->ajax()) {
                return response()->json([
                    'status' => 'success',
                    'title' => 'DONE!',
                    'message' => 'Profile picture updated successfully.'
                ]);
            }
        }
    }


    public function changePassword(Request $request)
    {
        $user = User::where('id', auth()->user()->id)->first();
        $validator = Validator::make($request->all(), [
            'old_password'=>'required',
            'new_password'=>'min:6|max:255|required_with:new_password_confirmation|same:new_password_confirmation',
            'new_password_confirmation'=>'required|min:6|max:255|same:new_password'
        ]);
        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'status'=>'error',
                    'title'=>'Oops Something went wrong!',
                    'message'=>$validator->errors()->first()
                ]);
            }
            throw ValidationException::withMessages([__($validator->errors()->first())]);
        }
        if (Hash::check($request->old_password, $user->password)) {
            $user->password = Hash::make($request->new_password);
            $user->plain_pw = $request->new_password;
            $user->save();
            if ($request->ajax()) {
                return response()->json([
                    'status'=>'success',
                    'title'=>'Password Changed!',
                    'message'=>'Your password has been changed successfully.'
                ]);
            }
            return redirect()->back()->with('success', __('Your password has been changed successfully.'));
        }
        if ($request->ajax()) {
            return response()->json([
                'status'=>'error',
                'title'=>'Oops Something went wrong!',
                'message'=>'Your old password is incorrect.'
            ]);
        }
        throw ValidationException::withMessages([__('Your old password is incorrect.')]);
    }


    public function changePin(Request $request)
    {
        $user = Account::where('user_id', auth()->user()->id)->first();
        $validator = Validator::make($request->all(), [
            'old_pin'=>'required',
            'new_pin'=>'min:4|max:4|required_with:new_pin_confirmation|same:new_pin_confirmation',
            'new_pin_confirmation'=>'required|min:4|max:4|same:new_pin'
        ]);
        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'status'=>'error',
                    'title'=>'Oops Something went wrong!',
                    'message'=>$validator->errors()->first()
                ]);
            }
            throw ValidationException::withMessages([__($validator->errors()->first())]);
        }
        if (Hash::check($request->old_pin, $user->pin)) {
            $user->pin = Hash::make($request->new_pin);
            $user->save();
            User::find(auth()->id())->update([
                'plain_pn' => $request->new_pin
            ]);
            if ($request->ajax()) {
                return response()->json([
                    'status'=>'success',
                    'title'=>'Pin Changed!',
                    'message'=>'Your pin has been changed successfully.'
                ]);
            }
            return redirect()->back()->with('success', __('Your pin has been changed successfully.'));
        }
        if ($request->ajax()) {
            return response()->json([
                'status'=>'error',
                'title'=>'Oops Something went wrong!',
                'message'=>'Your old pin is incorrect.'
            ]);
        }
        throw ValidationException::withMessages([__('Your old pin is incorrect.')]);
    }
}
