<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\Models\User;
use App\Models\CityRange;
use Illuminate\Support\Facades\Auth; 
use Hash;

class EditProfileController extends Controller {
    
    /** 
     * index api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function index(Request $request) {
        
        $userId    = auth()->user()->id;
        
        $user                          = User::where('id', $userId)->first();
        $user->name                    = request('name');
        $user->email                   = request('email');
        $user->phone_number            = request('phone_number');
        $user->brokerage               = request('brokerage');
        $user->realtor                 = request('realtor');
        $user->real_estate_association = request('real_estate_association'); 
        $user->language                = request('language');
        $user->awards                  = request('awards');
        $user->website                 = request('website');
        $user->bio                     = request('bio');
        $user->address                 = request('address');
        $user->service_area            = request('service_area');
        $user->region                  = request('region');
        $user->city                    = request('city');
        $user->realtor_year            = request('realtor_year');
        $user->sports_played           = request('sports_played');
        $user->interest_and_hobby      = request('interest_and_hobby');
        $user->years_with_brokerage    = request('years_with_brokerage');
        $user->other_language          = request('other_language');
        $user->save();
        
        
        if($user->user_type == 2){
            if($user->profile_pic){
                $profile_pic = url('storage/profile_pictures/realtor/'.$user->id.'/'.$user->profile_pic);
            }else{
                $profile_pic = '';
            }
            
        }else{
            if($user->profile_pic){
                $profile_pic = url('storage/profile_pictures/customer/'.$user->id.'/'.$user->profile_pic);
            }else{
                $profile_pic = '';
            }
        }
        
        $data = [
            'id'                      => $user->id,
            'name'                    => $user->name,
            'user_name'               => $user->user_name,
            'email'                   => $user->email,
            'phone_number'            => $user->phone_number,
            'brokerage'               => $user->brokerage, 
            'user_type'               => $user->user_type,
            'realtor'                 => $user->realtor,                 
            'real_estate_association' => $user->real_estate_association, 
            'language'                => $user->language,                
            'awards'                  => $user->awards,                 
            'website'                 => $user->website,                 
            'bio'                     => $user->bio,                    
            'address'                 => $user->address,                
            'service_area'            => $user->service_area,           
            'region'                  => $user->region,               
            'city'                    => $user->city,               
            'realtor_year'            => $user->realtor_year,               
            'sports_played'           => $user->sports_played,               
            'interest_and_hobby'      => $user->interest_and_hobby,               
            'years_with_brokerage'    => $user->years_with_brokerage,               
            'other_language'          => $user->other_language, 
            'profile_pic'             => $profile_pic,
        ];
        
        CityRange::where('user_id',$user->id)->delete();
        
        $cityRange = request('city_range');
        if($cityRange){
            $cityRange = json_decode($cityRange,true);
            foreach($cityRange as $cityRow){
                $cityRangeData = new CityRange();
                $cityRangeData->user_id    = $user->id;
                $cityRangeData->city_name  = $cityRow['cityName'];
                $cityRangeData->city_range = $cityRow['rangeKM'];
                $cityRangeData->save();
            }
        }
        
        $dataArray              = [];
        $dataArray['userData']  = $data;
        $dataArray['cityRange'] = CityRange::select('city_name','city_range')->where('user_id',$user->id)->orderBy('id','asc')->get();

        return response()->json([
            'success'     => 1,
            'data'        => $dataArray,
            'message'     => 'Profile Successfully Updated.'
        ], 200);
        
    }
    
    public function changePassword(Request $request) {
        
        $oldPassword     = request('old_password');
        $newPassword     = request('new_password');
        $confirmPassword = request('confirm_password');
        $userId          = auth()->user()->id;
        
        $user = User::select('id','password')->where('id',$userId)->first();
        if (!Hash::check($oldPassword, $user->password)) {
            return response()->json([
                'success'  => 0,
                'error'    => 'The old password you have entered is incorrect.'
            ], 200);
        }else if($newPassword != $confirmPassword){
            return response()->json([
                'success'  => 0,
                'error'    => 'The password and confirmation password do not match.'
            ], 200);
        }else{
           $user->password = Hash::make($newPassword);
           $user->save();
            return response()->json([
                'success'    => 1,
                'message'    => 'Your password has been changed.'
            ], 200);
        }
        
    }
    
    public function changeProfilePicture(Request $request)
    {
        $type   = request('type');
        $userId = auth()->user()->id;

        if($type == 'realtor'){
            
            $base64          = request('base64');
            $actualFilename  = request('filename'); 
            $customFilename  = time() . "_" . str_replace(" ","_",$actualFilename);
            
            $newDir  = storage_path('profile_pictures/realtor/'.$userId);
            if (!file_exists($newDir)) {
                mkdir($newDir, 0777, true);
            }
            $savePath = $newDir.'/'.$customFilename;
            file_put_contents($savePath, base64_decode($base64));
            
            $user              = User::select('id', 'profile_pic')->where('id', $userId)->first();
            $user->profile_pic = $customFilename;
            $user->save();
            
            $profile_pic = url('storage/profile_pictures/realtor/'.$user->id.'/'.$customFilename);
        }
        
        if($type == 'customer'){
            $base64          = request('base64');
            $actualFilename  = request('filename'); 
            $customFilename  = time() . "_" . str_replace(" ","_",$actualFilename);
            
            $newDir  = storage_path('profile_pictures/customer/'.$userId);
            
            if (!file_exists($newDir)) {
                mkdir($newDir, 0777, true);
            }
            $savePath = $newDir.'/'.$customFilename;
            file_put_contents($savePath, base64_decode($base64));
            
            $user              = User::select('id', 'profile_pic')->where('id', $userId)->first();
            $user->profile_pic = $customFilename;
            $user->save();
            
            $profile_pic = url('storage/profile_pictures/customer/'.$user->id.'/'.$customFilename);
        }
        
        return response()->json([
            'success'     => 1,
            'profile_pic' => $profile_pic,
            'message'     => 'Profile Picture Successfully Changed.'
        ], 200);
    }
}