<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Homepage;
use App\Helpers\Apihelpers;
use App\Traits\Apitraits;
use App\Locater;
use App\Page;
use App\City;
use DB;
use Validator;
use Illuminate\Support\Facades\Hash;


class SearchController extends Controller
{
    use Apitraits;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
       
    }

    private function getApiData($locality=null, $state=null, $city=null, $location=null, $page=null){

        $api_url = config('app.api_list');
        
        $apiLocaterData = $this->call_api_page($api_url, $locality, $state, $city, $location, $page);

        if ( count($apiLocaterData['data']) < 1 )
        return response()->json(['status' => 'error', 'data' => 'No data found!']);

        $locaterIds = collect($apiLocaterData['data'])->pluck('id'); 
        
        $locaterData = Locater::whereIn('locater_identity', $locaterIds)
                ->with(array('page'=> function ($query) {
                    $query->select(['locater_id', 'title', 'slug']);
                }))
                ->get();

        $locaterData = !empty($locaterData) ? $locaterData->groupBy('locater_identity') : [];   
        
        $finalData = array_map(function ($data) use ($locaterData) {
            $data['slug'] = null;
            
            if ( count($locaterData) < 1 ) return $data;
            if ( isset($locaterData[$data['id']]) ) {
                $data['name'] = $locaterData[$data['id']][0]->name;
                $data['slug'] = $locaterData[$data['id']][0]->page->slug ?? null;
            }
        
            return $data;
        }, $apiLocaterData['data']);

        $links = $apiLocaterData['links'];
        $meta = $apiLocaterData['meta'];

        $data = array();
        $data['finalData'] = $finalData;
        $data['links'] = $links;
        $data['meta'] = $meta;
        return response()->json([
            'status' => 'success',
            'data' => $data
        ]);
    
    }

    /** 
     * For Rendring index page first time and FetchData in DataBase and ApiData then Match both Data Then show final array with slug
     * 
     * */

    public function index(Request $request)
    {
        $detail = $this->getApiData();
        $final = $detail->original;
        
        if($final['status'] == 'success'){
           
            $finalData = $final['data']['finalData'];
            $links = $final['data']['links'];
            $meta = $final['data']['meta'];
            $getState = City::where('parent_id', '=', '1')->where('type', '=', '2')->get()->toarray();
           
            return view('frontend.searchs.index', compact('finalData','links','meta','getState'));

        }else{
            return response()->json(['status' => 'error', 'data' => 'No data found!']);
        }
    }

    /** 
     * For render location list after searching  
     * */
    public function searchlocater(Request $request)
    {
        $detail = $this->getApiData($request['locality'], $request['state'], $request['city'], $request['location'], $request['page']);
        $final = $detail->original;
        
        if($final['status'] == 'success'){

            $finalData = $final['data']['finalData'];
            $links = $final['data']['links'];
            $meta = $final['data']['meta'];

            $locality = $request->locality;
            $state = $request->state;
            $city = $request->city;
            $location = $request->location;

            $html = view('frontend.searchs.location_element', compact('finalData', 'links', 'locality','state','city', 'location', 'meta'))->render();
            return response()->json([
                'status' => 'success',
                'data' => $html
            ]);
            
        }else{

            $html = view('frontend.searchs.location_element', compact('finalData', 'links', 'locality','state','city', 'location', 'meta'))->render();
            return response()->json(['status' => 'error', 'data' => $html]);

        }
    }


    /** 
     * For render detail page 
     * */
    public function detail(Request $request, $slug) 
    {
        $pageData = Page::where('pages.slug', '=', $slug)
                ->with(array('locaterlists' => function ($query){
                    $query->select(['locater_identity', 'id']);
                }))
                ->first();
        
        /*Fetch Locater ID*/ 
        $locatorID = $pageData->locaterlists->locater_identity;

        $api_url = config('app.api_location');
        $locationDetailAPIdata = $this->call_api($api_url,$locatorID);
        
        $homepage = Homepage::where('homepages.status', '=', '1')->first();
        return view('frontend.searchs.detail', compact('homepage','locatorID','locationDetailAPIdata','pageData'));
    }

    
    /*For showing autocomplete result in index page*/
    public function autocomplete(Request $request)
    {
        $api_url = config('app.api_search');
        $locationDetailAPIdata = $this->call_api_page($api_url,$request['query']);   
        
        if(empty($locationDetailAPIdata['data'])){

            $html = view('frontend.searchs.autocomplete', compact('locationDetailAPIdata'))->render();
            return response()->json([
                'status' => 'error',
                'data' => $html
            ]);

        }else{

            $html = view('frontend.searchs.autocomplete', compact('locationDetailAPIdata'))->render();
            return response()->json([
                'status' => 'success',
                'data' => $html
            ]);
            
        }
    }


    /** 
     * For render Review ajax 
     * */
    public function reviewpaginate(Request $request)
    {
        $api_url = config('app.api');

        $reviewData = $this->review_api_detail($api_url,$request->locatorID,$request->page);
        
        if ( count($reviewData['data']) < 1 ) return '';

        return view('frontend.searchs.review_element', compact('reviewData'));
    }


    /** 
     * For render location list after searching  
     * */
    public function getCityValue(Request $request)
    {
        $getCityData = City::where('cities.name', '!=', '')->where('cities.parent_id', '=', $request->state)->pluck('name','id')->toarray();
        
        if(!empty($getCityData)){

            $html = view('frontend.searchs.city_dropdown', compact('getCityData'))->render();
            return response()->json([
                'status' => 'success',
                'data' => $html
            ]);
            
        }else{

            $html = view('frontend.searchs.city_dropdown', compact('getCityData'))->render();
            return response()->json(['status' => 'error', 'data' => $html]);

        }
    }
    
}
