<?php

namespace App\Http\Controllers\SEO_tools;


use Mpdf\Mpdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\HomeController;
use App\Services\Custom\WebCommonReportServiceInterface;



class WebsiteController extends HomeController 
{

    public function __construct(WebCommonReportServiceInterface $web_common_repport)
    {
        $this->web_repport= $web_common_repport;
        $this->set_global_userdata(true,[],[],2);
    }


    public function website_analysis()
    {
        $has_google_api = false;
        $use_admin_app = config('my_config.use_admin_app');
        if($use_admin_app == '' || $use_admin_app == 'no')
          $config_data =DB::table('config')->where('user_id',Auth::user()->id)->first();
        else{
          $config_data = DB::table('config')->where('access','all_users')->first();
        }
        if(isset($config_data)) {
            if($config_data->google_safety_api != "") {
                $has_google_api = true;
            }
        }
        $data['has_google_api'] = $has_google_api;
        $data['body'] = "seo-tools.analysis-tools.website.website-analysis";
        return $this->_viewcontroller($data); 
    }

    public function website_analysis_lists_data(Request $request)
    {

        $domain_name = trim($request->input("domain_name"));
        $post_date_range = $request->input("post_date_range");

        $display_columns = array("#",'CHECKBOX','id','domain_name','search_from','search_at','actions');
        $search_columns = ['domain_name','search_at'];

        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $start = isset($_POST['start']) ? intval($_POST['start']) : 0;
        $limit = isset($_POST['length']) ? intval($_POST['length']) : 10;
        $sort_index = isset($_POST['order'][0]['column']) ? strval($_POST['order'][0]['column']) : 2;
        $sort = isset($display_columns[$sort_index]) ? $display_columns[$sort_index] : 'id';
        $order = isset($_POST['order'][0]['dir']) ? strval($_POST['order'][0]['dir']) : 'desc';
        $order_by=$sort." ".$order;

        $from_date = $to_date = "";
        if($post_date_range!="")
        {
            $exp = explode('|', $post_date_range);
            $from_date = isset($exp[0])?$exp[0]:"";
            $to_date   = isset($exp[1])?$exp[1]:"";

        }

        $user_id = Auth::user()->id;
        $table = "website_analysis_info";
        $query = DB::table($table);
        if($from_date!='') $query->where("search_at", ">=", $from_date);
        if($to_date!='') $query->where("search_at", "<=", $to_date);

        if ($domain_name != '')
        {
            $query->where(function($query) use ($search_columns,$domain_name){
                foreach ($search_columns as $key => $value) $query->orWhere($value, 'like',  "%$domain_name%");
            });
        }
        $query->where(function($query) use ($user_id){
            if(session('user_type') == 'Admin'){
            $query->Where('website_analysis_info.user_id', '=', $user_id);
            $query->orWhere('website_analysis_info.user_id', '=', 0);
            }
            else{
                $query->Where('website_analysis_info.user_id', '=', $user_id);
            }
        });

        $select = array("id","user_id","domain_name","search_at");

        $table = "website_analysis_info";

        $info = $query->select("id","user_id","domain_name","search_at")->orderByRaw($order_by)->offset($start)->limit($limit)->get();
        
        $query = DB::table($table);
        $query->where(function($query) use ($user_id){
            if(session('user_type') == 'Admin'){
            $query->Where('website_analysis_info.user_id', '=', $user_id);
            $query->orWhere('website_analysis_info.user_id', '=', 0);
            }
            else{
                $query->Where('website_analysis_info.user_id', '=', $user_id);
            }
        });

        $total_result=$query->count();

        for ($i=0; $i < count($info) ; $i++) {

            if($info[$i]->search_at != "0000-00-00 00:00:00") {

                $info[$i]->search_at = "<div style='min-width:140px !important;' class='text-center'>".date("M j, Y h:i A",strtotime($info[$i]->search_at))."</div>";
            } else {

                $info[$i]->search_at = "<div class='text-muted text-center'><i class='fas fa-times'></i></div>";
            }

            if($info[$i]->user_id == 0) {
                $info[$i]->search_from = '<div class="badge badge-warning">'.__('Frontend').'</div>';
            } else {
                $info[$i]->search_from = '<div class="badge badge-primary">'.__('Application').'</div>';

            }

            $view_url = url('/website_analysis/analysis_report/').'/'.$info[$i]->id;
            $download_url = url('/website_analysis/download_analysis_report/').'/'.$info[$i]->id;

            $info[$i]->actions = "<div><a href='".$view_url."' title='".__("View Report")."' class='btn btn-outline-primary btn-circle'><i class='fa fa-eye'></i></a>&nbsp;&nbsp;";

            $info[$i]->actions .= "<a target='_BLANK' href='$download_url' title='".__("Download Report")."' class='btn btn-outline-success btn-circle'><i class='fa fa-cloud-download'></i></a>&nbsp;&nbsp;";

            $info[$i]->actions .= "<a href='#' title='".__("Delete Report")."' class='btn btn-outline-danger delete_domain btn-circle' table_id='".$info[$i]->id."'><i class='fa fa-trash-alt'></i></a></div>
                <script>$('[data-toggle=\"tooltip\"]').tooltip();</script>";
        }

        $data['draw'] = (int)$_POST['draw'] + 1;
        $data['recordsTotal'] = $total_result;
        $data['recordsFiltered'] = $total_result;
        $data['data'] = convertDataTableResult($info, $display_columns ,$start,$primary_key="id");

        echo json_encode($data);
        
    }

    public function analysis_report($id=0)
    {

        $data['id'] = $id;

        $domain_info = DB::table('website_analysis_info')->where('id',$id)->get();
        $domain_info= json_decode(json_encode($domain_info));
        $data['country_list'] =get_country_names();
        $data['domain_info'] = $domain_info;
        $data['body'] = "seo-tools.analysis-tools.website.analysis-report";
        return $this->_viewcontroller($data); 
    }


    public function ajax_domain_analysis_action(Request $request)
    {
        
        if ($request->isMethod('get')) {
            return redirect()->route('access_forbidden');
        }

        $completed_function_str = '';
        $domain_name = strip_tags(strtolower($request->input('domain_name')));
        $user_id = Auth::user()->id; 

        $status=$this->_check_usage($module_id=2,$req=1);

        if($status=="2") 
        {
            echo __("sorry, your bulk limit is exceeded for this module.")."<a href='".url('/payment/usage_history')."'>".__("click here to see usage log")."</a>";
            exit();
        }
        else if($status=="3") 
        {
            echo __("sorry, your monthly limit is exceeded for this module.")."<a href='".url('/payment/usage_history')."'>".__("click here to see usage log")."</a>";
            exit();
        }

        $common_result['user_id'] = $user_id;
        $common_result['domain_name'] = $domain_name;
        $common_result['search_at'] = date("Y-m-d G:i:s");

        $api_key=DB::table('config')->select('config.mobile_ready_api_key','config.moz_secret_key','config.moz_access_id','config.google_safety_api')->first();

        $use_admin_app = config('my_config.use_admin_app');
        if($use_admin_app == '' || $use_admin_app == 'no')
            $config_data= DB::table('config')->where("user_id",Auth::user()->id)->first();
        else
            $config_data= DB::table('config')->where("access",'all_users')->first();

        $moz_access_id="";
        $moz_secret_key="";
        $mobile_ready_api_key="";
        $api = "";
        if(isset($config_data))
        {
            $moz_access_id=$api_key->moz_access_id;
            $moz_secret_key=$api_key->moz_secret_key;
            $mobile_ready_api_key=$api_key->mobile_ready_api_key;
            $api=$api_key->google_safety_api;
        }

        
        // Getting screenshot from page speed insight
        $domain=addHttp($domain_name);
        $desktop_result=$this->web_repport->google_page_speed_insight($api,$domain,"desktop");
         
        if (isset($desktop_result['error'])) {
            $common_result['screenshot_error'] = $desktop_result['error']['message'];
        }
        else{

           $common_result['screenshot'] = isset($desktop_result['lighthouseResult']['audits']['final-screenshot']['details']['data']) ? $desktop_result['lighthouseResult']['audits']['final-screenshot']['details']['data'] : "";
        }            
        
        $ready_data = $this->web_repport->mobile_ready($domain_name,$mobile_ready_api_key);            
            
        if (isset($ready_data['error'])) {
            $common_result['google_api_error'] = $ready_data['error']['message'];
        }
        else {
            if (isset($ready_data['loadingExperience'])) {
                $common_result["loadingexperience_metrics"] =  isset($ready_data['loadingExperience']) ? json_encode($ready_data['loadingExperience']) : "";
            }
            if (isset($ready_data['originLoadingExperience'])) {
                $common_result["originloadingexperience_metrics"] =  isset($ready_data['originLoadingExperience']) ? json_encode($ready_data['originLoadingExperience']) : "";
            }
            if (isset($ready_data['lighthouseResult']['configSettings'])) {
               $common_result["lighthouseresult_configsettings"] =  isset($ready_data['lighthouseResult']['configSettings']) ? json_encode($ready_data['lighthouseResult']['configSettings']) : "";
            }

            if (isset($ready_data['lighthouseResult']['audits'])) {
                if(isset($ready_data['lighthouseResult']['audits']['resource-summary']))
                    unset($ready_data['lighthouseResult']['audits']['resource-summary']['details']);

                if (isset($ready_data['lighthouseResult']['audits']['efficient-animated-content']))
                    unset($ready_data['lighthouseResult']['audits']['efficient-animated-content']['details']);

                if (isset($ready_data['lighthouseResult']['audits']['metrics']))
                    unset($ready_data['lighthouseResult']['audits']['metrics']);   

                if (isset($ready_data['lighthouseResult']['audits']['network-server-latency']))
                    unset($ready_data['lighthouseResult']['audits']['network-server-latency']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['offscreen-images']))
                    unset($ready_data['lighthouseResult']['audits']['offscreen-images']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['uses-responsive-images']))
                    unset($ready_data['lighthouseResult']['audits']['uses-responsive-images']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['unused-css-rules']))
                    unset($ready_data['lighthouseResult']['audits']['unused-css-rules']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['total-byte-weight']))
                    unset($ready_data['lighthouseResult']['audits']['total-byte-weight']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['mainthread-work-breakdown']))
                    unset($ready_data['lighthouseResult']['audits']['mainthread-work-breakdown']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['uses-webp-images']))
                    unset($ready_data['lighthouseResult']['audits']['uses-webp-images']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['critical-request-chains']))
                    unset($ready_data['lighthouseResult']['audits']['critical-request-chains']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['dom-size']))
                    unset($ready_data['lighthouseResult']['audits']['dom-size']['details']);                

                if (isset($ready_data['lighthouseResult']['audits']['unminified-javascript']))
                    unset($ready_data['lighthouseResult']['audits']['unminified-javascript']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['redirects']))
                    unset($ready_data['lighthouseResult']['audits']['redirects']['details']);   

                if (isset($ready_data['lighthouseResult']['audits']['time-to-first-byte']))
                    unset($ready_data['lighthouseResult']['audits']['time-to-first-byte']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['render-blocking-resources']))
                    unset($ready_data['lighthouseResult']['audits']['render-blocking-resources']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['font-display']))
                    unset($ready_data['lighthouseResult']['audits']['font-display']['details']);

                if (isset($ready_data['lighthouseResult']['audits']['estimated-input-latency']))
                    unset($ready_data['lighthouseResult']['audits']['estimated-input-latency']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['uses-rel-preconnect']))
                    unset($ready_data['lighthouseResult']['audits']['uses-rel-preconnect']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['unminified-css']))
                    unset($ready_data['lighthouseResult']['audits']['unminified-css']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['bootup-time']))
                    unset($ready_data['lighthouseResult']['audits']['bootup-time']['details']);                

                if (isset($ready_data['lighthouseResult']['audits']['uses-rel-preload']))
                    unset($ready_data['lighthouseResult']['audits']['uses-rel-preload']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['user-timings']))
                    unset($ready_data['lighthouseResult']['audits']['user-timings']['details']);                

                if (isset($ready_data['lighthouseResult']['audits']['uses-text-compression']))
                    unset($ready_data['lighthouseResult']['audits']['uses-text-compression']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['uses-optimized-images']))
                    unset($ready_data['lighthouseResult']['audits']['uses-optimized-images']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['uses-long-cache-ttl']))
                    unset($ready_data['lighthouseResult']['audits']['uses-long-cache-ttl']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['third-party-summary']))
                    unset($ready_data['lighthouseResult']['audits']['third-party-summary']['details']);                
                if (isset($ready_data['lighthouseResult']['audits']['network-rtt']))
                    unset($ready_data['lighthouseResult']['audits']['network-rtt']['details']);                

                if (isset($ready_data['lighthouseResult']['audits']['diagnostics']))
                    unset($ready_data['lighthouseResult']['audits']['diagnostics']);                

                if (isset($ready_data['lighthouseResult']['audits']['network-requests']))
                    unset($ready_data['lighthouseResult']['audits']['network-requests']['details']);                

                if (isset($ready_data['lighthouseResult']['audits']['screenshot-thumbnails']))
                    unset($ready_data['lighthouseResult']['audits']['screenshot-thumbnails']);                

                if (isset($ready_data['lighthouseResult']['audits']['main-thread-tasks']))
                    unset($ready_data['lighthouseResult']['audits']['main-thread-tasks']);

                if (isset($ready_data['lighthouseResult']['categories']['performance']))
                    unset($ready_data['lighthouseResult']['categories']['performance']['auditRefs']);                
                
                $common_result['lighthouseresult_audits'] = isset($ready_data['lighthouseResult']['audits']) ? json_encode($ready_data['lighthouseResult']['audits']) : "";                   

            }

            if (isset($ready_data['lighthouseResult']['categories'])) {
                $common_result['lighthouseresult_categories'] = isset($ready_data['lighthouseResult']['categories']) ? json_encode($ready_data['lighthouseResult']['categories']) : "";
            }
                
        }
        //for dynamic progress bar data
        $add_complete = 0;
        $common_result['completed_step_count'] = $add_complete;
        $common_result['completed_step_string'] = '';
        $search_existing_info = DB::table('website_analysis_info')->where('user_id', $user_id)->where('domain_name', $domain_name)->get();

        if(!isset($search_existing_info) || count($search_existing_info) == 0)
        {

            $web_common_info_id = DB::table('website_analysis_info')->insertGetId($common_result); 

        }
        else
        {
            DB::table('website_analysis_info')->where('id',$search_existing_info[0]->id)->update($common_result);

            $web_common_info_id = $search_existing_info[0]->id;            
        }
        //***************************************//
        // insert data to useges log table
        $this->_insert_usage_log($module_id=2,$req=1);
        //***************************************//        
 
        // get moz info

 
        $get_moz_info = $this->web_repport->get_moz_info($domain_name,$moz_access_id, $moz_secret_key);
        $common_result['moz_subdomain_normalized'] = $get_moz_info['mozrank_subdomain_normalized'];
        $common_result['moz_subdomain_raw'] = $get_moz_info['mozrank_subdomain_raw'];
        $common_result['moz_url_normalized'] = $get_moz_info['mozrank_url_normalized'];
        $common_result['moz_url_raw'] = $get_moz_info['mozrank_url_raw'];
        $common_result['moz_http_status_code'] = $get_moz_info['http_status_code'];
        $common_result['moz_domain_authority'] = $get_moz_info['domain_authority'];
        $common_result['moz_page_authority'] = $get_moz_info['page_authority'];
        $common_result['moz_external_equity_links'] = $get_moz_info['external_equity_links'];
        $common_result['moz_links'] = $get_moz_info['links'];
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". MOZ ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);
        // end of get moz info

        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Mobile Friendly ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);
        // end of get mobile ready

        
        $backlink_count=$common_result['moz_external_equity_links'];
        if($backlink_count=="")
            $backlink_count=0;
            
        $common_result['google_back_link_count'] = number_format($backlink_count);
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Backlink ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);
        
        $common_result['yahoo_back_link_count'] = 0;
        $common_result['bing_back_link_count'] = 0;
        
        if (strpos($domain_name, 'https://') === false)  $domain_name_fb = 'https://' . $domain_name;
        
        $fb_like_comment_share = $this->web_repport->fb_like_comment_share($domain_name_fb);

        if(isset($fb_like_comment_share['total_share']))
            $common_result['fb_total_share'] = $fb_like_comment_share['total_share'];
        else 
            $common_result['fb_total_share'] = 0;

        if(isset($fb_like_comment_share['total_reaction']))
            $common_result['fb_total_like'] = $fb_like_comment_share['total_reaction'];
        else
            $common_result['fb_total_like'] = 0;

        if(isset($fb_like_comment_share['total_comment']))
            $common_result['fb_total_comment'] = $fb_like_comment_share['total_comment'];
        else
            $common_result['fb_total_comment'] = 0;

        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Facebook ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $pinterest_info = $this->web_repport->pinterest_pin($domain_name);
        $common_result['pinterest_pin'] = $pinterest_info;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Pinterest ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $stumbleupon_info = $this->web_repport->stumbleupon_info($domain_name);
        $common_result['stumbleupon_total_view'] = $stumbleupon_info['total_view'];
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Stumbleupon ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $buffer_info = $this->web_repport->buffer_share($domain_name);
        $common_result['buffer_share_count'] = $buffer_info;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Buffer ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $GoogleIP = $this->web_repport->GoogleIP($domain_name);
        $common_result['google_index_count'] = $GoogleIP;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Google Index ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $reddit_count = $this->web_repport->reddit_count($domain_name);
        $common_result['reddit_score'] = $reddit_count['score'];
        $common_result['reddit_ups'] = $reddit_count['ups'];
        $common_result['reddit_downs'] = $reddit_count['downs'];
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Reddit ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $xing_share_count = $this->web_repport->xing_share_count($domain_name);
        $common_result['xing_share_count'] = empty($xing_share_count) ? 0 : $xing_share_count;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Xing ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        
        $bing_index = $this->web_repport->bing_index($domain_name);
        $common_result['bing_index_count'] = $bing_index;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Bing ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $yahoo_index = $this->web_repport->yahoo_index($domain_name);
        $common_result['yahoo_index_count'] = $yahoo_index;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Yahoo ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $meta_tag_info = $this->web_repport->content_analysis($domain_name);
        $common_result['h1'] = json_encode($meta_tag_info['h1']);
        $common_result['h2'] = json_encode($meta_tag_info['h2']);
        $common_result['h3'] = json_encode($meta_tag_info['h3']);
        $common_result['h4'] = json_encode($meta_tag_info['h4']);
        $common_result['h5'] = json_encode($meta_tag_info['h5']);
        $common_result['h6'] = json_encode($meta_tag_info['h6']);
        $common_result['blocked_by_robot_txt'] = $meta_tag_info['blocked_by_robot_txt'];
        $common_result['meta_tag_information'] = json_encode($meta_tag_info['meta_tag_information']);
        $common_result['blocked_by_meta_robot'] = $meta_tag_info['blocked_by_meta_robot'];
        $common_result['nofollowed_by_meta_robot'] = $meta_tag_info['nofollowed_by_meta_robot'];
        $common_result['one_phrase'] = json_encode($meta_tag_info['one_phrase']);
        $common_result['two_phrase'] = json_encode($meta_tag_info['two_phrase']);
        $common_result['three_phrase'] = json_encode($meta_tag_info['three_phrase']);
        $common_result['four_phrase'] = json_encode($meta_tag_info['four_phrase']);
        $common_result['total_words'] = $meta_tag_info['total_words'];
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Metatag ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $whois_info = $this->web_repport->whois_email2($domain_name);
        $common_result['whois_is_registered'] = $whois_info['is_registered'];
        $common_result['whois_tech_email'] = $whois_info['tech_email'];
        $common_result['whois_admin_email'] = $whois_info['admin_email'];
        $common_result['whois_name_servers'] = $whois_info['name_servers'];
        $common_result['whois_created_at'] = $whois_info['created_at'];
        $common_result['whois_changed_at'] = $whois_info['changed_at'];
        $common_result['whois_expire_at'] = $whois_info['expire_at'];
        $common_result['whois_registrar_url'] = $whois_info['registrar_url'];
        $common_result['whois_registrant_name'] = $whois_info['registrant_name'];
        $common_result['whois_registrant_organization'] = $whois_info['registrant_organization'];
        $common_result['whois_registrant_street'] = $whois_info['registrant_street'];
        $common_result['whois_registrant_city'] = $whois_info['registrant_city'];
        $common_result['whois_registrant_state'] = $whois_info['registrant_state'];
        $common_result['whois_registrant_postal_code'] = $whois_info['registrant_postal_code'];
        $common_result['whois_registrant_email'] = $whois_info['registrant_email'];
        $common_result['whois_registrant_country'] = $whois_info['registrant_country'];
        $common_result['whois_registrant_phone'] = $whois_info['registrant_phone'];
        $common_result['whois_admin_name'] = $whois_info['admin_name'];
        $common_result['whois_admin_street'] = $whois_info['admin_street'];
        $common_result['whois_admin_city'] = $whois_info['admin_city'];
        $common_result['whois_admin_postal_code'] = $whois_info['admin_postal_code'];
        $common_result['whois_admin_country'] = $whois_info['admin_country'];
        $common_result['whois_admin_phone'] = $whois_info['admin_phone'];
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Whois ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $get_ip_country = $this->web_repport->get_ip_country($domain_name);
        $common_result['ipinfo_isp'] = $get_ip_country['isp'];
        $common_result['ipinfo_ip'] = $get_ip_country['ip'];
        $common_result['ipinfo_city'] = $get_ip_country['city'];
        $common_result['ipinfo_region'] = $get_ip_country['region'];
        $common_result['ipinfo_country'] = $get_ip_country['country'];
        $common_result['ipinfo_time_zone'] = $get_ip_country['time_zone'];
        $common_result['ipinfo_longitude'] = $get_ip_country['longitude'];
        $common_result['ipinfo_latitude'] = $get_ip_country['latitude'];
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". IP ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $this->web_repport->get_site_in_same_ip($common_result['ipinfo_ip'],$page=1,$proxy=""); 
        $sites_in_same_ip=$this->web_repport->same_site_in_ip; 
        $common_result['sites_in_same_ip']=json_encode($sites_in_same_ip);
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Site's in same IP - ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $norton_safety_check = $this->web_repport->norton_safety_check($domain_name,$proxy="");
        $common_result['norton_status'] = $norton_safety_check;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Norton ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $google_safety_check = $this->web_repport->google_safety_check($domain_name,$api);
        $common_result['google_safety_status'] = $google_safety_check;
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Google Safety ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $mcafee_status = $this->web_repport->macafee_safety_analysis($domain_name,$proxy="");
        $common_result['macafee_status'] = $mcafee_status;

        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Mcafee Safety ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $similar_site_from_google = $this->web_repport->similar_site_from_google($domain_name);
        $filtered_similar_sites = array_filter($similar_site_from_google);
        $common_result['similar_sites'] = implode(',', $filtered_similar_sites);
        //for dynamic progress bar data
        $add_complete++;
        $completed_function_str .= "<a href='#' class='list-group-item list-group-item-action text-primary'>".$add_complete.". Similar Site ".__("step completed")."<span class='text-primary float-right'><i class='fa fa-check-circle'></i></span></a>";
        $common_result['completed_step_count']=$add_complete;
        $common_result['completed_step_string']=$completed_function_str; 

        DB::table('website_analysis_info')->where('id',$web_common_info_id)->update($common_result);

        $link = url('/')."/website_analysis/analysis_report/".$web_common_info_id;
        echo '<a href="'.$link.'" class="btn btn-primary"><i class="fa fa-binoculars"></i> '.__("click here for detailed report").'</a><br/><br/>';

    }

    public function bulk_scan_progress_count(Request $request)
    {
        $domain_name=trim($request->domain_name);
        $bulk_complete_search = 0;
        $bulk_tracking_total_search= 20;

        $website_info = DB::table('website_analysis_info')
                        ->where('domain_name', $domain_name)
                        ->select('completed_step_string', 'completed_step_count','id')
                        ->get();

        $insert_table_id = isset($website_info[0]->id) ? $website_info[0]->id : 0;
        $bulk_complete_search=isset($website_info[0]->completed_step_count) ? (int)$website_info[0]->completed_step_count : 0;
        $completed_function_str=isset($website_info[0]->completed_step_string) ? $website_info[0]->completed_step_string : '';

        $response['view_details_button'] = 'not_set';
        if($insert_table_id != "")
        {

            $link = url('/')."/website_analysis/analysis_report/".$insert_table_id;
            $view_button = '<a href="'.$link.'" class="btn btn-primary"><i class="fa fa-eye"></i> '.__("detailed report").'</a><br/><br/>';
            $response['view_details_button'] = $view_button;
        }
        
        $response['search_complete'] = $bulk_complete_search;
        $response['search_total']=$bulk_tracking_total_search;
        $response['completed_function_str'] = $completed_function_str;
        
        echo json_encode($response);
        
    }


    public function delete_website_analysis_domain(Request $request)
    {
        DB::beginTransaction();
        $id = $request->input('table_id');

        DB::table('website_analysis_info')->where('id', $id)->delete();

        if(DB::commit()) {
            echo '0';
        } else {
            DB::rollBack();
            echo '1';
        }
    }


    public function ajax_delete_all_selected_domain(Request $request)
    {


        $selected_domain_data = $request->input('info');

        if(!is_array($selected_domain_data)) {
            $selected_domain_data = array();
        }

        $implode_ids = implode(",",$selected_domain_data);

        $table = "website_analysis_info";

        if(!empty($selected_domain_data)) {

            DB::table('website_analysis_info')->whereIn('id',$implode_ids)->delete();

            if(DB::table($table)->whereIn('id', $implode_ids)->count() == 0) {
                echo "0";
            } else {
                echo "1";
            }
        }
    }

    public function download_analysis_report($id=0)
    {
        $id = $id;
        $data["user_data"] = DB::table('users')->where('id', Auth::user()->id )->get();
        $data["user_data"]= json_decode(json_encode($data["user_data"]));

        
        $domain_info = DB::table('website_analysis_info')->where('id',$id)->get();
        $domain_info = json_decode(json_encode($domain_info));
        $data['country_list'] = get_country_names();
        $data['domain_info'] = $domain_info;
        $data["similar_web"] = $domain_info;
        $data["alexa_data"] = $domain_info;

        $info['fb_total_share'] = is_numeric($domain_info[0]->fb_total_share) ? number_format($domain_info[0]->fb_total_share) : 0;

        $info['fb_total_like'] = is_numeric($domain_info[0]->fb_total_like) ? number_format($domain_info[0]->fb_total_like) : 0;

        $info['fb_total_comment'] = is_numeric($domain_info[0]->fb_total_comment) ? number_format($domain_info[0]->fb_total_comment) : $domain_info[0]->fb_total_comment;


        $info['stumbleupon_total_view'] = is_numeric($domain_info[0]->stumbleupon_total_view) ? number_format($domain_info[0]->stumbleupon_total_view) : 0;

        $info['reddit_score'] = is_numeric($domain_info[0]->reddit_score) ? number_format($domain_info[0]->reddit_score) : 0;
        $info['reddit_ups'] = is_numeric($domain_info[0]->reddit_ups) ? number_format($domain_info[0]->reddit_ups) : 0;
        $info['reddit_downs'] = is_numeric($domain_info[0]->reddit_downs) ? number_format($domain_info[0]->reddit_downs) : 0;

        $info['pinterest_pin'] = is_numeric($domain_info[0]->pinterest_pin) ? number_format($domain_info[0]->pinterest_pin) : 0;
        $info['buffer_share'] = is_numeric($domain_info[0]->buffer_share_count) ? number_format($domain_info[0]->buffer_share_count) : 0;
        $info['xing_share'] = is_numeric($domain_info[0]->xing_share_count) ? number_format($domain_info[0]->xing_share_count) : 0;

        $data['info'] = $info;

        // ob_start();
        // include(APPPATH ."vendor/autoload.php");
        // $this->load->view("website_analysis/report/report",$data); 
        // ob_get_contents();
        // $html=ob_get_clean();
        // include(APPPATH ."vendor/mpdf/mpdf/src/Mpdf.php");
        // $mpdf2=new \Mpdf\Mpdf();
        // $mpdf2->autoScriptToLang = true;
        // $mpdf2->autoLangToFont = true;
        // $mpdf2->addPage();
        // $mpdf2->SetDisplayMode('fullpage');
        // $mpdf2->WriteHTML($html);       
        // $domain = time();
        // $download_id = $this->_random_number_generator(10);
        // $file_name = "website_analysis_".$domain."_".$download_id.".pdf";
        // $mpdf2->output($file_name,'I');

        
        $pdf=new \Mpdf\Mpdf();
        $pdf->autoScriptToLang = true;
        $pdf->autoLangToFont = true;
        $pdf->addPage();
        $pdf->SetDisplayMode('fullpage');
        $pdf->WriteHTML(view("seo-tools.analysis-tools.website.report.report", $data)->render());
        $domain = time();
        $download_id = $this->_random_number_generator(10);
        $file_name = "website_analysis_".$domain."_".$download_id.".pdf";
        $pdf->output($file_name,'I');
    }

    public function ajax_get_general_data(Request $request)
    {
        $domain_id = $request->input('domain_id');

        $domain_info= DB::table('website_analysis_info')->where('id', $domain_id)->get();
        $info['country_list'] = get_country_names();
        $info['domain_info'] = $domain_info;
       
        $domain_details = view('seo-tools.analysis-tools.website.general',$info)->render();
        
        echo $domain_details;

    }

    public function ajax_get_alexa_info_data(Request $request)
    {
        $domain_id = $request->input('domain_id');

        $data["alexa_data"]= DB::table('website_analysis_info')->where('id', $domain_id)->get();

        $alexa_details = view('seo-tools.analysis-tools.website.alexa-details-one',$data)->render();

        echo $alexa_details;
    }

    public function ajax_get_social_network_data(Request $request)
    {
        $domain_id = $request->input('domain_id');

        $infos = DB::table('website_analysis_info')->where('id',$domain_id)->get();

        $domain_info = array();  
        $domain_info['domain_name'] = $infos[0]->domain_name;

        $domain_info['fb_total_share'] = is_numeric($infos[0]->fb_total_share) ? number_format($infos[0]->fb_total_share) : $infos[0]->fb_total_share;

        $domain_info['fb_total_reaction'] = is_numeric($infos[0]->fb_total_like) ? number_format($infos[0]->fb_total_like) : $infos[0]->fb_total_like;

        $domain_info['fb_total_comment'] = is_numeric($infos[0]->fb_total_comment) ? number_format($infos[0]->fb_total_comment) : $infos[0]->fb_total_comment;


        $domain_info['stumbleupon_total_view'] = is_numeric($infos[0]->stumbleupon_total_view) ? number_format($infos[0]->stumbleupon_total_view) : $infos[0]->stumbleupon_total_view;
        if($domain_info['stumbleupon_total_view']=="")$domain_info['stumbleupon_total_view'] =0;

        $domain_info['reddit_score'] = is_numeric($infos[0]->reddit_score) ? number_format($infos[0]->reddit_score) : $infos[0]->reddit_score;
        $domain_info['reddit_ups'] = is_numeric($infos[0]->reddit_ups) ? number_format($infos[0]->reddit_ups) : $infos[0]->reddit_ups;
        $domain_info['reddit_downs'] = is_numeric($infos[0]->reddit_downs) ? number_format($infos[0]->reddit_downs) : $infos[0]->reddit_downs;

        $domain_info['pinterest_pin'] = is_numeric($infos[0]->pinterest_pin) ? number_format($infos[0]->pinterest_pin) : $infos[0]->pinterest_pin;
        $domain_info['buffer_share'] = is_numeric($infos[0]->buffer_share_count) ? number_format($infos[0]->buffer_share_count) : $infos[0]->buffer_share_count;
        $domain_info['xing_share'] = is_numeric($infos[0]->xing_share_count) ? number_format($infos[0]->xing_share_count) : $infos[0]->xing_share_count;


        $social_network_info = array(
            __('Facebook Total Share') => $infos[0]->fb_total_share,        
            __('Facebook Total Like') => $infos[0]->fb_total_like,        
            __('Facebook Total Comment') => $infos[0]->fb_total_comment,        
            __('Pinterest') => $infos[0]->pinterest_pin,        
            __('Reddit Score') => $infos[0]->reddit_score,        
            __('Buffer Share Count') => $infos[0]->buffer_share_count,        
            __('Xing Share Count') => $infos[0]->xing_share_count,        
        );
        
        $domain_info['social_network_info'] = $social_network_info;

        $domain_info['color_codes'] = "

            <li class='media mb-1 pb-0'>
                <div class='social_shared_icon mt-1' style='background-color: #003f5c !important;'></div>
                <div class='media-body ml-3'>
                    <h4 class='media-title'>".__('Facebook Total Share')."</h4>
                </div>
            </li>
            <li class='media mb-0 pb-0'>
                <div class='social_shared_icon mt-2' style='background-color: #4571ef !important;'></div>
                <div class='media-body ml-3'>
                    <div class='media-title'>".__('Facebook Total Like')."</div>
                </div>
            </li>
            <li class='media mb-0 pb-0'>
                <div class='social_shared_icon mt-2' style='background-color: #ce6f45 !important;'></div>
                <div class='media-body ml-3'>
                    <div class='media-title'>".__('Facebook Total Comment')."</div>
                </div>
            </li>
            <li class='media mb-0 pb-0'>
                <div class='social_shared_icon mt-2' style='background-color: #58508d !important;'></div>
                <div class='media-body ml-3'>
                    <div class='media-title'>".__('Pinterest')."</div>
                </div>
            </li>
            <li class='media mb-0 pb-0'>
                <div class='social_shared_icon mt-2' style='background-color: #bc5090 !important;'></div>
                <div class='media-body ml-3'>
                    <div class='media-title'>".__('Reddit Score')."</div>
                </div>
            </li>
            <li class='media mb-0 pb-0'>
                <div class='social_shared_icon mt-2' style='background-color: #ff6361 !important;'></div>
                <div class='media-body ml-3'>
                    <div class='media-title'>".__('Buffer Share Count')."</div>
                </div>
            </li>
            <li class='media mb-0 pb-0'>
                <div class='social_shared_icon mt-2' style='background-color: #ffa600 !important;'></div>
                <div class='media-body ml-3'>
                    <div class='media-title'>".__('Xing Share Count')."</div>
                </div>
            </li>
        ";

        echo json_encode($domain_info);
    }

    public function ajax_get_meta_tag_info_data(Request $request)
    {
        $domain_id = $request->input('domain_id');

        $data["meta_tag_info"]=DB::table('website_analysis_info')->where('id', $domain_id)->get();
        $data["meta_tag_info"] = json_decode(json_encode($data["meta_tag_info"]));

        $meta_tag_info = view('seo-tools.analysis-tools.website.meta-tag-details',$data)->render();

        echo $meta_tag_info;
    }



}
