<?php

namespace App\Http\Controllers;

use App\Ad;
use App\Agency;
use App\Brand;
use App\Category;
use App\City;
use App\Country;
use App\Media;
use App\Payment;
use App\Report_ad;
use App\State;
use App\Sub_Category;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Visitors;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

use App\Service_provider;
use Mail;

use App\Ad_agent;


class AdsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    
     
    public function index()
    {
        $title = trans('app.all_ads');
        $ads = Ad::with('city', 'country', 'state')->whereStatus(1)->orderBy('id', 'desc')->paginate(20);
        return view('admin.all_ads', compact('title', 'ads'));
    }
    
    public function indexme(Request $request)
    {
        
        //return $request;
        
          $rules = [
            'first_name'    => 'required|email|unique:users',

            ];
            
            $this->validate($request, $rules);
        $data = [
                
                'agency_id'  => 10,
                'user_id'    =>  10,
                'first_name'    =>  $request->first_name,



            ];
         $agency_create = Agency::create($data);

        return $agency_create ;
    }
    
    
    
    public function caseylisting(Request $request){
        $ads = Ad::active();
        $premium_ads = Ad::activePremium();
        
        //primal coordinates
        function get_cods($ads, $request){
            $first_ad = $ads->first();
            //run if ads exist
            $lat = @$first_ad->latitude;
            $lng = @$first_ad->longitude;
            $res = false;
            $zoom = 13;
            $my_res = 'Total Listings Found For : <u>'. $request->q .'</u>' ;
            
            
            if($lat == null || $lng == null || $request->q == null || $request->q == 'zambia'){
                $lat = -15.2562546;
                $lng = 28.52351265;
                $zoom = 7;
                $res = true;
                $my_res = 'Smart search could not find listings  for <u> '. $request->q . '</u> Other Listings:';
                
            }
            if(isset($request->q)){
                   
            }else{
                 $my_res = null;
            }
            return $co_od = [
                'lat' => $lat,
                'lng' => $lng,
                'zoom' => $zoom,
                'res' => $res,
                'myres' => $my_res
                ];
        }
        
        //format string for indexing and search
        function format_string($data){
    
            //(1)combine string 
            $mydata = array();
            foreach($data as $thisdata){
                $mydata[] = $thisdata;
            }
            
            $mydata = implode(" ", $mydata);
            
            //(2)replace punctuation
            $mypuncs = array(':', ':', "'", '!', '.', ']', '[');
            foreach($mypuncs as $punc){
                $mydata = str_replace($punc, " ", $mydata);
            }
            
            //(3)replace apostrophe with nothing
            $mydata = str_replace("'", " ", $mydata);
            $mydata = str_replace("`", " ", $mydata);
            
            //(4)replace commas inbweeten numbers
            $mydata = preg_replace_callback("/(?P<nrs>[0-9]+,[0-9]+)/",
                                            function($matches){
                                                return str_replace("," , "" , $matches["nrs"]);
                                            } , 
                                            $mydata);
            
            //(5)replace commas with space
            $mydata = str_replace(",", " ", $mydata);
            
            //(6)correct spellings
            $mydata = explode(" ", $mydata);
            foreach($mydata as $thisdata){
                if(!is_numeric($thisdata)){
                    $thisdata = metaphone($thisdata);
                    $mysaves[] = $thisdata;
                    
                }
                else{
                    $mysaves[] = $thisdata;
                }
            }
            
            //return data as an array and string
            return $mydata = [
                        'data_array'  => $mysaves,
                        'data_string' => implode(" ", $mysaves),
                       ];
          }
        
        //handle request
        if ($request){
            $myreq = explode(" ", $request->q);
            $myreq = format_string($myreq);
            $myreq = $myreq['data_array'];
            $ads = $ads->where(function($ads) use($request, $myreq) {
            foreach ($myreq as $keyword) {
                $ads->where('keywords', 'like', "% {$keyword} %");
                }
            });
        }
        
        if ($request->type){
            $ads = $ads->whereType($request->type);
        }
        if ($request->country){
            $ads = $ads->whereCountryId($request->country);
        }
        if ($request->state){
            $ads = $ads->whereStateId($request->state);
        }
        if ($request->city){
            $ads = $ads->whereCityId($request->city);
        }
        if ($request->min_price){
            $ads = $ads->where('price', '>=', $request->min_price);
        }
        if ($request->max_price){
            $ads = $ads->where('price', '<=', $request->max_price);
        }
        if ($request->adType){
            if ($request->adType == 'business') {
                $ads = $ads->business();
            }elseif ($request->adType == 'personal'){
                $ads = $ads->personal();
            }
        }
        if ($request->user_id){
            $ads = $ads->whereUserId($request->user_id);
        }
        if ($request->shortBy){
            switch ($request->shortBy){
                case 'price_high_to_low':
                    $ads = $ads->orderBy('price', 'desc');
                    break;
                case 'price_low_to_height':
                    $ads = $ads->orderBy('price', 'asc');
                    break;
                case 'latest':
                    $ads = $ads->orderBy('id', 'desc');
                    break;
            }
        }else{
            $ads = $ads->orderBy('id', 'desc');
        }

        $ads_per_page = get_option('ads_per_page');
        $ads = $ads->with('city')->whereNotNull('latitude')->whereNotNull('longitude');
        $ads = $ads->paginate($ads_per_page);
        
        //coordinates
        $cods = get_cods($ads, $request);
        if($cods['res']){
            $ads = Ad::active();
            $ads = $ads->with('city')->whereNotNull('latitude')->whereNotNull('longitude');
            $ads = $ads->paginate($ads_per_page);
        }
        

        //Check max impressions
        $max_impressions = get_option('premium_ads_max_impressions');
        $premium_ads = $premium_ads->where('max_impression', '<', $max_impressions);
        $take_premium_ads = get_option('number_of_premium_ads_in_listing');
        if ($take_premium_ads > 0){
            $premium_order_by = get_option('order_by_premium_ads_in_listing');
            $premium_ads = $premium_ads->take($take_premium_ads);
            $last_days_premium_ads = get_option('number_of_last_days_premium_ads');

            $premium_ads = $premium_ads->where('created_at', '>=', Carbon::now()->timezone(get_option('default_timezone'))->subDays($last_days_premium_ads));

            if ($premium_order_by == 'latest'){
                $premium_ads = $premium_ads->orderBy('id', 'desc');
            }elseif ($premium_order_by == 'random'){
                $premium_ads = $premium_ads->orderByRaw('RAND()');
            }

            $premium_ads = $premium_ads->get();

        }else{
            $premium_ads = false;
        }
        
        $title = trans('app.search_properties');
        $countries = Country::all();

        $selected_categories = Category::find($request->category);
        $selected_sub_categories = Category::find($request->sub_category);

        $selected_countries = Country::find($request->country);
        $selected_states = State::find($request->state);
        //dd($selected_countries->states);
        
        $req = $request->q;
        

        $agents = User::whereActiveStatus('1')->whereFeature('1')->whereUserType('user')->take(10)->orderBy('id', 'desc')->get();
        session(['grid_list_view' => 'list']);
        return view($this->theme.'caseylisting', compact('top_categories', 'ads', 'title', 'countries', 'selected_categories', 'selected_sub_categories', 'selected_countries', 'selected_states', 'premium_ads', 'agents', 'cods', 'req'));
    }
    
    public function mapview(Request $request)
    {  
        function format_response($hold)
        {
            foreach($hold as $ad){
                    $holder[] = array(
                            'media_url'     => media_url($ad->feature_img),
                            'gallery_url'   => $ad->media_imgs,
                            'amenities'     => $ad->amenities,
                            'purpose'       => $ad->purpose,
                            'title'         => $ad->title,
                            'bedrooms'      => $ad->beds,
                            'type'          => $ad->type,
                            'description'   => $ad->description,
                            'bathrooms'     => $ad->common_bath,
                            'square_feet'   => $ad->square_unit_space,
                            'address'       => $ad->address,
                            'agent'         => $ad->agent,
                            'longitude'     => $ad ->longitude,
                            'latitude'      => $ad ->latitude,
                            'route'         => route('single_ad', $ad->slug),
                            'price'         => $ad->price,
                            'agency'        => $ad->agency,
                        );
                }
            return $holder;
         }
        
        //query database by coordinates
        if(isset($request->longitude) && isset($request->latitude)){
            //get variables
            $longitude = $request->longitude;
            $latitude  = $request->latitude;
            //check for a direct match
            $map_ads = Ad::wherelatitude('LIKE', $latitude)->wherelongitude('LIKE', $longitude)->whereStatus(1)->orderBy('id', 'desc')->paginate(20);
            
            //prepare for multi search
            $longitude = strval($longitude);
            $latitude  = strval($latitude);
            $longcount = strlen($longitude);
            $laticount = strlen($latitude);
            
            //set a base length
            if($longcount > $laticount){
                $length = $laticount;
            }else{
                $length = $longcount;
            }
            
            //query until property is found
            while(count($map_ads) < 4){
                //format coordinates
                $longitude = substr($longitude, 0, $length);
                $latitude = substr($latitude,  0, $length);
                $map_ads = Ad::wherelatitude(floatval($latitude))->wherelongitude(floatval($longitude))->whereStatus(1)->orderBy('id', 'desc')->paginate(20);
                --$length;
                if($length == 4){
                    break ;
                }else{
                    return format_response($map_ads);
                }
            }
        }
        //error handling
        else if(isset($request->longitude)){
            $response = ['error' => 'You have not supplied a latitude or  format you provided is invalid if both the longitude and latitude/latu has been provided then follow the following format \'longitude=15.3235245141254&latitude=-5.235258122536251525\' the order in which the longitude and latitude does not matter as long as/latu the names are lowercase and have the same number of digits'];
        }else if(isset($request->latitude)){
            $response = ['error' => 'You have not supplied a longitude or format you provided is invalid if both the longitude and latitude/latu has been provided then follow the following format \'longitude=15.3235245141254&latitude=-5.235258122536251525\' the order in which the longitude and latitude does not matter as long as/latu the names are lowercase and have the same number of digits'];
        }
        else{
            
            //query database by city
            if(isset($request->city)){
                $city = City::where('city_name', 'LIKE', $request->city)->first();
                if(count($city) == 0){
                    return $response = [
                        'response' => [
                            'error'=> 'city does not exist in database please try another city or add city to database',
                            'solutions' => [ 
                                '1' => 'spell the city correctly ( not case sensitive!)',
                                '2' => 'use the city\'s formal name no ISO CODES, Abbreviations or colloqual names eg, Johannesburg not Joburg or Jozi!)',
                                '3' => 'use the spaces or a dash _ to separate the city names for those cities that have multiple names eg, los_angeles or los angeles not losangeles'
                               ]
                            ],
                        'city'=> $request->city,
                        'request'=> $request,
                        ];
                }
                $ads = Ad::whereCityId($city->id)->orderBy('id', 'desc')->paginate(100);
                if(count($ads) == 0){
                    $response = [
                        'response' => 'no ads in your requested city',
                        'city'=> $city,
                        'request'=> $request,
                        ];
                    }
                else{
                   }
                           
                }
                
            }
        $response = Ad::whereStatus(1)->orderBy('id', 'desc')->paginate(100);
        
        return format_response($response);
    }

    public function adminPendingAds()
    {
        $title = trans('app.pending_ads');
        $ads = Ad::with('city', 'country', 'state')->whereStatus(0)->orderBy('id', 'desc')->paginate(20);

        return view('admin.all_ads', compact('title', 'ads'));
    }
    public function adminBlockedAds()
    {
        $title = trans('app.blocked_ads');
        $ads = Ad::with('city', 'country', 'state')->whereStatus(2)->orderBy('id', 'desc')->paginate(20);
        return view('admin.all_ads', compact('title', 'ads'));
    }
    
    public function myAds(){
        $title = trans('app.my_ads');

        $user = Auth::user();
        
        $ads = $user->ads()->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);
        
        return view('admin.my_ads', compact('title', 'ads' ,'user'));
    }
    
      public function agencyAds(){
        $title = trans('app.my_ads');
        $user = Auth::user();
        $num = $user->id;
        $ads = Ad::where('agency', '=',$num)->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);
        return view('admin.my_ads', compact('title', 'ads','user'));
    }
    
     public function pendingagencyAds(){
        $title = trans('User Pending');
        $user = Auth::user();
        $num = $user->id;
        $ads = Ad::where('agency', '=',$num)->whereStatus(0)->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);

        return view('admin.pending_ads', compact('title', 'ads'));
    }
    
    public function userads(){
        $title = trans('Represented Posts');

        $user = Auth::user();
        $ads = Ad::where('customer_id', '!=', $user->id)->where('user_id', $user->id)->whereStatus(1)->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);
        
        return view('admin.user_ads', compact('title', 'ads'));
    }

    public function pendingAds(){
        $title = trans('User Pending');

        $user = Auth::user();
        $ads = $user->ads()->whereStatus(0)->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);

        return view('admin.pending_ads', compact('title', 'ads'));
    }
    
    public function userpend(){
        $title = trans('User Ads');

        $user = Auth::user();
        $ads = Ad::where('customer_id', '!=', $user->id)->where('user_id', $user->id)->whereStatus(0)->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);

        return view('admin.user_pend', compact('title', 'ads'));
    }
    
    public function userblocked(){
        $title = trans('Orphan Posts');

        $user = Auth::user();
        $ads = Ad::where('customer_id', '!=', $user->id)->where('user_id', 0)->whereStatus(0)->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);

        return view('admin.user_pend', compact('title', 'ads'));
    }
    
    public function favoriteAds(){
        $title = trans('app.favourite_ads');

        $user = Auth::user();
        $ads = $user->favourite_ads()->with('city', 'country', 'state')->orderBy('id', 'desc')->paginate(20);
        
        return view('admin.favourite_ads', compact('title', 'ads'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = Auth::user();
        
        if($user->phone == NULL){
                return redirect()->route('profile_edit')->with('missing_mobile', "Please Enter your Phone Number Before you can post an Ad");
        }
        
        $user_id = $user->id;
        $title = trans('app.post_an_ad');
        $categories = Category::all();
        $distances = Brand::all();
        $countries = Country::all();
        $ads_images = Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->get();
        
        $previous_states = State::where('country_id', old('country'))->get();
        $previous_cities = City::where('state_id', old('state'))->get();


        return view('admin.create_ad', compact('title', 'categories', 'countries', 'ads_images', 'distances', 'previous_states', 'previous_cities'));
    }
    
      public function createad()
    {
        $user_id = Auth::user()->id;
        $agn_id = Auth::user()-> agent_id;

        $title = trans('app.post_an_ad');
        $categories = Category::all();
        $distances = Brand::all();
        $countries = Country::all();
        $ads_images = Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->get();
        $previous_states = State::where('country_id', old('country'))->get();
        $previous_cities = City::where('state_id', old('state'))->get();
        $num = $user_id;
        $users =  User::select('id','name', 'user_name', 'email', 'phone')->where('agency_id', '=',$num)->where('active_status', '=','1')->orderBy('id', 'desc')->get();
        $admin =  User::select('id','name', 'user_name', 'email', 'phone')->where('id', '=',$agn_id)->where('active_status', '=','1')->orderBy('id', 'desc')->get();

        //return $users;
        return view('admin.create_agency_ad', compact('title','admin', 'categories', 'countries', 'ads_images', 'distances', 'previous_states', 'previous_cities','users'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    
    //store the ad into the database
    public function store(Request $request)
    {
        
        //return $request;
         //format string for indexing and search
         
         //return $request;
         function format_string($data, $city){

            //(1)combine string 
            $mydata = array();
            $mydata[] = $city;
            foreach($data as $thisdata){
                $mydata[] = $thisdata;
            }
            $mydata = implode(" ", $mydata);
            
            //(2)replace punctuation
            $mypuncs = array(':', ';', "'", '!', '.', '"');
            foreach($mypuncs as $punc){
                $mydata = str_replace($punc, " ", $mydata);
            }
            
            //(3)replace apostrophe with nothing
            $mydata = str_replace("'", " ", $mydata);
            $mydata = str_replace("`", " ", $mydata);
            
            //(4)replace commas inbweeten numbers
            $mydata = preg_replace_callback("/(?P<nrs>[0-9]+,[0-9]+)/",
                                            function($matches){
                                                return str_replace("," , "" , $matches["nrs"]);
                                            } , 
                                            $mydata);
            
            //(5)replace commas with space
            $mydata = str_replace(",", " ", $mydata);
            
            //(6)correct spellings
            $mydata = explode(" ", $mydata);
            foreach($mydata as $thisdata){
                if(!is_numeric($thisdata)){
                    $thisdata = metaphone($thisdata);
                    $mysaves[] = $thisdata;
                    
                }
                else{
                    $mysaves[] = $thisdata;
                }
            }
            //return data as an array and string
            return $mydata = [
                        'data_array'  => $mysaves,
                        'data_string' => implode(" ", $mysaves),
                       ];
          }
            
            
        $user = Auth::user();
        $user_id = $user->id;
        $ads_price_plan = get_option('ads_price_plan');
        $mydata = array();

        if($user->user_type == 'customer'){
            $rules = [
            'ad_title'  => 'required',
            'ad_description'  => 'required',
            'type'  => 'required',
            'purpose'  => 'required',
            'city'  => 'required',
            ];
        }
        else{
            $rules = [
            'ad_title'  => 'required',
            'ad_description'  => 'required',
            'type'  => 'required',
            'purpose'  => 'required',
            'city'  => 'required',
            'seller_name'  => 'required',
            'seller_email'  => 'required',
            'seller_phone'  => 'required',
        ];
        }

        if( $ads_price_plan != 'all_ads_free'){
            $rules['price_plan'] = 'required';
        }

        $this->validate($request, $rules);

        $title = $request->ad_title;
        $slug = unique_slug($title);

        $is_negotialble = $request->negotiable ? $request->negotiable : 0;
        $mark_ad_urgent = $request->mark_ad_urgent ? $request->mark_ad_urgent : 0;
        $video_url = $request->video_url ? $request->video_url : '';

        $amenities = serialize($request->amenities);
        $distances = serialize($request->distances);
        $city = City::whereId($request->city)->get();
        $city = json_encode($city);
        
         if($user->user_type == 'customer'){
             if( $request->rep_agent == 'allow'){
                    $data = [
                        'title'         => $request->ad_title,
                        'slug'          => $slug,
                        'description'   => $request->ad_description,
                        'type'          => $request->type,
                        'price'         => $request->price,
                        'currency_type' => $request->currency_type,
                        'is_negotiable' => $is_negotialble,
                        'address' => $request->ad_address,

            
                        'purpose'       => $request->purpose,
                        'price_per_unit'       => $request->price_per_unit,
                        'unit_type'       => $request->price_unit,
                        'square_unit_space'       => $request->square_unit_space,
                        'floor'       => $request->floor,
                        'beds'       => $request->beds,
                        'attached_bath'       => $request->attached_bath,
                        'common_bath'       => $request->common_bath,
                        'balcony'       => $request->balcony,
                        'dining_space'       => $request->dining_space,
                        'living_room'       => $request->living_room,
                        'amenities'       => $amenities,
                        'distances'       => $distances,
                        'country_id'    => $request->country,
                        'state_id'      => $request->state,
                        'city_id'       => $request->city,
                        //'address'       => $request->address,
            
                        'latitude'       => $request->latitude,
                        'longitude'       => $request->longitude,
            
                        'video_url'     => $video_url,
                        'price_plan'    => $request->price_plan,
                        'mark_ad_urgent' => $mark_ad_urgent,
                        'status'        => 0,
                        'keywords'      => "puppies",
                        // 'user_id'       => 0,
                        'user_id'       => $user->id,
                        'customer_id'   => $user->id,
                        'seller_name'   => $user->name,
                        'seller_email'  => $user->email,
                        'seller_phone'  => $user->phone,
                    ];
            }
             else {
                 
                $rep_agent = User::select('id')->whereId($request->rep_agent);
                
                $data = [
                    'title'         => $request->ad_title,
                    'slug'          => $slug,
                    'description'   => $request->ad_description,
                    'type'          => $request->type,
                    'price'         => $request->price,
                    'currency_type' => $request->currency_type,
                    'is_negotiable' => $is_negotialble,
                    'address' => $request->ad_address,

        
                    'purpose'       => $request->purpose,
                    'price_per_unit'       => $request->price_per_unit,
                    'unit_type'       => $request->price_unit,
                    'square_unit_space'       => $request->square_unit_space,
                    'floor'       => $request->floor,
                    'beds'       => $request->beds,
                    'attached_bath'       => $request->attached_bath,
                    'common_bath'       => $request->common_bath,
                    'balcony'       => $request->balcony,
                    'dining_space'       => $request->dining_space,
                    'living_room'       => $request->living_room,
                    'amenities'       => $amenities,
                    'distances'       => $distances,
        
                    'seller_name'   => $user->name,
                    'seller_email'  => $user->email,
                    'seller_phone'  => $user->phone,
                    'country_id'    => $request->country,
                    'state_id'      => $request->state,
                    'city_id'       => $request->city,
                    //'address'       => $request->address,
        
                    'latitude'       => $request->latitude,
                    'longitude'       => $request->longitude,
        
                    'video_url'     => $video_url,
                    'price_plan'    => $request->price_plan,
                    'mark_ad_urgent' => $mark_ad_urgent,
                    'status'        => 0,
                    'user_id'       => $user->id,
                    // 'user_id'       => $rep_agent->id, // supposed to be representative agent
                    'keywords'      => null,
                    'seller_name'   => $user->name,
                    'seller_email'  => $user->email,
                    'seller_phone'  => $user->phone,
                ];
                         
             }
             
        }
        else if( $user->user_type == 'agent'){
            $data = [
            'title'         => $request->ad_title,
            'slug'          => $slug,
            'description'   => $request->ad_description,
            'type'          => $request->type,
            'price'         => $request->price,
            'currency_type' => $request->currency_type,
            'is_negotiable' => $is_negotialble,
            'address' => $request->ad_address,
            'purpose'       => $request->purpose,
            'price_per_unit'       => $request->price_per_unit,
            'unit_type'       => $request->price_unit,
            'square_unit_space'       => $request->square_unit_space,
            'floor'       => $request->floor,
            'beds'       => $request->beds,
            'attached_bath'       => $request->attached_bath,
            'common_bath'       => $request->common_bath,
            'balcony'       => $request->balcony,
            'dining_space'       => $request->dining_space,
            'living_room'       => $request->living_room,
            'amenities'       => $amenities,
            'distances'       => $distances,
            'agency'                => $user->agency_id,
            'seller_name'   => $user->name,
            'seller_email'  => $user->email,
            'seller_phone'  => $user->phone,
            'country_id'    => $request->country,
            'state_id'      => $request->state,
            'city_id'       => $request->city,
            //'address'       => $user->address,
            'keywords'      => "puppies",
            'latitude'       => $request->latitude,
            'longitude'       => $request->longitude,

            'video_url'     => $video_url,
            'price_plan'    => $request->price_plan,
            'mark_ad_urgent' => $mark_ad_urgent,
            'status'        => 0,
            'user_id'       => $user_id,
            // 'keywords'      => null,
        ];
            
        }
        
                else{
            $data = [
            'title'         => $request->ad_title,
            'slug'          => $slug,
            'description'   => $request->ad_description,
            'type'          => $request->type,
            'price'         => $request->price,
            'currency_type' => $request->currency_type,
            'is_negotiable' => $is_negotialble,
            'address' => $request->ad_address,
            'purpose'       => $request->purpose,
            'price_per_unit'       => $request->price_per_unit,
            'unit_type'       => $request->price_unit,
            'square_unit_space'       => $request->square_unit_space,
            'floor'       => $request->floor,
            'beds'       => $request->beds,
            'attached_bath'       => $request->attached_bath,
            'common_bath'       => $request->common_bath,
            'balcony'       => $request->balcony,
            'dining_space'       => $request->dining_space,
            'living_room'       => $request->living_room,
            'amenities'       => $amenities,
            'distances'       => $distances,
            //'agency'                => $user->agency_id,
            'seller_name'   => $request->seller_name,
            'seller_email'  => $request->seller_email,
            'seller_phone'  => $request->seller_phone,
            'country_id'    => $request->country,
            'state_id'      => $request->state,
            'city_id'       => $request->city,
            //'address'       => $user->address,

            'latitude'       => $request->latitude,
            'longitude'       => $request->longitude,

            'video_url'     => $video_url,
            'price_plan'    => $request->price_plan,
            'mark_ad_urgent' => $mark_ad_urgent,
            'status'        => 0,
            'user_id'       => $user_id,
            'keywords'      => "puppies",
        ];
            
        }

        //create index with format_string()
        $mydata = format_string($data, $city);
        $data['keywords'] = $mydata['data_string'];
    //   $data['keywords'] = "puppies";

        //Check ads moderation settings
        if (get_option('ads_moderation') == 'direct_publish'){
            $data['status'] = 1;
        }

        //if price_plan not in post data, then set a default value, although mysql will save it as enum first value
        if ( ! $request->price_plan){
            $data['price_plan'] = 'regular';
        }
        
               // return  $data;

    
        $created_ad = Ad::create($data);
        // Send email to admins when property has been uploaded
        $admin_users = User::where('user_type','=', 'admin')->get();
        
        foreach($admin_users as $admin_user){
            $email_data = (object)['email'=>$admin_user->email]; //email object used to get data inside the closure function 
            $email_content = ['sample_data'=>'sample_data']; //not used but is used to insert variables into the email
    
            Mail::send('emails.property_upload', $email_content, function ($m) use ($email_data) {
                $m->from('website@kupeza.co.zm', 'Kupeza');
    
                $m->to($email_data->email, "Kupeza Admin")->subject('A User Uploaded A property');
            });
        }
        

        /**
         * iF add created
         */
        if ($created_ad){
            //Attach all unused media with this ad
            Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->update(['ad_id'=>$created_ad->id]);
            
            /**
             * Payment transaction login here
             */
            $ads_price = get_ads_price($created_ad->price_plan);
            if ($mark_ad_urgent){
                $ads_price = $ads_price + get_option('urgent_ads_price');
            }

            if ($ads_price){
                //Insert checkout Logic

                $transaction_id = 'tran_'.time().str_random(6);
                // get unique recharge transaction id
                while( ( Payment::whereLocalTransactionId($transaction_id)->count() ) > 0) {
                    $transaction_id = 'reid'.time().str_random(5);
                }
                $transaction_id = strtoupper($transaction_id);

                $currency = get_option('currency_sign');
                $payments_data = [
                    'ad_id'     => $created_ad->id,
                    'user_id'   => $user_id,
                    'amount'    => $ads_price,
                    'payment_method'    => $request->payment_method,
                    'status'    => 'initial',
                    'currency'  => $currency,
                    'local_transaction_id'  => $transaction_id
                ];
                $created_payment = Payment::create($payments_data);

                return redirect(route('payment_checkout', $created_payment->local_transaction_id));
            }
            
            

            return redirect(route('pending_ads'))->with('success', trans('app.ad_created_msg'));

        }
        

        //dd($request->input());
    }
    
        public function agencystore(Request $request)
    {
         //format string for indexing and search
         
        // return $request;
         function format_string($data, $city){

            //(1)combine string 
            $mydata = array();
            $mydata[] = $city;
            foreach($data as $thisdata){
                $mydata[] = $thisdata;
            }
            $mydata = implode(" ", $mydata);
            
            //(2)replace punctuation
            $mypuncs = array(':', ';', "'", '!', '.', '"');
            foreach($mypuncs as $punc){
                $mydata = str_replace($punc, " ", $mydata);
            }
            
            //(3)replace apostrophe with nothing
            $mydata = str_replace("'", " ", $mydata);
            $mydata = str_replace("`", " ", $mydata);
            
            //(4)replace commas inbweeten numbers
            $mydata = preg_replace_callback("/(?P<nrs>[0-9]+,[0-9]+)/",
                                            function($matches){
                                                return str_replace("," , "" , $matches["nrs"]);
                                            } , 
                                            $mydata);
            
            //(5)replace commas with space
            $mydata = str_replace(",", " ", $mydata);
            
            //(6)correct spellings
            $mydata = explode(" ", $mydata);
            foreach($mydata as $thisdata){
                if(!is_numeric($thisdata)){
                    $thisdata = metaphone($thisdata);
                    $mysaves[] = $thisdata;
                    
                }
                else{
                    $mysaves[] = $thisdata;
                }
            }
            //return data as an array and string
            return $mydata = [
                        'data_array'  => $mysaves,
                        'data_string' => implode(" ", $mysaves),
                       ];
          }
            
            
        $user = Auth::user();
        $user_id = $user->id;
        $ads_price_plan = get_option('ads_price_plan');
        $mydata = array();

        
            $rules = [
            'ad_title'  => 'required',
            'ad_description'  => 'required',
            'type'  => 'required',
            'purpose'  => 'required',
            'city'  => 'required',
            'seller_name'  => 'required',
            'seller_email'  => 'required',
            'seller_phone'  => 'required',
        ];
        //}

        if( $ads_price_plan != 'all_ads_free'){
            $rules['price_plan'] = 'required';
        }

        $this->validate($request, $rules);

        $title = $request->ad_title;
        $slug = unique_slug($title);

        $is_negotialble = $request->negotiable ? $request->negotiable : 0;
        $mark_ad_urgent = $request->mark_ad_urgent ? $request->mark_ad_urgent : 0;
        $video_url = $request->video_url ? $request->video_url : '';

        $amenities = serialize($request->amenities);
        $distances = serialize($request->distances);
        $city = City::whereId($request->city)->get();
        $city = json_encode($city);
        
        $useridp = User::select('id')->where('email', '=',$request->seller_email)->get();
 
        //return $useridp[0]->id;

              //  else{
            $data = [
            'title'         => $request->ad_title,
            'slug'          => $slug,
            'description'   => $request->ad_description,
            'type'          => $request->type,
            'price'         => $request->price,
            'is_negotiable' => $is_negotialble,
            'address' => $request->ad_address,
            'purpose'       => $request->purpose,
            'price_per_unit'       => $request->price_per_unit,
            'unit_type'       => $request->price_unit,
            'square_unit_space'       => $request->square_unit_space,
            'floor'       => $request->floor,
            'beds'       => $request->beds,
            'attached_bath'       => $request->attached_bath,
            'common_bath'       => $request->common_bath,
            'balcony'       => $request->balcony,
            'dining_space'       => $request->dining_space,
            'living_room'       => $request->living_room,
            'amenities'       => $amenities,
            'distances'       => $distances,
            //'agency'                => $user->agency_id,
            'seller_name'   => $request->seller_name,
            'seller_email'  => $request->seller_email,
            'seller_phone'  => $request->seller_phone,
            'country_id'    => $request->country,
            'state_id'      => $request->state,
            'city_id'       => $request->city,
            'agency'                => $user->id,

            //'address'       => $user->address,

            'latitude'       => $request->latitude,
            'longitude'       => $request->longitude,

            'video_url'     => $video_url,
            'price_plan'    => $request->price_plan,
            'mark_ad_urgent' => $mark_ad_urgent,
            'status'        => 0,
            'user_id'       => $useridp[0]->id,
            'keywords'      => null,
        ];
            
      //  }

        //create index with format_string()
        $mydata = format_string($data, $city);
        $data['keywords'] = $mydata['data_string'];
       

        //Check ads moderation settings
        if (get_option('ads_moderation') == 'direct_publish'){
            $data['status'] = 1;
        }

        //if price_plan not in post data, then set a default value, although mysql will save it as enum first value
        if ( ! $request->price_plan){
            $data['price_plan'] = 'regular';
        }
        
               // return  $data;

    
        $created_ad = Ad::create($data);
        
        

        /**
         * iF add created
         */
        if ($created_ad){
            //Attach all unused media with this ad
            Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->update(['ad_id'=>$created_ad->id]);
            
            /**
             * Payment transaction login here
             */
            $ads_price = get_ads_price($created_ad->price_plan);
            if ($mark_ad_urgent){
                $ads_price = $ads_price + get_option('urgent_ads_price');
            }

            if ($ads_price){
                //Insert checkout Logic

                $transaction_id = 'tran_'.time().str_random(6);
                // get unique recharge transaction id
                while( ( Payment::whereLocalTransactionId($transaction_id)->count() ) > 0) {
                    $transaction_id = 'reid'.time().str_random(5);
                }
                $transaction_id = strtoupper($transaction_id);

                $currency = get_option('currency_sign');
                $payments_data = [
                    'ad_id'     => $created_ad->id,
                    'user_id'   => $user_id,
                    'amount'    => $ads_price,
                    'payment_method'    => $request->payment_method,
                    'status'    => 'initial',
                    'currency'  => $currency,
                    'local_transaction_id'  => $transaction_id
                ];
                $created_payment = Payment::create($payments_data);

                return redirect(route('payment_checkout', $created_payment->local_transaction_id));
            }

            return redirect(route('pending_ads'))->with('success', trans('app.ad_created_msg'));

        }
        

        //dd($request->input());
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
     
    public function edit($id)
    {
        $user = Auth::user();
        $user_id = $user->id;

        $title = trans('app.edit_ad');
        $ad = Ad::find($id);
        
        //return $ad->address;

        $countries = Country::all();
        $ads_images = Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->get();

        $previous_states = State::where('country_id', $ad->country_id)->get();
        $previous_cities = City::where('state_id', $ad->state_id)->get();

        $categories = Category::all();
        $distances = Brand::all();
        
        //return $ad ;

        return view('admin.edit_ad', compact('title', 'categories', 'countries', 'ads_images', 'ad', 'distances', 'previous_states', 'previous_cities'));

    }
    
      public function editagprop($id)
    {
        $user = Auth::user();
        $user_id = $user->id;

        $title = trans('app.edit_ad');
        $ad = Ad::find($id);
        
        //return $ad->address;

        $countries = Country::all();
        $ads_images = Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->get();

        $previous_states = State::where('country_id', $ad->country_id)->get();
        $previous_cities = City::where('state_id', $ad->state_id)->get();

        $categories = Category::all();
        $distances = Brand::all();
        $agn_id = $ad-> user_id;
        $num = $ad->agency;
        $users =  User::select('id','name', 'user_name', 'email', 'phone')->where('agency_id', '=',$num)->where('active_status', '=','1')->orderBy('id', 'desc')->get();
        $admin =  User::select('id','name', 'user_name', 'email', 'phone')->where('id', '=',$agn_id)->where('active_status', '=','1')->orderBy('id', 'desc')->get();
        //return $ad;

        return view('admin.agency_edit_ad', compact('title', 'users','admin','categories', 'countries', 'ads_images', 'ad', 'distances', 'previous_states', 'previous_cities'));

    }
    
    public function agencyupdate(Request $request, $id)
    
    
    {
        

        $ad = Ad::find($id);
        $user = Auth::user();
        $user_id = $user->id;

        //if (! $user->is_admin()){
        //    if ($user->user_type != 'agent'){
        //        return view('admin.error.error_404');
         //   }
        //}
        $mark_ad_urgent = $request->mark_ad_urgent ? $request->mark_ad_urgent : 0;

        $rules = [
            'ad_title'  => 'required',
            'ad_description'  => 'required',
            'type'  => 'required',
            'purpose'  => 'required',
            'country'  => 'required',
            'seller_name'  => 'required',
            'seller_email'  => 'required',
            'seller_phone'  => 'required',
            //'address'  => 'required',
            'latitude'  => 'required',
            'longitude'  => 'required',
        ];

        $this->validate($request, $rules);

        $title = $request->ad_title;
        

        //$slug = unique_slug($title);
        
        $sub_category = Category::find($request->category);
        $is_negotialble = $request->negotiable ? $request->negotiable : 0;
        $brand_id = $request->brand ? $request->brand : 0;
        $video_url = $request->video_url ? $request->video_url : '';

        $amenities = serialize($request->amenities);
        $distances = serialize($request->distances);
        $useridp = User::select('id')->where('email', '=',$request->seller_email)->get();
        //return $useridp;


        $data = [
            'title'         => $request->ad_title,
            'description'   => $request->ad_description,
            'type'          => $request->type,
            'price'         => $request->price,
            'is_negotiable' => $is_negotialble,
            'purpose'       => $request->purpose,
            'price_per_unit'       => $request->price_per_unit,
            'unit_type'       => $request->price_unit,
            'square_unit_space'       => $request->square_unit_space,
            'floor'       => $request->floor,
            'beds'       => $request->beds,
            'attached_bath'       => $request->attached_bath,
            'common_bath'       => $request->common_bath,
            'balcony'       => $request->balcony,
            'dining_space'       => $request->dining_space,
            'living_room'       => $request->living_room,
            'amenities'       => $amenities,
            'distances'       => $distances,

            'seller_name' => $request->seller_name,
            'seller_email' => $request->seller_email,
            'seller_phone' => $request->seller_phone,
            'country_id' => $request->country,
            'state_id' => $request->state,
            'city_id' => $request->city,
            'address' => $request->ad_address,

            'latitude'       => $request->latitude,
            'longitude'       => $request->longitude,
            'user_id' => $useridp[0]->id,

            'video_url' => $video_url,
            //'mark_ad_urgent' => $mark_ad_urgent,

        ];
        
                             //return $data;

        
        
        $updated_ad = $ad->update($data);

        /**
         * iF add created
         */
        if ($updated_ad){
            //Attach all unused media with this ad
            Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->update(['ad_id'=>$ad->id]);
            
                    return redirect()->back()->with('success', trans('app.ad_updated'));

        }
        else {

        return redirect()->back()->with('failed', trans('app.ad_updated'));   }
    }
    
    public function myedit($id)
    {
        $user = Auth::user();
        $user_id = $user->id;

        $title = trans('app.edit_ad');
        $ad = Ad::find($id);

        if (!$ad)
            return view('admin.error.error_404');

        if (! $user->is_admin()){
            if ($ad->user_id != $user_id){
                return view('admin.error.error_404');
            }
        }

        $countries = Country::all();
        $ads_images = Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->get();

        $previous_states = State::where('country_id', $ad->country_id)->get();
        $previous_cities = City::where('state_id', $ad->state_id)->get();

        $categories = Category::all();
        $distances = Brand::all();

        return view('admin.edit_ad', compact('title', 'categories', 'countries', 'ads_images', 'ad', 'distances', 'previous_states', 'previous_cities'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    
    
    {
        

        $ad = Ad::find($id);
        $user = Auth::user();
        $user_id = $user->id;

        //if (! $user->is_admin()){
        //    if ($user->user_type != 'agent'){
        //        return view('admin.error.error_404');
         //   }
        //}
        $mark_ad_urgent = $request->mark_ad_urgent ? $request->mark_ad_urgent : 0;

        $rules = [
            'ad_title'  => 'required',
            'ad_description'  => 'required',
            'type'  => 'required',
            'purpose'  => 'required',
            'country'  => 'required',
            'seller_name'  => 'required',
            'seller_email'  => 'required',
            'seller_phone'  => 'required',
            //'address'  => 'required',
            'latitude'  => 'required',
            'longitude'  => 'required',
        ];

        $this->validate($request, $rules);

        $title = $request->ad_title;
        

        //$slug = unique_slug($title);
        
        $sub_category = Category::find($request->category);
        $is_negotialble = $request->negotiable ? $request->negotiable : 0;
        $brand_id = $request->brand ? $request->brand : 0;
        $video_url = $request->video_url ? $request->video_url : '';

        $amenities = serialize($request->amenities);
        $distances = serialize($request->distances);

        $data = [
            'title'         => $request->ad_title,
            'description'   => $request->ad_description,
            'type'          => $request->type,
            'currency_type' => $request->currency_type,
            'price'         => $request->price,
            'is_negotiable' => $is_negotialble,
            'purpose'       => $request->purpose,
            'price_per_unit'       => $request->price_per_unit,
            'unit_type'       => $request->price_unit,
            'square_unit_space'       => $request->square_unit_space,
            'floor'       => $request->floor,
            'beds'       => $request->beds,
            'attached_bath'       => $request->attached_bath,
            'common_bath'       => $request->common_bath,
            'balcony'       => $request->balcony,
            'dining_space'       => $request->dining_space,
            'living_room'       => $request->living_room,
            'amenities'       => $amenities,
            'distances'       => $distances,

            'seller_name' => $request->seller_name,
            'seller_email' => $request->seller_email,
            'seller_phone' => $request->seller_phone,
            'country_id' => $request->country,
            'state_id' => $request->state,
            'city_id' => $request->city,
            'address' => $request->ad_address,

            'latitude'       => $request->latitude,
            'longitude'       => $request->longitude,
            'user_id' => $user->id,

            'video_url' => $video_url,
            //'mark_ad_urgent' => $mark_ad_urgent,

        ];
        
                             //return $data;

        
        
        $updated_ad = $ad->update($data);

        /**
         * iF add created
         */
        if ($updated_ad){
            //Attach all unused media with this ad
            Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->update(['ad_id'=>$ad->id]);
            
                    return redirect()->back()->with('success', trans('app.ad_updated'));

        }
        else {

        return redirect()->back()->with('failed', trans('app.ad_updated'));   }
    }


    public function adStatusChange(Request $request){
        $slug = $request->slug;
        $ad = Ad::whereSlug($slug)->first();
        if ($ad){
            $value = $request->value;
            /*
            $ad->status = $value;
            $ad->save();*/
            $user = User::find($ad->user_id);
                
            $email_data = (object)['email'=>$user->email, 'name'=>$user->name];
            
            ad_status_change($ad->id, $value);
            if ($value ==1){
                
                $email_content = ['ad_title'=>$ad->title, 'status_change'=>"approved", 'name'=>$user->name];
        
                Mail::send('emails.status_change', $email_content, function ($m) use ($email_data) {
                    $m->from('respond@kupeza.co.zm', 'Kupeza Website');
        
                    $m->to($email_data->email, $email_data->name)->subject('Your Ad on Kupeza Has Been Approved');
                });
                
                return ['success'=>1, 'msg' => trans('app.ad_approved_msg')];
            }elseif($value ==2){
                
                $email_content = ['ad_title'=>$ad->title, 'status_change'=>"blocked", 'name'=>$user->name];
        
                Mail::send('emails.status_change', $email_content, function ($m) use ($email_data) {
                    $m->from('respond@kupeza.co.zm', 'Kupeza Website');
        
                    $m->to($email_data->email, $email_data->name)->subject('Your Ad on Kupeza Has Been Blocked');
                });
                
                return ['success'=>1, 'msg' => trans('app.ad_blocked_msg')];
            }
            elseif($value ==3){
                
                $email_content = ['ad_title'=>$ad->title, 'status_change'=>"archived", 'name'=>$user->name];
        
                Mail::send('emails.status_change', $email_content, function ($m) use ($email_data) {
                    $m->from('respond@kupeza.co.zm', 'Kupeza Website');
        
                    $m->to($email_data->email, $email_data->name)->subject('Your Ad on Kupeza Has Been Archived');
                });
                
                return ['success'=>1, 'msg' => trans('app.ad_archived_msg')];
            }
        }
        
        return ['success'=>0, 'msg' => trans('app.error_msg')];

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $slug = $request->slug;
        $ad = Ad::whereSlug($slug)->first();
        if ($ad){
            $media = Media::whereAdId($ad->id)->get();
            if ($media->count() > 0){
                foreach($media as $m){
                    $storage = Storage::disk($m->storage);
                    if ($storage->has('uploads/images/'.$m->media_name)){
                        $storage->delete('uploads/images/'.$m->media_name);
                    }
                    if ($m->type == 'image'){
                        if ($storage->has('uploads/images/thumbs/'.$m->media_name)){
                            $storage->delete('uploads/images/thumbs/'.$m->media_name);
                        }
                    }
                    $m->delete();
                }
            }
            $ad->delete();
            return ['success'=>1, 'msg' => trans('app.media_deleted_msg')];
        }
        return ['success'=>0, 'msg' => trans('app.error_msg')];
    }

    public function getSubCategoryByCategory(Request $request){
        $category_id = $request->category_id;
        $brands = Sub_Category::whereCategoryId($category_id)->select('id', 'category_name', 'category_slug')->get();
        return $brands;
    }

    public function getBrandByCategory(Request $request){
        $category_id = $request->category_id;
        $brands = Brand::whereCategoryId($category_id)->select('id', 'brand_name')->get();
        return $brands;
    }

    public function getStateByCountry(Request $request){
        $country_id = $request->country_id;
        $states = State::whereCountryId($country_id)->select('id', 'state_name')->get();
        return $states;
    }

    public function getCityByState(Request $request){
        $state_id = $request->state_id;
        $cities = City::whereStateId($state_id)->select('id', 'city_name')->get();
        return $cities;
    }

    public function getParentCategoryInfo(Request $request){
        $category_id = $request->category_id;
        $sub_category = Category::find($category_id);
        $category = Category::find($sub_category->category_id);
        return $category;
    }

    public function uploadAdsImage(Request $request){
        $user_id = Auth::user()->id;

        if ($request->hasFile('images')){
            $image = $request->file('images');
            $valid_extensions = ['jpg','jpeg','png'];

            if ( ! in_array(strtolower($image->getClientOriginalExtension()), $valid_extensions) ){
                return ['success' => 0, 'msg' => implode(',', $valid_extensions).' '.trans('app.valid_extension_msg')];
            }

            $file_base_name = str_replace('.'.$image->getClientOriginalExtension(), '', $image->getClientOriginalName());

            $resized = Image::make($image)->resize(640, null, function ($constraint) {
                $constraint->aspectRatio();
            })->stream();
            $resized_thumb = Image::make($image)->resize(320, 213)->stream();

            $image_name = strtolower(time().str_random(5).'-'.str_slug($file_base_name)).'.' . $image->getClientOriginalExtension();

            $imageFileName = 'uploads/images/'.$image_name;
            $imageThumbName = 'uploads/images/thumbs/'.$image_name;

            try{
                //Upload original image
                $is_uploaded = current_disk()->put($imageFileName, $resized->__toString(), 'public');

                if ($is_uploaded) {
                    //Save image name into db
                    $created_img_db = Media::create(['user_id' => $user_id, 'media_name'=>$image_name, 'type'=>'image', 'storage' => get_option('default_storage'), 'ref'=>'ad']);

                    //upload thumb image
                    current_disk()->put($imageThumbName, $resized_thumb->__toString(), 'public');
                    $img_url = media_url($created_img_db, false);
                    return ['success' => 1, 'img_url' => $img_url];
                } else {
                    return ['success' => 0];
                }
            } catch (\Exception $e){
                return $e->getMessage();
            }

        }
    }
    /**
     * @param Request $request
     * @return array
     */

    public function deleteMedia(Request $request){
        $media_id = $request->media_id;
        $media = Media::find($media_id);

        $storage = Storage::disk($media->storage);
        if ($storage->has('uploads/images/'.$media->media_name)){
            $storage->delete('uploads/images/'.$media->media_name);
        }

        if ($media->type == 'image'){
            if ($storage->has('uploads/images/thumbs/'.$media->media_name)){
                $storage->delete('uploads/images/thumbs/'.$media->media_name);
            }
        }

        $media->delete();
        return ['success'=>1, 'msg'=>trans('app.media_deleted_msg')];
    }

    /**
     * @param Request $request
     * @return array
     */
    public function featureMediaCreatingAds(Request $request){
        $user_id = Auth::user()->id;
        $media_id = $request->media_id;

        Media::whereUserId($user_id)->whereAdId('0')->whereRef('ad')->update(['is_feature'=>'0']);
        Media::whereId($media_id)->update(['is_feature'=>'1']);

        return ['success'=>1, 'msg'=>trans('app.media_featured_msg')];
    }

    /**
     * @return mixed
     */
    
    public function appendMediaImage(){
        $user_id = Auth::user()->id;
        $ads_images = Media::whereUserId($user_id)->whereAdId(0)->whereRef('ad')->get();

        return view('admin.append_media', compact('ads_images'));
    }

    /**
     * Listing
     * 
     * 
     * 
     */
     
    public function agents(Request $request){
        $ads = Ad::active();
        $premium_ads = Ad::activePremium();
        //format string for indexing and search
        function format_string($data){
    
            //(1)combine string 
            $mydata = array();
            foreach($data as $thisdata){
                $mydata[] = $thisdata;
            }
            
            $mydata = implode(" ", $mydata);
            
            //(2)replace punctuation
            $mypuncs = array(':', ':', "'", '!', '.', ']', '[');
            foreach($mypuncs as $punc){
                $mydata = str_replace($punc, " ", $mydata);
            }
            
            //(3)replace apostrophe with nothing
            $mydata = str_replace("'", " ", $mydata);
            $mydata = str_replace("`", " ", $mydata);
            
            //(4)replace commas inbweeten numbers
            $mydata = preg_replace_callback("/(?P<nrs>[0-9]+,[0-9]+)/",
                                            function($matches){
                                                return str_replace("," , "" , $matches["nrs"]);
                                            } , 
                                            $mydata);
            
            //(5)replace commas with space
            $mydata = str_replace(",", " ", $mydata);
            
            //(6)correct spellings
            $mydata = explode(" ", $mydata);
            foreach($mydata as $thisdata){
                if(!is_numeric($thisdata)){
                    $thisdata = metaphone($thisdata);
                    $mysaves[] = $thisdata;
                    
                }
                else{
                    $mysaves[] = $thisdata;
                }
            }
            
            //return data as an array and string
            return $mydata = [
                        'data_array'  => $mysaves,
                        'data_string' => implode(" ", $mysaves),
                       ];
          }
        
        //handle request
        if ($request){
            $myreq = explode(" ", $request->q);
            $myreq = format_string($myreq);
            $myreq = $myreq['data_array'];
            $ads = $ads->where(function($ads) use($request, $myreq) {
            foreach ($myreq as $keyword) {
                $ads->where('keywords', 'like', "% {$keyword} %");
                }
            });
        }
        
        if ($request->type){
            $ads = $ads->whereType($request->type);
        }
        if ($request->country){
            $ads = $ads->whereCountryId($request->country);
        }
        if ($request->state){
            $ads = $ads->whereStateId($request->state);
        }
        if ($request->city){
            $ads = $ads->whereCityId($request->city);
        }
        if ($request->min_price){
            $ads = $ads->where('price', '>=', $request->min_price);
        }
        if ($request->max_price){
            $ads = $ads->where('price', '<=', $request->max_price);
        }
        if ($request->adType){
            if ($request->adType == 'business') {
                $ads = $ads->business();
            }elseif ($request->adType == 'personal'){
                $ads = $ads->personal();
            }
        }
        if ($request->user_id){
            $ads = $ads->whereUserId($request->user_id);
        }
        if ($request->shortBy){
            switch ($request->shortBy){
                case 'price_high_to_low':
                    $ads = $ads->orderBy('price', 'desc');
                    break;
                case 'price_low_to_height':
                    $ads = $ads->orderBy('price', 'asc');
                    break;
                case 'latest':
                    $ads = $ads->orderBy('id', 'desc');
                    break;
            }
        }else{
            $ads = $ads->orderBy('id', 'desc');
        }

        $ads_per_page = get_option('ads_per_page');
        $ads = $ads->with('city');
        $ads = $ads->paginate($ads_per_page);

        //Check max impressions
        $max_impressions = get_option('premium_ads_max_impressions');
        $premium_ads = $premium_ads->where('max_impression', '<', $max_impressions);
        $take_premium_ads = get_option('number_of_premium_ads_in_listing');
        if ($take_premium_ads > 0){
            $premium_order_by = get_option('order_by_premium_ads_in_listing');
            $premium_ads = $premium_ads->take($take_premium_ads);
            $last_days_premium_ads = get_option('number_of_last_days_premium_ads');

            $premium_ads = $premium_ads->where('created_at', '>=', Carbon::now()->timezone(get_option('default_timezone'))->subDays($last_days_premium_ads));

            if ($premium_order_by == 'latest'){
                $premium_ads = $premium_ads->orderBy('id', 'desc');
            }elseif ($premium_order_by == 'random'){
                $premium_ads = $premium_ads->orderByRaw('RAND()');
            }

            $premium_ads = $premium_ads->get();

        }else{
            $premium_ads = false;
        }
        
        $title = trans('app.search_properties');
        $countries = Country::all();

        $selected_categories = Category::find($request->category);
        $selected_sub_categories = Category::find($request->sub_category);

        $selected_countries = Country::find($request->country);
        $selected_states = State::find($request->state);
        //dd($selected_countries->states);

        $agents = User::whereActiveStatus('1')->whereUserType('agent')->take(10)->orderBy('id', 'desc')->get();
        $feature_agents = User::whereActiveStatus('1')->whereUserType('agent')->wherefeature(1)->take(10)->orderBy('id', 'desc')->get();
        session(['grid_list_view' => 'list']);
        return view($this->theme.'agents', compact( 'title','agents', 'feature_agents'));
    }
    
    public function listing(Request $request){
        $ads = Ad::active();
        $premium_ads = Ad::activePremium();
        
        //primal coordinates
        function get_cods($ads, $request){
            $first_ad = $ads->first();
            //run if ads exist
            $lat = @$first_ad->latitude;
            $lng = @$first_ad->longitude;
            $res = false;
            $zoom = 13;
            $my_res = 'Total Listings Found For : <u>'. $request->q .'</u>' ;
            
            
            if($lat == null || $lng == null || $request->q == null || $request->q == 'zambia'){
                $lat = -15.2562546;
                $lng = 28.52351265;
                $zoom = 7;
                $res = true;
                $my_res = 'Smart search could not find listings  for <u> '. $request->q . '</u> Other Listings:';
                
            }
            if(isset($request->q)){
                   
            }else{
                 $my_res = null;
            }
            return $co_od = [
                'lat' => $lat,
                'lng' => $lng,
                'zoom' => $zoom,
                'res' => $res,
                'myres' => $my_res
                ];
        }
        
        //format string for indexing and search
        function format_string($data){
    
            //(1)combine string 
            $mydata = array();
            foreach($data as $thisdata){
                $mydata[] = $thisdata;
            }
            
            $mydata = implode(" ", $mydata);
            
            //(2)replace punctuation
            $mypuncs = array(':', ':', "'", '!', '.', ']', '[');
            foreach($mypuncs as $punc){
                $mydata = str_replace($punc, " ", $mydata);
            }
            
            //(3)replace apostrophe with nothing
            $mydata = str_replace("'", " ", $mydata);
            $mydata = str_replace("`", " ", $mydata);
            
            //(4)replace commas inbweeten numbers
            $mydata = preg_replace_callback("/(?P<nrs>[0-9]+,[0-9]+)/",
                                            function($matches){
                                                return str_replace("," , "" , $matches["nrs"]);
                                            } , 
                                            $mydata);
            
            //(5)replace commas with space
            $mydata = str_replace(",", " ", $mydata);
            
            //(6)correct spellings
            $mydata = explode(" ", $mydata);
            foreach($mydata as $thisdata){
                if(!is_numeric($thisdata)){
                    $thisdata = metaphone($thisdata);
                    $mysaves[] = $thisdata;
                    
                }
                else{
                    $mysaves[] = $thisdata;
                }
            }
            
            //return data as an array and string
            return $mydata = [
                        'data_array'  => $mysaves,
                        'data_string' => implode(" ", $mysaves),
                       ];
          }
        
        //handle request
        if ($request){
            $myreq = explode(" ", $request->q);
            $myreq = format_string($myreq);
            $myreq = $myreq['data_array'];
            $ads = $ads->where(function($ads) use($request, $myreq) {
            foreach ($myreq as $keyword) {
                $ads->where('keywords', 'like', "% {$keyword} %");
                }
            });
        }
        
        if ($request->type){
            $ads = $ads->whereType($request->type);
        }
        if ($request->country){
            $ads = $ads->whereCountryId($request->country);
        }
        if ($request->state){
            $ads = $ads->whereStateId($request->state);
        }
        if ($request->city){
            $ads = $ads->whereCityId($request->city);
        }
        if ($request->min_price){
            $ads = $ads->where('price', '>=', $request->min_price);
        }
        if ($request->max_price){
            $ads = $ads->where('price', '<=', $request->max_price);
        }
        if ($request->adType){
            if ($request->adType == 'business') {
                $ads = $ads->business();
            }elseif ($request->adType == 'personal'){
                $ads = $ads->personal();
            }
        }
        if ($request->user_id){
            $ads = $ads->whereUserId($request->user_id);
        }
        if ($request->shortBy){
            switch ($request->shortBy){
                case 'price_high_to_low':
                    $ads = $ads->orderBy('price', 'desc');
                    break;
                case 'price_low_to_height':
                    $ads = $ads->orderBy('price', 'asc');
                    break;
                case 'latest':
                    $ads = $ads->orderBy('id', 'desc');
                    break;
            }
        }else{
            $ads = $ads->orderBy('id', 'desc');
        }

        $ads_per_page = get_option('ads_per_page');
        $ads = $ads->with('city')->whereNotNull('latitude')->whereNotNull('longitude');
        $ads = $ads->paginate($ads_per_page);
        
        //coordinates
        $cods = get_cods($ads, $request);
        if($cods['res']){
            $ads = Ad::active();
            $ads = $ads->with('city')->whereNotNull('latitude')->whereNotNull('longitude');
            $ads = $ads->paginate($ads_per_page);
        }
        

        //Check max impressions
        $max_impressions = get_option('premium_ads_max_impressions');
        $premium_ads = $premium_ads->where('max_impression', '<', $max_impressions);
        $take_premium_ads = get_option('number_of_premium_ads_in_listing');
        if ($take_premium_ads > 0){
            $premium_order_by = get_option('order_by_premium_ads_in_listing');
            $premium_ads = $premium_ads->take($take_premium_ads);
            $last_days_premium_ads = get_option('number_of_last_days_premium_ads');

            $premium_ads = $premium_ads->where('created_at', '>=', Carbon::now()->timezone(get_option('default_timezone'))->subDays($last_days_premium_ads));

            if ($premium_order_by == 'latest'){
                $premium_ads = $premium_ads->orderBy('id', 'desc');
            }elseif ($premium_order_by == 'random'){
                $premium_ads = $premium_ads->orderByRaw('RAND()');
            }

            $premium_ads = $premium_ads->get();

        }else{
            $premium_ads = false;
        }
        
        $title = trans('app.search_properties');
        $countries = Country::all();

        $selected_categories = Category::find($request->category);
        $selected_sub_categories = Category::find($request->sub_category);

        $selected_countries = Country::find($request->country);
        $selected_states = State::find($request->state);
        //dd($selected_countries->states);
        
        $req = $request->q;

        

        $agents = User::whereActiveStatus('1')->whereFeature('1')->whereUserType('user')->take(10)->orderBy('id', 'desc')->get();
        
        $providers = Service_provider::where('status',0)->get();
//         $origin = $request->ip();
//         $json = file_get_contents("http://api.ipstack.com/" . $origin . "?access_key=c450b4e65d3ac153a25c94c43a34f2f3");
//         $json = json_decode($json);
        
//         try { $locationofsearcher = $json->city .", ". $json->country_name;
//         } catch (Exception $e) {
//             $locationofsearcher ="Lusaka";
//         }
//                 if(!isset($request->q)){
//              $req = $locationofsearcher;
//         }
//               $u_agent = $_SERVER['HTTP_USER_AGENT'];
//   $bname = 'Unknown';
//   $platform = 'Unknown';
//   $version= "";

//   //First get the platform?
//   if (preg_match('/linux/i', $u_agent)) {
//     $platform = 'linux';
//   }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
//     $platform = 'mac';
//   }elseif (preg_match('/windows|win32/i', $u_agent)) {
//     $platform = 'windows';
//   }

//   // Next get the name of the useragent yes seperately and for good reason
//   if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)){
//     $bname = 'Internet Explorer';
//     $ub = "MSIE";
//   }elseif(preg_match('/Firefox/i',$u_agent)){
//     $bname = 'Mozilla Firefox';
//     $ub = "Firefox";
//   }elseif(preg_match('/OPR/i',$u_agent)){
//     $bname = 'Opera';
//     $ub = "Opera";
//   }elseif(preg_match('/Chrome/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
//     $bname = 'Google Chrome';
//     $ub = "Chrome";
//   }elseif(preg_match('/Safari/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
//     $bname = 'Apple Safari';
//     $ub = "Safari";
//   }elseif(preg_match('/Netscape/i',$u_agent)){
//     $bname = 'Netscape';
//     $ub = "Netscape";
//   }elseif(preg_match('/Edge/i',$u_agent)){
//     $bname = 'Edge';
//     $ub = "Edge";
//   }elseif(preg_match('/Trident/i',$u_agent)){
//     $bname = 'Internet Explorer';
//     $ub = "MSIE";
//   }

//   // finally get the correct version number
//   $known = array('Version', $ub, 'other');
//   $pattern = '#(?<browser>' . join('|', $known) .
// ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
//   if (!preg_match_all($pattern, $u_agent, $matches)) {
//     // we have no matching number just continue
//   }
//   // see how many we have
//   $i = count($matches['browser']);
//   if ($i != 1) {
//     //we will have two since we are not using 'other' argument yet
//     //see if version is before or after the name
//     if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
//         $version= $matches['version'][0];
//     }else {
//         $version= $matches['version'][1];
//     }
//   }else {
//     $version= $matches['version'][0];
//   }
//     $model = new Visitors;
//     $model->country= $json->country_name;
//     $model->City= $json->city;
//     $model->ip= $json->ip;
//     $model->Device= $platform;
//     $model->browser= $bname;
//     $model->version= $version;
//     $model->page = "listing page";
//     if (auth()->user()){
//                 $user = auth()->user();
//      $model->user_id = $user->id;
//     }
//     $model->save();

        session(['grid_list_view' => 'list']);
        // return view($this->theme.'listing', compact('locationofsearcher','providers','top_categories', 'ads', 'title', 'countries', 'selected_categories', 'selected_sub_categories', 'selected_countries', 'selected_states', 'premium_ads', 'agents', 'cods', 'req'));
        return view($this->theme.'listing', compact('providers','top_categories', 'ads', 'title', 'countries', 'selected_categories', 'selected_sub_categories', 'selected_countries', 'selected_states', 'premium_ads', 'agents', 'cods', 'req'));
    }


    public function red(Request $request){
            $outputpremium = array();

        return view($this->theme.'red', $outputpremium);
    }

    // Get Images from Media Database
    public function getPictures($ad_id){

        $images = Media::where('ad_id', $ad_id)->get();
        if(count($images) > 0 ){
            return response()->json(['hasImages'=>true, 'ad_images'=>$images]);
        } else{
            return response()->json(['hasImages'=>false]);
        }

    }
    

    /**
     * @param $slug
     * @return mixed
     */
    public function reportAd($slug){
        $limit_regular_ads = get_option('number_of_free_ads_in_home');
        $ad = Ad::whereSlug($slug)->first();

        if (! $ad){
            return view('theme.error_404');
        }
        
        if ( ! $ad->is_published()){
            if (Auth::check()){
                $user_id = Auth::user()->id;
                if ($user_id != $ad->user_id){
                    return view('theme.error_404');
                }
            }else{
                return view('theme.error_404');
            }
        }else{
            $ad->view = $ad->view+1;
            $ad->save();
        }

        $title = $ad->title;
        $ad_agent_id = $ad->user_id;

        //Get distances
        $distances = Brand::all();
        $indore_ammenties = Category::whereCategoryType('indoor')->get();
        $outdoor_ammenties = Category::whereCategoryType('outdoor')->get();
        //Get Related Ads, add [->whereCountryId($ad->country_id)] for more specific results
        $related_ads = Ad::active()->whereUserId($ad_agent_id)->where('id', '!=',$ad->id)->with('city')->limit($limit_regular_ads)->orderByRaw('RAND()')->get();

        $agents = User::whereActiveStatus('1')->whereFeature('1')->whereUserType('user')->take(10)->orderBy('id', 'desc')->get();

        return view($this->theme.'reportad', compact('ad', 'title', 'distances', 'indore_ammenties', 'outdoor_ammenties', 'related_ads', 'agents'));
    }


    public function singleAd($slug){
        $limit_regular_ads = get_option('number_of_free_ads_in_home');
        $ad = Ad::whereSlug($slug)->first();

        if (! $ad){
            return view('theme.error_404');
        }
        
        if ( ! $ad->is_published()){
            if (Auth::check()){
                $user_id = Auth::user()->id;
                if ($user_id != $ad->user_id){
                    return view('theme.error_404');
                }
            }else{
                return view('theme.error_404');
            }
        }else{
            $ad->view = $ad->view+1;
            $ad->save();
        }
        $other_agents = Ad_agent::where([['property_id', $ad->id],['accepted', 1]])->get();
        $title = $ad->title;
        $ad_agent_id = $ad->user_id;
        $myagent = User::whereId($ad->user_id)->first();
        // $agency = Agency::whereId($myagent->agency)->first();
        // $ad->agency = $agency;
        //Get distances
        $distances = Brand::all();
        $indore_ammenties = Category::whereCategoryType('indoor')->get();
        $outdoor_ammenties = Category::whereCategoryType('outdoor')->get();
        //Get Related Ads, add [->whereCountryId($ad->country_id)] for more specific results
        $related_ads = Ad::active()->whereUserId($ad_agent_id)->where('id', '!=',$ad->id)->with('city')->limit($limit_regular_ads)->orderByRaw('RAND()')->get();

        $agents = User::whereActiveStatus('1')->whereFeature('1')->whereUserType('user')->take(10)->orderBy('id', 'desc')->get();

        // return view($this->theme.'single_ad', compact('ad', 'title', 'distances', 'indore_ammenties', 'outdoor_ammenties', 'related_ads', 'agents', 'agency'));
        return view($this->theme.'single_ad', compact('ad', 'title', 'distances', 'indore_ammenties', 'outdoor_ammenties', 'related_ads', 'agents','other_agents'));
    }

    public function embeddedAd($slug){
        $ad = Ad::whereSlug($slug)->first();
        return view($this->theme.'embedded_ad', compact('ad'));
    }

    /**
     * @param Request $request
     */

    public function switchGridListView(Request $request){
        
        session(['grid_list_view' => 'list']);
    }

    /**
     * @param Request $request
     * @return array
     */

    public function reportAds(Request $request){
        $ad = Ad::whereSlug($request->slug)->first();
        if ($ad) {
            $data = [
                'ad_id' => $ad->id,
                'reason' => $request->reason,
                'email' => $request->email,
                'message' => $request->message,
            ];
            Report_ad::create($data);
            return ['status'=>1, 'msg'=>trans('app.ad_reported_msg')];
        }
        return ['status'=>0, 'msg'=>trans('app.error_msg')];
    }
    
    public function reports(){
        $reports = Report_ad::orderBy('id', 'desc')->with('ad')->paginate(20);
        $title = trans('app.ad_reports');

        return view('admin.ad_reports', compact('title', 'reports'));
    }

    public function deleteReports(Request $request){
        Report_ad::find($request->id)->delete();
        return ['success'=>1, 'msg' => trans('app.report_deleted_success')];
    }
    
    public function reportsByAds($slug){
        $user = Auth::user();

        if ($user->is_admin()){
            $ad = Ad::whereSlug($slug)->first();
        }else{
            $ad = Ad::whereSlug($slug)->whereUserId($user->id)->first();
        }

        if (! $ad){
            return view('admin.error.error_404');
        }

        $reports = $ad->reports()->paginate(20);

        $title = trans('app.ad_reports');
        return view('admin.reports_by_ads', compact('title', 'ad', 'reports'));

    }

    public function listingModal(Request $request){
        $ads = Ad::active();
        $premium_ads = Ad::activePremium();
        
        //primal coordinates
        function get_cods($ads, $request){
            $first_ad = $ads->first();
            //run if ads exist
            $lat = @$first_ad->latitude;
            $lng = @$first_ad->longitude;
            $res = false;
            $zoom = 13;
            $my_res = 'Total Listings Found For : <u>'. $request->q .'</u>' ;
            
            
            if($lat == null || $lng == null || $request->q == null || $request->q == 'zambia'){
                $lat = -15.2562546;
                $lng = 28.52351265;
                $zoom = 7;
                $res = true;
                $my_res = 'Smart search could not find listings  for <u> '. $request->q . '</u> Other Listings:';
                
            }
            if(isset($request->q)){
                   
            }else{
                 $my_res = null;
            }
            return $co_od = [
                'lat' => $lat,
                'lng' => $lng,
                'zoom' => $zoom,
                'res' => $res,
                'myres' => $my_res
                ];
        }
        
        //format string for indexing and search
        function format_string($data){
    
            //(1)combine string 
            $mydata = array();
            foreach($data as $thisdata){
                $mydata[] = $thisdata;
            }
            
            $mydata = implode(" ", $mydata);
            
            //(2)replace punctuation
            $mypuncs = array(':', ':', "'", '!', '.', ']', '[');
            foreach($mypuncs as $punc){
                $mydata = str_replace($punc, " ", $mydata);
            }
            
            //(3)replace apostrophe with nothing
            $mydata = str_replace("'", " ", $mydata);
            $mydata = str_replace("`", " ", $mydata);
            
            //(4)replace commas inbweeten numbers
            $mydata = preg_replace_callback("/(?P<nrs>[0-9]+,[0-9]+)/",
                                            function($matches){
                                                return str_replace("," , "" , $matches["nrs"]);
                                            } , 
                                            $mydata);
            
            //(5)replace commas with space
            $mydata = str_replace(",", " ", $mydata);
            
            //(6)correct spellings
            $mydata = explode(" ", $mydata);
            foreach($mydata as $thisdata){
                if(!is_numeric($thisdata)){
                    $thisdata = metaphone($thisdata);
                    $mysaves[] = $thisdata;
                    
                }
                else{
                    $mysaves[] = $thisdata;
                }
            }
            
            //return data as an array and string
            return $mydata = [
                        'data_array'  => $mysaves,
                        'data_string' => implode(" ", $mysaves),
                       ];
          }
        
        //handle request
        if ($request){
            $myreq = explode(" ", $request->q);
            $myreq = format_string($myreq);
            $myreq = $myreq['data_array'];
            $ads = $ads->where(function($ads) use($request, $myreq) {
            foreach ($myreq as $keyword) {
                $ads->where('keywords', 'like', "% {$keyword} %");
                }
            });
        }
        
        if ($request->type){
            $ads = $ads->whereType($request->type);
        }
        if ($request->country){
            $ads = $ads->whereCountryId($request->country);
        }
        if ($request->state){
            $ads = $ads->whereStateId($request->state);
        }
        if ($request->city){
            $ads = $ads->whereCityId($request->city);
        }
        if ($request->min_price){
            $ads = $ads->where('price', '>=', $request->min_price);
        }
        if ($request->max_price){
            $ads = $ads->where('price', '<=', $request->max_price);
        }
        if ($request->adType){
            if ($request->adType == 'business') {
                $ads = $ads->business();
            }elseif ($request->adType == 'personal'){
                $ads = $ads->personal();
            }
        }
        if ($request->user_id){
            $ads = $ads->whereUserId($request->user_id);
        }
        if ($request->shortBy){
            switch ($request->shortBy){
                case 'price_high_to_low':
                    $ads = $ads->orderBy('price', 'desc');
                    break;
                case 'price_low_to_height':
                    $ads = $ads->orderBy('price', 'asc');
                    break;
                case 'latest':
                    $ads = $ads->orderBy('id', 'desc');
                    break;
            }
        }else{
            $ads = $ads->orderBy('id', 'desc');
        }

        $ads_per_page = get_option('ads_per_page');
        $ads = $ads->with('city')->whereNotNull('latitude')->whereNotNull('longitude');
        $ads = $ads->paginate($ads_per_page);
        
        //coordinates
        $cods = get_cods($ads, $request);
        if($cods['res']){
            $ads = Ad::active();
            $ads = $ads->with('city')->whereNotNull('latitude')->whereNotNull('longitude');
            $ads = $ads->paginate($ads_per_page);
        }
        

        //Check max impressions
        $max_impressions = get_option('premium_ads_max_impressions');
        $premium_ads = $premium_ads->where('max_impression', '<', $max_impressions);
        $take_premium_ads = get_option('number_of_premium_ads_in_listing');
        if ($take_premium_ads > 0){
            $premium_order_by = get_option('order_by_premium_ads_in_listing');
            $premium_ads = $premium_ads->take($take_premium_ads);
            $last_days_premium_ads = get_option('number_of_last_days_premium_ads');

            $premium_ads = $premium_ads->where('created_at', '>=', Carbon::now()->timezone(get_option('default_timezone'))->subDays($last_days_premium_ads));

            if ($premium_order_by == 'latest'){
                $premium_ads = $premium_ads->orderBy('id', 'desc');
            }elseif ($premium_order_by == 'random'){
                $premium_ads = $premium_ads->orderByRaw('RAND()');
            }

            $premium_ads = $premium_ads->get();

        }else{
            $premium_ads = false;
        }
        
        $title = trans('app.search_properties');
        $countries = Country::all();

        $selected_categories = Category::find($request->category);
        $selected_sub_categories = Category::find($request->sub_category);

        $selected_countries = Country::find($request->country);
        $selected_states = State::find($request->state);
        //dd($selected_countries->states);
        
        $req = $request->q;
        

        $agents = User::whereActiveStatus('1')->whereFeature('1')->whereUserType('user')->take(10)->orderBy('id', 'desc')->get();
        session(['grid_list_view' => 'list']);
        return view($this->theme.'listing_modal', compact('top_categories', 'ads', 'title', 'countries', 'selected_categories', 'selected_sub_categories', 'selected_countries', 'selected_states', 'premium_ads', 'agents', 'cods', 'req'));
    }
    
    public function getExchangeRates(){
        
        $url = 'http://data.fixer.io/api/latest?access_key=1b13022fe6f90d1cdc15595495a0c7e4';
    
        //Initiate cURL
        $curl = curl_init($url);
        $result = curl_exec($curl);
        
        curl_close($curl);
    
        //Print out the response output.
        echo $result;
    }
    
    
      public function setAgent(Request $request, $id)
      {
      
        $title = "Ad Agents";
        // $title = $request->name;
        $has_agents = false;
        $property_id = $id;
        $agents_added = Ad_agent::where("property_id", $id)->get();
        if(!isset($request->name)){
            return view('admin.add_agent',compact('has_agents','property_id', 'title', "agents_added"));
        } else{
           
            
            $agents = User::where([["user_type","=","agent"],["active_status","=","1"]])->where("name", 'LIKE', '%' . $request->name . '%')->get();
            
            // foreach($agents as $agent){
            //     $agent_string = 
            // }
            return view('admin.add_agent',compact('has_agents','property_id', 'title',"agents", "agents_added"));
        }
        
      }
      
      public function setAgentToAd($property_id, $agent_id){
          
          $current_agent = Ad_agent::where([["property_id", '=' , $property_id],["agent_id",'=', $agent_id] ])->first();
          
          if(isset($current_agent)){
              return redirect()->back()->with('error', "The agent has already been added to the Property Please wait for their response");
          }
          
          $ad_agent = new Ad_agent;
          
          $ad_agent->user_id = Auth::user()->id;
          $ad_agent->agent_id = $agent_id;
          $ad_agent->property_id = $property_id;
          $ad_agent->save();
          
          $user = User::find($agent_id);
          $ad = Ad::find($property_id);
          
          $email_data = (object)['email'=>$user->email, 'name'=>$user->name];
          $email_content = ["name"=>$user->name, "ad_title"=>$ad->title];
          
          
    
          Mail::send('emails.set_agent', $email_content, function ($m) use ($email_data) {
            $m->from('website@kupeza.co.zm', 'Kupeza');
    
            $m->to($email_data->email, $email_data->name)->subject('You have been Added to A Property');
          });
          
          
          
          return redirect()->back()->with('success', "The agent has been added to the Property you will get a notification when they accept");
          
      }
      
      public function addedToAdPage(){
          
          $title = "Property Invites";
          $properties_added = Ad_agent::where('agent_id',Auth::user()->id)->get();
          
          return view('admin.added_to_ad',compact('properties_added', 'title'));
      }
      
      public function acceptAdInvite($invite_id, $answer){
          
          $properties_added = Ad_agent::find($invite_id);
          $user = User::find($properties_added->user_id);
          
          $email_data = (object)['email'=>$user->email, 'name'=>$user->name];
          
          
          if($answer == 1){
              
              $email_content = ["name"=>$user->name, "invite_status"=>"Accepted", "agent_name"=>Auth::user()->name];
          
          
    
              Mail::send('emails.invite_status', $email_content, function ($m) use ($email_data) {
                $m->from('website@kupeza.co.zm', 'Kupeza');
        
                $m->to($email_data->email, $email_data->name)->subject('Your Invite has been Accepted');
              });
              
              $properties_added->accepted = 1;
              $properties_added->save();
              return redirect()->back()->with('success', "You have successfully accepted the invite");
              
          } else{
              
              $email_content = ["name"=>$user->name, "invite_status"=>"Rejected", "agent_name"=>Auth::user()->name];
          
          
    
              Mail::send('emails.invite_status', $email_content, function ($m) use ($email_data) {
                $m->from('website@kupeza.co.zm', 'Kupeza');
        
                $m->to($email_data->email, $email_data->name)->subject('Your Invite has been Rejected');
              });
              
             $properties_added->accepted = 2;
              $properties_added->save();
              return redirect()->back()->with('error', "You have rejected the invite"); 
          }
          
      }
    
}
