<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Models\CityRange;
use Crypt;
use Hash;

class EditProfileController extends Controller
{
    
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function edit(Request $request)
    {
        $this->bladeContent['title']      = 'Edit Profile';
        $this->bladeContent['active']     = 'edit-profile';
        $this->bladeContent['user']       = User::where('id',auth()->user()->id)->first();
        $this->bladeContent['cityRanges'] = CityRange::where('user_id',auth()->user()->id)->get();
        return view('edit_profile.edit',$this->bladeContent);
    }
    
    public function update(Request $request)
    {
        
        $language = NULL;
        if(request('language')){
            $language = explode(', ',request('language'));
        }
        
        $user                          = User::where('id',auth()->user()->id)->first();
        $user->name                    = request('name');
        $user->phone_number            = request('phone_number');
        $user->email                   = request('email');
        $user->address                 = request('address');
        $user->brokerage               = request('brokerage');
        $user->real_estate_association = request('real_estate_association');
        $user->awards                  = request('awards');
        $user->website                 = request('website');
        $user->realtor                 = request('realtor');
        $user->bio                     = request('bio');
        $user->sports_played           = request('sports_played');
        $user->interest_and_hobby      = request('interest_and_hobby');
        $user->years_with_brokerage    = request('years_with_brokerage');
        $user->realtor_year            = request('years_of_realtor');
        $user->language                = $language ? json_encode($language) : NULL;
        $user->other_language          = request('other_language');
        
        if($request->hasFile('profile_pic')){
            $file    = $request->file('profile_pic');
            $newDir  = storage_path('profile_pictures/realtor/'.auth()->user()->id);
            if (!file_exists($newDir)) {
                mkdir($newDir, 0777, true);
            }
            $fileName = time() . "_" . str_replace(" ","_",$file->getClientOriginalName());
            $file->move(storage_path('profile_pictures/realtor/'.auth()->user()->id),$fileName);
            $user->profile_pic = $fileName;
        }
        
        $user->save();
        
        $city      = request('city');
        $cityRange = request('city_range');
        $cityIds   = request('city_id');
        
        if($cityIds && is_array($cityIds)){
            CityRange::where('user_id', auth()->user()->id)->whereNotIn('id',$cityIds)->delete();
        }
        
        if($city){
            foreach($city as $key => $data){
                if($cityIds && count($cityIds) > 0 && array_key_exists($key,$cityIds)){
                    $cityRangeData = CityRange::where('id',$cityIds[$key])->first();
                }else{
                    $cityRangeData          = new CityRange();
                    $cityRangeData->user_id = auth()->user()->id;
                }
                $cityRangeData->city_name  = $data;
                $cityRangeData->city_range = $cityRange[$key];
                $cityRangeData->save();
            }
        }
        
    
        return redirect()->back()->with('success', 'Profile successfully updated.');
    }
    
    public function changePassword(Request $request)
    {
        $id    = auth()->user()->id;
        $users = User::select('id', 'password')->where('id', $id)->first();
        if (!Hash::check($request->get('old_password'), $users->password)) {
           return redirect()->back()->with('error', 'The current password you have entered is incorrect.');   
        }else if($request->get('new_password') != $request->get('confirm_password')){
           return redirect()->back()->with('error', 'The password and confirmation password do not match.');
        }else{
           $users->password = Hash::make(request('new_password'));
           $users->save();
           return redirect()->back()->with('success', 'Password successfully changed.');
        }
    }
}