<?php

namespace App\Http\Controllers;

use App\Ad;
use App\Contact_query;
use App\Payment;
use App\Service_provider;
use App\User;
use App\Media;
use App\City;
use Illuminate\Http\Request;

use App\Http\Requests;



use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;
use Illuminate\Http\Response;

// use Symfony\Component\HttpFoundation\Response;

// use Mail;




class CustomController extends Controller
{
    
    public function serviceProvidersIndex(){
        
        $providers = Service_provider::all();
        
        return view('admin.service_providers', compact('providers'));
        
    }
    
    public function serviceProvidersCreate(){
        
        // $providers = Service_provider::All();
        
        return view('admin.service_providers_add', compact('providers'));
        
    }
    
    public function serviceProvidersAdd(Request $request){
        
        
        $this->validate($request,[
            'name'=>'required',
            'description'=>'required',
            'type'=>'required',
            'logo'=>'required|image',
            
        ]);
        
        
        
        if ($request->hasFile('logo')){
            $rules = ['photo'=>'mimes:jpeg,jpg,png'];
            $this->validate($request, $rules);
            
            $image = $request->file('logo');
            $file_base_name = str_replace('.'.$image->getClientOriginalExtension(), '', $image->getClientOriginalName());
            $resized_thumb = Image::make($image)->stream();

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

            $imageFileName = 'uploads/images/serviceproviders/'.$image_name;

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

        }else{
            $fileNameToStore = 'default.jpg';
        }
        
        
        
        $provider = new Service_provider;
        $provider->name = $request->name;
        $provider->description = $request->description;
        $provider->type = $request->type;
        $provider->logo = $image_name;
        $provider->website = $request->website;
        $provider->email = $request->email;
        $provider->phone_number = $request->phone_number;
        $provider->rate = $request->rate;
        $provider->price = $request->price;
        $provider->status = $request->status;
        $provider->is_premium = $request->premium;
        $provider->save();
        
        
        return back()->with('success','The provider has been Added');
        
    }
    
    public function serviceProvidersModify($id){
        $provider = Service_provider::find($id);
        
        return view('admin.service_providers_edit', compact('provider'));
    }
    
    public function serviceProvidersEdit(Request $request, $id){
        
        $provider = Service_provider::find($id);
        
        // $providers = Service_provider::All();
        $this->validate($request,[
            'name'=>'required',
            'description'=>'required',
            'type'=>'required',
            
            
        ]);
        
        
        
        if ($request->hasFile('logo')){
            $rules = ['photo'=>'mimes:jpeg,jpg,png'];
            $this->validate($request, $rules);
            
            $image = $request->file('logo');
            $file_base_name = str_replace('.'.$image->getClientOriginalExtension(), '', $image->getClientOriginalName());
            $resized_thumb = Image::make($image)->stream();

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

            $imageFileName = 'uploads/images/serviceproviders/'.$image_name;

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

            if ($is_uploaded){
                $previous_photo= $provider->logo;
                $previous_photo_storage= $provider->logo;
                                    


                $provider->logo = $image_name;
                // $user->photo_storage = get_option('default_storage');
                

                if ($previous_photo != "default.jpg"){
                    $previous_photo_path = 'uploads/images/serviceproviders/'.$previous_photo;
                    $storage = Storage::disk('public');
                    if ($storage->has($previous_photo_path)){
                        $storage->delete($previous_photo_path);
                    }
                }
            }
        }
        
        $provider->name = $request->name;
        $provider->description = $request->description;
        $provider->type = $request->type;
        // $provider->logo = $image_name;
        $provider->website = $request->website;
        $provider->email = $request->email;
        $provider->phone_number = $request->phone_number;
        $provider->rate = $request->rate;
        $provider->price = $request->price;
        $provider->status = $request->status;
        $provider->is_premium = $request->premium;
        
        $provider->save();
        
        
        return back()->with('success','The provider has been Updated');
        
    }

    public function providerApi()
    {
        $providers = Service_provider::All();
        // $providers = Service_provider::where('status',0)->get();
        
        return $providers;
    }
    
    public function messageProvider($id)
    {
        $provider = Service_provider::find($id);
        
         
        
        return view('theme.contact_provider', compact('provider'));
        
    }
    
    public function sendToProvider(Request $request)
    {
        
        $provider = Service_provider::find($request->id);
        
        
        $toEmail = "chota@pynch.co.zm";//$provider->email
        $ccEmail = $request->email;
        
        $data = array('sender_name'=>$request->name.' '.$request->lname,'themessage'=>$request->message, 'phone_number'=>$request->phone, 'email'=>$request->email, 'provider_name'=>$provider->name);
        
        Mail::send('emails.contact_provider', $data, function($message) use ($toEmail, $request)
        {
            $message->to($toEmail, 'Email Message')->subject('You Have A Query From Kupeza');
            $message->cc($request->email);
            $message->bcc('info@kupeza.co.zm');
            $message->from('info@kupeza.co.zm','Kupeza Support Team');
        });
        
        return back()->with('success','The E-Mail has been sent');
        
        
    }
    
    public function sendToProviderApi(Request $request)
    {
        
        $provider = Service_provider::find($request->id);
        
        
        $toEmail = "chota@pynch.co.zm";//$provider->email
        // $ccEmail = $request->email;
        
        $data = array('sender_name'=>$request->name.' '.$request->lname,'themessage'=>$request->message, 'phone_number'=>$request->phone, 'email'=>$request->email, 'provider_name'=>$provider->name);
        
        Mail::send('emails.contact_provider', $data, function($message) use ($toEmail, $request)
        {
            $message->to($toEmail, 'Email Message')->subject('You Have A Query From Kupeza');
            $message->cc($request->email);
            $message->from('info@kupeza.co.zm','Kupeza Support Team');
        });
        
        
        
        return json_encode(["message"=>"success"]);
        
        
    }
    
    public function addView($id)
    {
        $property = Ad::find($id);
        $property->view += 1;
 
        $property->save();
 
        return json_encode(['message'=>'View added']);
 
     }
     
    //  public function registerSuccess()
    //  {
    //      return view('theme.register_success');
    //  }
    
    public function notifySellers(){
        $properties = Ad::all();
        $propertyCount = 0;
        
        foreach($properties as $property){
            
            $propertyUpdatedAt = strtotime($property->updated_at);
            $currentTime = strtotime(date("Y/m/d"));
            
            $dueTime = $currentTime - $propertyUpdatedAt; //seconds between the two dates
            $dueTime = $dueTime/2592000; //  1 months in seconds
            
            if($dueTime > 3 && $property->status == 1 && $property->purpose == "sale"){
                $propertyCount += 1;
                
                
                $toEmail = $property->seller_email;
                // $toEmail = "testdev@kupeza.co.zm";
                // $ccEmail = $request->email;
                
                $data = array('ad_title'=>$property->title, 'seller_name'=>$property->seller_name, 'the_message'=>"Your property has been listed for over 3 months please mark it as sold or update the property");
                
                Mail::send('emails.ad_reminder', $data, function($message) use ($toEmail)
                {
                    $message->to($toEmail, 'Email Message')->subject('Your Ad on Kupeza');
                    
                    $message->from('info@kupeza.co.zm','Kupeza Support Team');
                });
                
                
            }
            
            if($dueTime > 1 && $property->status == 1 && $property->purpose == "rent"){
                $propertyCount += 1;
                
                
                $toEmail = $property->seller_email;
                // $ccEmail = $request->email;
                // $toEmail = "testdev@kupeza.co.zm";
                
                $data = array('ad_title'=>$property->title, 'seller_name'=>$property->seller_name, 'the_message'=>"Your property has been listed for over 1 month please mark it as rented or update the property");
                
                Mail::send('emails.ad_reminder', $data, function($message) use ($toEmail)
                {
                    $message->to($toEmail, 'Email Message')->subject('Your Ad on Kupeza');
                    
                    $message->from('info@kupeza.co.zm','Kupeza Support Team');
                });
                
                
            }
            
        }
        
        return ["message"=>$propertyCount];
        
    }
    
    // public function wordpressApi($apiKey){
        
    //     if(!isset($apikey)){
    //         return response(json_encode(["status"=>"err"]))
    //                         ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
    //                         ->header('Access-Control-Allow-Origin', '*')
    //                         ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
    //     }
        
    //     $user = User::where('wordpress_api', $apikey)->first();
    //     $properties = Ad::where('user_id', $user->id)->get();
        
    //     // $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token');
    //     // $response->header('Access-Control-Allow-Origin', '*');
        
    //     if(isset($properties)){
    //         return response(json_encode(["status"=>"ok","properties"=>$properties]))
    //                         ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
    //                         ->header('Access-Control-Allow-Origin', '*')
    //                         ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
    // `   }  else {
    //         return response(json_encode(["status"=>"err"]))
    //                         ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
    //                         ->header('Access-Control-Allow-Origin', '*')
    //                         ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
    //     }
    // }
    
    
    public function wordpressApi($apikey){
        
        if(!isset($apikey)){
            return response(json_encode(["status"=>"err", "message"=>"no api key"]))
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        }
        
        $user = User::where('wordpress_api', $apikey)->first();
        
        if(isset($user)){
            $properties = Ad::where([['user_id','=', $user->id],['status','=', 1]])->with(['media_imgs'])->get();
        } else {
            return response(["status"=>"err", "message"=>"invalid key"])
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        }
        
        if(isset($properties)){
            $all_properties = [];
            foreach($properties as $property){
                
                $imgs = Media::where("ad_id", $property->id)->get();
                $property->media_img = $imgs;
                array_push($all_properties, $property);
                
            }
            // $imgs = Media::where("ad_id", 178)->get();
            // 
            return response(["properties"=>$all_properties])
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        } else{
            return response(["status"=>"err", "message"=>"no properties"])
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        }
        
        
    
        
    }
    
    
    public function wordpressView(){
        $user = Auth::user();
        $wordpressApi = $user->wordpress_api;
        return view('admin.wordpress', compact('wordpressApi'));
    }
    
    public function wordpressGenerate(){
        
        $user = Auth::user();
        $user->wordpress_api = str_random(20);
        $user->save();
        
        return redirect()->back()->with('success', "Key Generated");
    }
    
    public function twilioSearch(){
        $sale_type = $_GET['SALE_TYPE'];
        $bedrooms = $_GET['BEDROOMS'];
        $max_budget = $_GET['MAX_BUDGET'];
        $city = $_GET['CITY'];
        $city_id = City::where("city_name","=",ucfirst($city))->first();
        // ['city_id','=',$city_id->id],
        if($sale_type == 'all')
        {
            $properties = Ad::where([['city_id','=',$city_id->id],['type','!=', 'land'],['type','!=', 'commercial_space'],['beds','=', $bedrooms],['price','<=', $max_budget],['status','=', 1]])->with(['media_imgs'])->get();
            return response(["properties"=>$properties])
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        } else {
            $properties = Ad::where([['city_id','=',$city_id->id],['type','!=', 'land'],['type','!=', 'commercial_space'],['purpose','=', $sale_type],['beds','=', $bedrooms],['price','<=', $max_budget],['status','=', 1]])->with(['media_imgs'])->get();
            return response(["properties"=>$properties, "city"=>$city])
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
                            // "properties"=>$properties,
        }
    }
    
    public function twilioSearchOffices(){
        $sale_type = $_GET['SALE_TYPE'];
        $max_budget = $_GET['MAX_BUDGET'];
        $city = $_GET['CITY'];
        $city_id = City::where("city_name","=",ucfirst($city))->first();
        // ['city_id','=',$city_id->id],
        if($sale_type == 'all')
        {
            $properties = Ad::where([['city_id','=',$city_id->id],['type','=', 'commercial_space'],['price','<=', $max_budget],['status','=', 1]])->with(['media_imgs'])->get();
            return response(["properties"=>$properties])
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        } else {
            $properties = Ad::where([['city_id','=',$city_id->id],['type','=', 'commercial_space'],['purpose','=', $sale_type],['price','<=', $max_budget],['status','=', 1]])->with(['media_imgs'])->get();
            return response(["properties"=>$properties, "city"=>$city])
                            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                            ->header('Access-Control-Allow-Origin', '*')
                            ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
                            // "properties"=>$properties,
        }
    }
    
    public function twilioSearchLand(){
        // $sale_type = $_GET['SALE_TYPE'];
        $max_budget = $_GET['MAX_BUDGET'];
        $city = $_GET['CITY'];
        $city_id = City::where("city_name","=",ucfirst($city))->first();
        // ['city_id','=',$city_id->id],
        $properties = Ad::where([['city_id','=',$city_id->id],['type','=', 'land'],['price','<=', $max_budget],['status','=', 1]])->with(['media_imgs'])->get();
        return response(["properties"=>$properties])
                        ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
                        ->header('Access-Control-Allow-Origin', '*')
                        ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        // if($sale_type == 'all')
        // {
        //     $properties = Ad::where([['city_id','=',$city_id->id],['type','=', 'land'],['price','<=', $max_budget],['status','=', 1]])->with(['media_imgs'])->get();
        //     return response(["properties"=>$properties])
        //                     ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
        //                     ->header('Access-Control-Allow-Origin', '*')
        //                     ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        // } else {
        //     $properties = Ad::where([['city_id','=',$city_id->id],['type','=', 'land'],['purpose','=', $sale_type],['price','<=', $max_budget],['status','=', 1]])->with(['media_imgs'])->get();
        //     return response(["properties"=>$properties, "city"=>$city])
        //                     ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token')
        //                     ->header('Access-Control-Allow-Origin', '*')
        //                     ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
                            // "properties"=>$properties,
        // }
    }
    
    public function markAsSold($id){
        $property = Ad::find($id);
        
        $property->sold = $property->sold == 0 ? 1 : 0;
        $property->save();
        return redirect()->back()->with('success', "Property Status Changed");
        
    }
    
    
    
}
