<?php

class SearchController extends BaseController
{

    public function initialize($hash)
    {

        $analyze = new AnalyzeService();
        $analyzeResponse = $analyze->save($hash);

        if($analyzeResponse['status'] == true){
            return Redirect::route('site.name', [$analyzeResponse['name']]);
        }else{
            Session::flash('error', $analyzeResponse['message']);
            return Redirect::route('index');
        }

    }


    public function index($name)
    {

        $siteData = WebSite::getSiteByName($name);

        if (!$siteData) {
            $form = true;
            $socialEnabled = true;
            return View::make('404')
                ->with('title', DBLang::get('not_found_site_title'))
                ->with('message', DBLang::get('not_found_site_desc'))
                ->with('form', $form)
                ->with('site', $name)
                ->with('socialEnabled', $socialEnabled);
        }

        if ($siteData->meta == '' || $siteData->search == '' || $siteData->html == '' || $siteData->social == '' || $siteData->dmoz == '' || $siteData->alexa == '' || $siteData->whois == '' || $siteData->color == ''){
            Session::flash('error', 'Analysis was abandoned at half. Please re-analyze.');
            return Redirect::route('index');
        }

        $metaData = unserialize(base64_decode($siteData->meta));
        $searchData = unserialize(base64_decode($siteData->search));
        $htmlData = unserialize(base64_decode($siteData->html));
        $socialData = unserialize(base64_decode($siteData->social));
        $dmozData = unserialize(base64_decode($siteData->dmoz));
        $alexaData = unserialize(base64_decode($siteData->alexa));
        $whoisData = unserialize(base64_decode($siteData->whois));
        $colorData = unserialize(base64_decode($siteData->color));
        $comments = Comment::getAll($siteData->id);

        /* İç link limitleme */
        $htmlData['internal_links_count'] = count($htmlData['internal_links']);
        if ($htmlData['internal_links_count'] > 50) {
            $htmlData['internal_links'] = array_slice($htmlData['internal_links'], 1, 50);
        }

        // META KEYWORDS DAĞILIMI
        $keywordDensity = array();
        if ($metaData['site_keywords']) {
            $keywordsText = str_replace('，', ',', $metaData['site_keywords']);
            $keywords = explode(',', $keywordsText);

            $keywords = array_map(function($text){
                return trim(strtolower_tr($text));
            }, $keywords);

            $keywords = array_unique($keywords);
            $keywords = array_diff($keywords, ['', ' ']);
            $counter = 0;

            foreach ($keywords as $key) {

                if(count($keywordDensity) == 50){
                    break;
                }

                $websiteCount = Keyword::keywordCount($key);
                if($websiteCount > 1){
                    $keywordDensity[] = [
                            'keyword'       => firstUpperCase($key),
                            'website_count' => $websiteCount,
                            'color'         => Config::get('app.colors')[$counter]
                    ];
                    $counter++;
                }
            }
        }



        // HTML Title Tag Data
        $htmlTitleTags = [
            'h1'       => [
                'count' => count($htmlData['h1_tags']),
                'tags'  => array_group($htmlData['h1_tags'])
            ],
            'h2'       => [
                'count' => count($htmlData['h2_tags']),
                'tags'  => array_group($htmlData['h2_tags'])
            ],
            'h3'       => [
                'count' => count($htmlData['h3_tags']),
                'tags'  => array_group($htmlData['h3_tags'])
            ],
            'h4'       => [
                'count' => count($htmlData['h4_tags']),
                'tags'  => array_group($htmlData['h4_tags'])
            ],
            'h5'       => [
                'count' => count($htmlData['h5_tags']),
                'tags'  => array_group($htmlData['h5_tags'])
            ],
            'h6'       => [
                'count' => count($htmlData['h6_tags']),
                'tags'  => array_group($htmlData['h6_tags'])
            ]
        ];

        $htmlStyleTags = [
            'strong'       => [
                'count' => count($htmlData['strong_tags']),
                'tags' => array_group($htmlData['strong_tags'])
            ],
            'b'            => [
                'count' => count($htmlData['b_tags']),
                'tags' => array_group($htmlData['b_tags'])
            ],
            'em'           => [
                'count' => count($htmlData['em_tags']),
                'tags' => array_group($htmlData['em_tags'])
            ],
            'i'            => [
                'count' => count($htmlData['i_tags']),
                'tags' => array_group($htmlData['i_tags'])
            ],
            'u'            => [
                'count' => count($htmlData['u_tags']),
                'tags' => array_group($htmlData['u_tags'])
            ],
            'cite'         => [
                'count' => count($htmlData['cite_tags']),
                'tags' => array_group($htmlData['cite_tags'])
            ],
        ];

        if ($alexaData['top_countries']) {
            $totalCountries = 0;
            foreach ($alexaData['top_countries'] as $index => $country) {
                $totalCountries += str_replace('%', '', $country['ratio']);
            }

            if ($totalCountries < 100) {
                $alexaData['top_countries'][] = [
                    'name'  => 'Other',
                    'ratio' => number_format(100 - $totalCountries, 1) . '%',
                    'rank'  => 0
                ];
            }
        }

        $alexaData['top_countries_count'] = count($alexaData['top_countries']);

        $htmlData['code_text_ratio'] = number_format($htmlData['code_text_ratio'],2);

        $htmlData['responsive_support'] = 0;
        if ($metaData['others']) {
            foreach ($metaData['others'] as $meta) {
                if (strtolower($meta['name']) == 'viewport') {
                    $htmlData['responsive_support'] = 1;
                }
            }
        }

        if (isset($searchData['google_page_speed_score'])){
            $searchData['google_page_speed_value'] = '';
            if($searchData['google_page_speed_score']){
                if($searchData['google_page_speed_score'] < 26){
                    $searchData['google_page_speed_value'] = DBLang::get('page_speed_very_slow');
                }
                elseif($searchData['google_page_speed_score'] < 51){
                    $searchData['google_page_speed_value'] = DBLang::get('page_speed_slow');
                }
                elseif($searchData['google_page_speed_score'] < 76){
                    $searchData['google_page_speed_value'] = DBLang::get('page_speed_normal');
                }
                elseif($searchData['google_page_speed_score'] < 96){
                    $searchData['google_page_speed_value'] = DBLang::get('page_speed_fast');
                }
                elseif($searchData['google_page_speed_score'] <= 100){
                    $searchData['google_page_speed_value'] = DBLang::get('page_speed_fast');
                }
            }
        }

        $adsenseUsedSites = [];
        if ($siteData['google_adsense_id']) {
            $adsenseUsedSites = Website::getSitesByAdsense($siteData['google_adsense_id']);
        }

        $sameIpAddressSites = [];
        $cClassIpAddressSites = [];

        if ($siteData['ip_address']) {
            $sameIpAddressSites = WebSite::getSitesByIpAddress($siteData['ip_address']);
            $cClassIpAddressSites = Website::getSitesByCClassIpAddress($siteData['ip_address']);
        }

        return View::make('detail')
            ->with('name', $siteData['name'])
            ->with('id', $siteData['id'])
            ->with('metaData', $metaData)
            ->with('siteData', $siteData)
            ->with('keywordDensity', $keywordDensity)
            ->with('searchData', $searchData)
            ->with('htmlData', $htmlData)
            ->with('colorData', $colorData)
            ->with('htmlTitleTags', $htmlTitleTags)
            ->with('htmlStyleTags', $htmlStyleTags)
            ->with('socialData', $socialData)
            ->with('dmozData', $dmozData)
            ->with('alexaData', $alexaData)
            ->with('whoisData', $whoisData)
            ->with('adsenseUsedSites', $adsenseUsedSites)
            ->with('sameIpAddressSites', $sameIpAddressSites)
            ->with('cClassIpAddressSites', $cClassIpAddressSites)
            ->with('comments', $comments);
    }


}