<?php

class AjaxSearchController extends BaseController
{
    private $json;

    public function __construct()
    {
        $this->json = [
            'status'  => false,
            'message' => []
        ];
    }

    public function search()
    {
        $analyze = new AnalyzeService();
        $analyzeResponse = $analyze->prepare(Input::get('url'));



        if($analyzeResponse['status'] == true){
            $this->json['status'] = true;
            if(isset($analyzeResponse['redirect'])){
                $this->json['redirect'] = $analyzeResponse['redirect'];
            }else{
                $this->json['protocol'] = $analyzeResponse['protocol'];
                $this->json['hash'] = $analyzeResponse['hash'];
                $this->json['name'] = $analyzeResponse['name'];
            }
        }else{
            $this->json['message'] = $analyzeResponse['message'];
        }

        return $this->send();
    }

    public function reAnalyze()
    {
        $siteName = Input::get('site');

        $reAnalyze = new AnalyzeService();
        $reAnalyzeResponse = $reAnalyze->prepareReAnalyze($siteName);

        if($reAnalyzeResponse['status']){
            $this->json['hash'] = $reAnalyzeResponse['hash'];
            $this->json['protocol'] = $reAnalyzeResponse['protocol'];
            $this->json['name'] = $reAnalyzeResponse['name'];
            $this->json['status'] = true;
        }else{
            $this->json['message'] = $reAnalyzeResponse['message'];
        }

        return $this->send();

    }

    public function autoCompleteSearch($s)
    {

        $s = trim(urldecode($s));
        $s = str_replace('https://', '', $s);
        $s = str_replace('http://', '', $s);
        $s = str_replace('www.', '', $s);

        $searchResults = HSearch::getWebsite($s);
        $siteResults = [];

        if ($searchResults) {
            $this->json['status'] = true;
            foreach ($searchResults as $site) {

                if($site->alexa_rank > 0){
                    $alexaRank = '#' . standard_number($site->alexa_rank);
                }else{
                    $alexaRank = 'no-data';
                }

                $siteResults[] = [
                    'favicon'    => 'http://s2.googleusercontent.com/s2/favicons?domain_url=' . $site->name,
                    'name'       => $site->name,
                    'detail_url' => route('site.name', [$site->name]),
                    'alexa'      => $alexaRank
                ];
            }
        }

        $this->json['results'] = $siteResults;

        return $this->send();

    }

    private function send()
    {
        return json_encode($this->json);
    }
}