<?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 DB;
use Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

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

    /** 
     * 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)
    {
        // $file = storage_path('app/key/apikey.dba');
        /*$file = Storage::disk('public')->path('key/apikey.dba');
        dd($file);
        
        if (!is_file($file)) {
			$fh = fopen($file, 'w') or $this->traceLog('Code Error #: Unable to create .dba file');
        }
        die($fh);*/

        $api_url = config('app.api_list');
        $apiLocaterData = $this->call_api('',$api_url);

        if ( count($apiLocaterData['data']) < 1 ) return '';

        $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'];

        $homepage = Homepage::where('homepages.status', '=', '1')->first();

        return view('frontend.searchs.index', compact('homepage','finalData','links','meta'));
    }

    /** 
     * For render location list after searching  
     * */
    public function searchlocator(Request $request)
    {
        $api_url = config('app.api_list');
        
        $apiLocaterData = $this->call_api_page($api_url,$request->locality,$request->page);
        
        if ( count($apiLocaterData['data']) < 1 ) return '';

        $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'];
        $locality = $request->locality;
        //print_r($links);
        
        return view('frontend.searchs.location_element', compact('finalData','links','locality','meta'));
    }

    /** 
     * 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($locatorID,$api_url);
        
        $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($request['query'],$api_url);    
        
        return view('frontend.searchs.autocomplete', compact('locationDetailAPIdata'));
    }
    
}
