<?php
namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Models\CityRange;
use App\Models\Province;
use App\Models\Region;
use App\Models\City;
use App\Models\RealtorYear;
use App\Models\Language;
use App\Models\MessageThread;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Config;
use App\Http\Controllers\Controller;
use Crypt;
use Illuminate\Support\Facades\Http;

class RealtorsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
         if($request->ajax()){
             return datatables()->of(User::select('id', 'name', 'email', 'status', 'phone_number', 'created_at')->where('user_type','2'))
           ->addColumn('actions', function($row){
                return '<span class="action-links"><a class="uk-text-primary uk-edit" href="'.url('admin/realtors/'.$row->id.'/edit').'" uk-tooltip="Edit Realtor"><i class="fa-solid fa-pen-to-square"></i></a></span>';
            })
            ->addColumn('status', function($row){
                if($row->status == '1'){ 
                    $status = '<a href="javascript:void(0)" data-id="'.$row->id.'" class="uk-label uk-label-success active">Active</a>';
                }else{
                    $status = '<a href="javascript:void(0)" data-id="'.$row->id.'" class="uk-label uk-label-danger inactive">Inactive</a>';
                }
                return $status;
            })
            ->addColumn('login', function($row){
                if(auth()->user()->user_type == 1){
                    return '<a class="uk-label uk-label-success" href="'.url('realtors/admin-login/'.Crypt::encrypt($row->id)).'">Login</a>';
                }else{
                    return  '';
                }
            })
            ->rawColumns(['actions','status', 'login'])->toJson();
        }
        else{
            $this->bladeContent['title']  = 'Realtors'; 
            $this->bladeContent['active'] = 'realtors';
            return view('admin.realtors.index',$this->bladeContent);
        }
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        $this->bladeContent['title']        = 'Add Realtor';
        $this->bladeContent['active']       = 'realtors';
        $this->bladeContent['realtorYears'] = RealtorYear::select('name')->where('status', 1)->orderBy('ordering', 'asc')->get();
        $this->bladeContent['languages']    = Language::select('name')->where('status', 1)->orderBy('ordering', 'asc')->get();
        return view ('admin.realtors.create', $this->bladeContent);
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
     public function store(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        
        $language = NULL;
        if(request('language')){
            $language = explode(', ',request('language'));
        }
        
        $realtor                          = new User();
        $realtor->name                    = request('name');
        $realtor->phone_number            = request('phone_number');
        $realtor->email                   = request('email');
        $realtor->address                 = request('address');
        $realtor->brokerage               = request('brokerage');
        $realtor->real_estate_association = request('real_estate_association');
        $realtor->awards                  = request('awards');
        $realtor->website                 = request('website');
        $realtor->realtor                 = request('realtor');
        $realtor->bio                     = request('bio');
        $realtor->sports_played           = request('sports_played');
        $realtor->interest_and_hobby      = request('interest_and_hobby');
        $realtor->years_with_brokerage    = request('years_with_brokerage');
        $realtor->realtor_year            = request('years_of_realtor');
        $realtor->password                = (request('password') ? Hash::make(request('password')) : '');
        $realtor->user_name               = 'Realtor_'.rand(100, 1000);
        $realtor->user_type               = 2;
        $realtor->language                = $language ? json_encode($language) : NULL;
        $realtor->other_language          = request('other_language');
        $realtor->save();

        if($request->hasFile('profile_pic')){
            $file    = $request->file('profile_pic');
            $newDir  = storage_path('profile_pictures/realtor/'.$realtor->id);
            if (!file_exists($newDir)) {
                mkdir($newDir, 0777, true);
            }
            $fileName = time() . "_" . str_replace(" ","_",$file->getClientOriginalName());
            $file->move(storage_path('profile_pictures/realtor/'.$realtor->id),$fileName);
            
            User::where('id', $realtor->id)->update([
                'profile_pic' => $fileName,
            ]);
        }
        

        $city      = request('city');
        $cityRange = request('city_range');
        
        foreach($cityRange as $key => $value){
            $cityRangeData             = new CityRange();
            $cityRangeData->user_id    = $realtor->id;
            $cityRangeData->city_name  = $city[$key];
            $cityRangeData->city_range = $value;
            $cityRangeData->save();
        }
        
        return redirect('admin/realtors')->with('success','Realtor successfully created.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        // $request->session()->put('name',$request->input('name'));
        // return view('task')->with('name',$request->session()->get('name'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        $realtor                            = User::where('id', $id)->first(); 
        $this->bladeContent['title']        = 'Edit Realtor';
        $this->bladeContent['active']       = 'realtors';
        $this->bladeContent['data']         =  $realtor;
        $this->bladeContent['realtorYears'] = RealtorYear::select('name')->where('status', 1)->orderBy('ordering', 'asc')->get();
        $this->bladeContent['languages']    = Language::select('name')->where('status', 1)->orderBy('ordering', 'asc')->get();
        $this->bladeContent['cityRanges']   = CityRange::where('user_id',$id)->orderBy('id', 'asc')->get();
        return view('admin.realtors.edit', $this->bladeContent);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        
        $language = NULL;
        if(request('language')){
            $language = explode(', ',request('language'));
        }
        
        $realtor                          = User::where('id', $id)->first();
        $realtor->name                    = request('name');
        $realtor->phone_number            = request('phone_number');
        $realtor->email                   = request('email');
        $realtor->address                 = request('address');
        $realtor->brokerage               = request('brokerage');
        $realtor->real_estate_association = request('real_estate_association');
        $realtor->awards                  = request('awards');
        $realtor->website                 = request('website');
        $realtor->realtor                 = request('realtor');
        $realtor->bio                     = request('bio');
        $realtor->sports_played           = request('sports_played');
        $realtor->interest_and_hobby      = request('interest_and_hobby');
        $realtor->years_with_brokerage    = request('years_with_brokerage');
        $realtor->realtor_year            = request('years_of_realtor');
        $realtor->language                = $language ? json_encode($language) : NULL;
        $realtor->other_language          = request('other_language');
        if($request->get('password')){
            $realtor->password   = Hash::make(request('password'));  
        }

        if($request->hasFile('profile_pic')){
            $file    = $request->file('profile_pic');
            $newDir  = storage_path('profile_pictures/realtor/'.$id);
            if (!file_exists($newDir)) {
                mkdir($newDir, 0777, true);
            }
            $fileName = time() . "_" . str_replace(" ","_",$file->getClientOriginalName());
            $file->move(storage_path('profile_pictures/realtor/'.$id),$fileName);
            $realtor->profile_pic = $fileName;
        }
        
        $realtor->save();
        
        $city      = request('city');
        $cityRange = request('city_range');
        $cityIds   = request('city_id');
        
        if($cityIds && is_array($cityIds)){
            CityRange::where('user_id', $realtor->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 = $realtor->id;
                }
                $cityRangeData->city_name  = $data;
                $cityRangeData->city_range = $cityRange[$key];
                $cityRangeData->save();
            }
        }
        
        return redirect()->back()->with('success','Realtor successfully updated.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Users  $users
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        User::where('id',$id)->delete();
        
        MessageThread::where('request_user_id', $id)->delete();
        MessageThread::where('realtor_user_id', $id)->delete();
        
        return response()->json([
            'success' => 1,
            'message' => 'Data successfully deleted.'
        ]);
    } 
    
    public function status(Request $request)
    {
        if(auth()->user()->user_type != 1){
            return redirect('/');
        }
        $id = request('id');
        if($request->type == 'active'){
            $value = '1';
        }else{
            $value = '0';
        }
       User::where('id', $id)->update(array('status' => $value));
        return response()->json([
        'success' => 1,
        'message' => 'status changed.'
      ]);
    } 
    
    public function removeProfile(Request $request){
     
        $userId         = request('id');
        
        $profilePic = User::where('id', $userId)->first();
        
        $fileName  = $profilePic->profile_pic;
        
        $path      = storage_path('profile_pictures/realtor/'.$userId.'/'.$profilePic->profile_pic);
        
        if(file_exists($path)){
            unlink($path);
        }
        
        User::where('id', $userId)->update([
            'profile_pic' => '',
        ]);
        
        return response()->json([
            'success'  => 1,
            'message' => 'Profile picture successfully removed',
        ]);
        

    }
    
    public function getCityCoordinates(Request $request)
    {
        $cityNames = $request->input('data');
        
        $apiKey = env('MAP_KEY');
        $coordinates = [];

        foreach ($cityNames as $city) {
            $cityName = $city['city'];
            $radius = $city['range'];
            $geocodeUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($cityName) . "&key=" . $apiKey;

            $response = json_decode(file_get_contents($geocodeUrl), true);

            if (!empty($response['results'])) {
                $location = $response['results'][0]['geometry']['location'];
                $coordinates[] = [
                    'city' => $cityName,
                    'range' => $radius,
                    'latitude' => $location['lat'],
                    'longitude' => $location['lng'],
                ];
            }
        }

        return response()->json($coordinates);
    }
    
    public function fetchNearbyPlaces(Request $request)
    {
        $lat = $request->input('lat');
        $lng = $request->input('lng');
        $radius = $request->input('radius');
        $apiKey = env('MAP_KEY');
        
        $nextPageToken = $request->input('nextPageToken');
        
        $params = [
            'location' => "$lat,$lng",
            'radius' => $radius,
            'key' => $apiKey,
        ];
        
        if ($nextPageToken) {
            $params['pagetoken'] = $nextPageToken;
        }

        $response = Http::get("https://maps.googleapis.com/maps/api/place/nearbysearch/json", $params);
        $data = $response->json();

        return response()->json([
            'results'       => $data['results'],
            'nextPageToken' => $data['next_page_token'] ?? null,
        ]);
    }
}