<?php

namespace App\Http\Controllers\Admin;

use Auth;
use App\Type;
use App\Location;
use App\Property;
use App\PropertyGallery;


use Illuminate\Http\Request;
use Session;
use Illuminate\Support\Str; 
use Intervention\Image\Facades\Image;

class PropertyController extends MainAdminController
{
	  
    public function list()
    { 
 
        if(Auth::User()->usertype!="Admin" AND Auth::User()->usertype!="Sub_Admin")
        {
            Session::flash('flash_message', trans('words.access_denied'));
            return redirect('dashboard');            
        }

        if(isset($_GET['s']))
        {
            $keyword = $_GET['s'];  
            $list = Property::where("title", "LIKE","%$keyword%")->with(['types', 'users'])->orderBy('title')->paginate(12);

            $list->appends(\Request::only('s'))->links();
        }
        else if(isset($_GET['type_id']) AND $_GET['type_id']!="")
        {   
            $type_id = $_GET['type_id'];

            $list = Property::where("type_id", $type_id)->with(['types', 'users'])->orderBy('title')->paginate(12);
  
            $list->appends(\Request::only('type_id'))->links();
        }
        else if(isset($_GET['location_id']) AND $_GET['location_id']!="")
        {   
            $location_id = $_GET['location_id'];

            $list = Property::where("location_id", $location_id)->with(['types', 'users'])->orderBy('title')->paginate(12);
  
            $list->appends(\Request::only('location_id'))->links();
        }      
        else
        {
            $list = Property::with(['types', 'users'])->orderBy('id','DESC')->paginate(12);
        }

        $page_title=trans('words.property_text');

        $type_list = Type::orderBy('type_name')->get();

        $location_list = Location::orderBy('name')->get();
          
        return view('admin.pages.property.list',compact('page_title','list','type_list','location_list'));
    }

    public function add()    
    {     
          if(Auth::User()->usertype!="Admin" AND Auth::User()->usertype!="Sub_Admin")
            {
                Session::flash('flash_message', trans('words.access_denied'));
                return redirect('dashboard');                
             }  

          $page_title=trans('words.add_property');

          $type_list = Type::orderBy('type_name')->get();

          $location_list = Location::orderBy('name')->get();
           
          return view('admin.pages.property.addedit',compact('page_title','type_list','location_list'));
        
    }

    public function edit($post_id)    
    {     
          if(Auth::User()->usertype!="Admin" AND Auth::User()->usertype!="Sub_Admin")
            {
                Session::flash('flash_message', trans('words.access_denied'));
                return redirect('dashboard');                
             }  

          $page_title=trans('words.edit_property');

          $info = Property::findOrFail($post_id);

          $gallery_images = PropertyGallery::where('post_id',$info->id)->orderBy('id')->get();

          $type_list = Type::orderBy('type_name')->get();  
          
          $location_list = Location::orderBy('name')->get();
        
          return view('admin.pages.property.addedit',compact('page_title','info','type_list','location_list','gallery_images'));
        
    }

    public function addnew(Request $request)
    {  
       
       $inputs = $request->all();
       $data = $request->all();
       
       if(!empty($inputs['id'])){
         $rule=array(
                'type' => 'required',
                'title' => 'required',
                'location' => 'required',
                'image' => 'required_without:image_file',
                'image_file' => 'nullable|mimes:jpg,jpeg,png,gif,webp',
                'floor_plan_image_file' => 'nullable|mimes:jpg,jpeg,png,gif,webp',
                'gallery_files.*' => 'nullable|mimes:jpg,jpeg,png,gif,webp'
                );
         
        }else
        {
            $rule=array(
                    'type' => 'required',
                    'title' => 'required',
                    'location' => 'required',
                    'image' => 'required_without:image_file',
                    'image_file' => 'required_without:image|mimes:jpg,jpeg,png,gif,webp',
                    'floor_plan_image_file' => 'nullable|mimes:jpg,jpeg,png,gif,webp',
                    'gallery_files.*' => 'nullable|mimes:jpg,jpeg,png,gif,webp'
                     );
        }

         
         $validator = \Validator::make($data,$rule);
 
        if ($validator->fails())
        {
                return redirect()->back()->withErrors($validator->messages());
        } 
        if(!empty($inputs['id'])){
           
            $data_obj = Property::findOrFail($inputs['id']);

        }else{

            $data_obj = new Property;

            $data_obj->user_id = Auth::User()->id;
        } 

        $title_slug = Str::slug($inputs['title'], '-',null);

        $main_image = $this->storeUploadedImage($request->file('image_file'), 'property');
        if (!$main_image) {
            $main_image = $this->normalizeImageInput($inputs['image'] ?? '');
        }

        $floor_plan_image = $this->storeUploadedImage($request->file('floor_plan_image_file'), 'floorplan');
        if (!$floor_plan_image) {
            $floor_plan_image = $this->normalizeImageInput($inputs['floor_plan_image'] ?? '');
        }
        
        $data_obj->type_id = $inputs['type']; 
        $data_obj->title = addslashes($inputs['title']);
        $data_obj->slug = $title_slug;
        $data_obj->description = addslashes($inputs['description']);
        $data_obj->phone = $inputs['phone']; 
        $data_obj->location_id = $inputs['location'];
        $data_obj->address = $inputs['address']; 
        $data_obj->latitude = $inputs['latitude']; 
        $data_obj->longitude = $inputs['longitude']; 
        $data_obj->purpose = $inputs['purpose']; 
        $data_obj->bedrooms = $inputs['bedrooms']; 
        $data_obj->bathrooms = $inputs['bathrooms']; 
        $data_obj->area = $inputs['area']; 
        $data_obj->furnishing = $inputs['furnishing']; 
        $data_obj->amenities = addslashes($inputs['amenities']);
        $data_obj->price = $inputs['price']; 
        $data_obj->verified = $inputs['verified']; 

        if ($main_image) {
            $data_obj->image = $main_image;
        } elseif (empty($inputs['id'])) {
            $data_obj->image = $inputs['image'];
        }

        if ($floor_plan_image) {
            $data_obj->floor_plan_image = $floor_plan_image;
        } elseif (!empty($inputs['floor_plan_image'])) {
            $data_obj->floor_plan_image = $inputs['floor_plan_image'];
        }
         
        $data_obj->status = $inputs['status']; 
        
        $data_obj->save();
        
        
            //News Gallery Image
            $gallery_items = array();
            if (!empty($inputs['image_gallery']) && is_array($inputs['image_gallery'])) {
                foreach ($inputs['image_gallery'] as $gallery_item) {
                    $gallery_item = $this->normalizeImageInput($gallery_item);
                    if ($gallery_item) {
                        $gallery_items[] = $gallery_item;
                    }
                }
            }

            if ($request->hasFile('gallery_files')) {
                foreach ($request->file('gallery_files') as $gallery_file) {
                    $stored = $this->storeUploadedImage($gallery_file, 'gallery');
                    if ($stored) {
                        $gallery_items[] = $stored;
                    }
                }
            }

            $gallery_items = array_values(array_unique($gallery_items));
            $gallery_count = count($gallery_items);
 
            if(!empty($inputs['id']))
            {
               $property_id= $inputs['id'];
            }
            else
            {
                $property_id= $data_obj->id; 
            }

            for($gallery_img=0; $gallery_img<$gallery_count; $gallery_img++)
            {  
                $gallery_obj = new PropertyGallery;
 
                if($gallery_items[$gallery_img] != '')
                {
                    $gallery_obj->post_id = $property_id; 
                    $gallery_obj->image = $gallery_items[$gallery_img];       
    
                    $gallery_obj->save();
                }
                
            }
         
 
        if(!empty($inputs['id'])){

            Session::flash('flash_message', trans('words.successfully_updated'));
            return \Redirect::back();

        }else{

            Session::flash('flash_message', trans('words.added'));
            return \Redirect::back();

        }   
    }

    public function generate()
    {
        if(Auth::User()->usertype!="Admin" AND Auth::User()->usertype!="Sub_Admin")
        {
            Session::flash('flash_message', trans('words.access_denied'));
            return redirect('dashboard');
        }

        $page_title = "Generate Properties";
        $type_list = Type::orderBy('type_name')->get();
        $location_list = Location::orderBy('name')->get();

        return view('admin.pages.property.generate', compact('page_title', 'type_list', 'location_list'));
    }

    public function generate_store(Request $request)
    {
        if(Auth::User()->usertype!="Admin" AND Auth::User()->usertype!="Sub_Admin")
        {
            Session::flash('flash_message', trans('words.access_denied'));
            return redirect('dashboard');
        }

        $data = $request->all();
        $rule = array(
            'count' => 'required|integer|min:1|max:200',
            'type_id' => 'required|exists:type,id',
            'purpose' => 'required|in:Sale,Rent',
            'price_min' => 'required|integer|min:1',
            'price_max' => 'required|integer|min:1',
            'location_id' => 'required|exists:location,id',
            'images' => 'required_without:image_files|string',
            'image_files' => 'required_without:images|array',
            'image_files.*' => 'nullable|mimes:jpg,jpeg,png,gif,webp'
        );

        $validator = \Validator::make($data, $rule);
        if ($validator->fails())
        {
            return redirect()->back()->withErrors($validator->messages())->withInput();
        }

        $price_min = (int) $data['price_min'];
        $price_max = (int) $data['price_max'];
        if ($price_min > $price_max)
        {
            return redirect()->back()->withErrors(['price_max' => 'Maximum price must be greater than or equal to minimum price.'])->withInput();
        }

        $images = $this->parseImageList($data['images'] ?? '');
        if ($request->hasFile('image_files')) {
            foreach ($request->file('image_files') as $image_file) {
                $stored = $this->storeUploadedImage($image_file, 'generator');
                if ($stored) {
                    $images[] = $stored;
                }
            }
        }
        $images = array_values(array_unique($images));
        if (count($images) == 0)
        {
            return redirect()->back()->withErrors(['images' => 'Please provide at least one valid image path or upload at least one image.'])->withInput();
        }

        $type = Type::findOrFail($data['type_id']);
        $location = Location::findOrFail($data['location_id']);
        $total = (int) $data['count'];

        $created = 0;
        for ($i = 0; $i < $total; $i++)
        {
            $title = $this->buildTitle($type->type_name, $location->name);
            $slug = Str::slug($title . '-' . Str::random(6), '-', null);
            $main_image = $this->randomFrom($images);
            $gallery_images = $this->pickGalleryImages($images, 1, 4);
            $coords = $this->buildCoordinates($location->name);

            $data_obj = new Property;
            $data_obj->user_id = Auth::User()->id;
            $data_obj->type_id = $type->id;
            $data_obj->location_id = $location->id;
            $data_obj->title = addslashes($title);
            $data_obj->slug = $slug;
            $data_obj->description = addslashes($this->buildDescription($type->type_name, $location->name));
            $data_obj->phone = $this->randomPhone();
            $data_obj->address = $this->buildAddress($location->name);
            $data_obj->latitude = $coords['lat'];
            $data_obj->longitude = $coords['lng'];
            $data_obj->purpose = $data['purpose'];
            $data_obj->bedrooms = (string) mt_rand(1, 5);
            $data_obj->bathrooms = (string) mt_rand(1, 4);
            $data_obj->area = mt_rand(600, 3500) . ' Sq-ft';
            $data_obj->furnishing = $this->randomFrom(array('Unfurnished', 'Semi-Furnished', 'Furnished'));
            $data_obj->amenities = $this->buildAmenities();
            $data_obj->price = mt_rand($price_min, $price_max);
            $data_obj->verified = 'YES';
            $data_obj->image = $main_image;
            $data_obj->floor_plan_image = $this->randomFrom($images);
            $data_obj->status = 1;
            $data_obj->save();

            foreach ($gallery_images as $gallery_image)
            {
                $gallery_obj = new PropertyGallery;
                $gallery_obj->post_id = $data_obj->id;
                $gallery_obj->image = $gallery_image;
                $gallery_obj->save();
            }

            $created++;
        }

        Session::flash('flash_message', $created . ' properties generated.');
        return redirect('admin/property');
    }

    private function parseImageList($raw)
    {
        $items = preg_split('/[,\r\n]+/', $raw);
        $images = array();
        foreach ($items as $item)
        {
            $path = trim($item);
            if ($path === '')
            {
                continue;
            }

            $path = str_replace('\\', '/', $path);
            if (Str::startsWith($path, array('http://', 'https://', '//')))
            {
                $images[] = $path;
                continue;
            }
            if (Str::startsWith($path, 'public/'))
            {
                $path = substr($path, 7);
            }

            $path = ltrim($path, '/');
            if (!file_exists(public_path($path)))
            {
                continue;
            }
            $images[] = $path;
        }

        return array_values(array_unique($images));
    }

    private function normalizeImageInput($path)
    {
        if (!is_string($path)) {
            return null;
        }

        $path = trim($path);
        if ($path === '') {
            return null;
        }

        if (Str::startsWith($path, array('http://', 'https://', '//'))) {
            return $path;
        }

        $path = str_replace('\\', '/', $path);
        if (Str::startsWith($path, 'public/')) {
            $path = substr($path, 7);
        }

        return ltrim($path, '/');
    }

    private function storeUploadedImage($file, $prefix)
    {
        if (!$file) {
            return null;
        }

        $tmpFilePath = public_path('/upload/');
        $name = $prefix . '-' . md5(time() . rand(1000, 9999));
        $extension = strtolower($file->getClientOriginalExtension());
        if ($extension === '') {
            $extension = 'jpg';
        }

        $filename = $name . '.' . $extension;
        $img = Image::make($file);
        $img->save($tmpFilePath . $filename);

        return 'upload/' . $filename;
    }

    private function randomFrom(array $items)
    {
        return $items[array_rand($items)];
    }

    private function pickGalleryImages(array $images, $min, $max)
    {
        $max = min($max, count($images));
        $min = min($min, $max);
        $count = mt_rand($min, $max);
        $shuffled = $images;
        shuffle($shuffled);
        return array_slice($shuffled, 0, $count);
    }

    private function buildTitle($type_name, $location_name)
    {
        $adjectives = array('Modern', 'Cozy', 'Spacious', 'Bright', 'Classic', 'Luxury', 'Quiet', 'Urban', 'Charming', 'Elegant');
        $suffixes = array('Home', 'Residence', 'Estate', 'Retreat', 'Place', 'House', 'Suite');
        $number = mt_rand(100, 999);
        return $adjectives[array_rand($adjectives)] . ' ' . $type_name . ' ' . $suffixes[array_rand($suffixes)] . ' in ' . $location_name . ' ' . $number;
    }

    private function buildDescription($type_name, $location_name)
    {
        return "Well maintained " . $type_name . " located in " . $location_name . ". Close to local amenities and public transport.";
    }

    private function buildAddress($location_name)
    {
        $street_names = array('Main', 'Oak', 'Pine', 'Maple', 'Cedar', 'Hill', 'Park', 'Lake', 'Sunset', 'Garden');
        $street_types = array('St', 'Ave', 'Rd', 'Blvd', 'Ln');
        return mt_rand(10, 999) . ' ' . $street_names[array_rand($street_names)] . ' ' . $street_types[array_rand($street_types)] . ', ' . $location_name;
    }

    private function randomPhone()
    {
        return '9' . mt_rand(100000000, 999999999);
    }

    private function buildAmenities()
    {
        $amenities = array('Parking', 'Balcony', 'Gym', 'Pool', 'Security', 'Internet', 'Lift', 'Garden', 'CCTV', 'Air conditioning');
        shuffle($amenities);
        $count = mt_rand(3, 6);
        return implode(',', array_slice($amenities, 0, $count));
    }

    private function buildCoordinates($location_name)
    {
        $map = array(
            'London' => array(51.5074, -0.1278),
            'New York' => array(40.7128, -74.0060),
            'Paris' => array(48.8566, 2.3522),
            'Tokyo' => array(35.6762, 139.6503)
        );

        foreach ($map as $key => $coords)
        {
            if (Str::contains($location_name, $key))
            {
                $lat = $coords[0] + (mt_rand(-200, 200) / 1000);
                $lng = $coords[1] + (mt_rand(-200, 200) / 1000);
                return array('lat' => $lat, 'lng' => $lng);
            }
        }

        $lat = mt_rand(-55000, 55000) / 1000;
        $lng = mt_rand(-170000, 170000) / 1000;
        return array('lat' => $lat, 'lng' => $lng);
    }
  
}
