<?php 
 
namespace App\Controller\Seo; 
 
use App\Entity\Seo\SEOTasks; 
use App\Entity\Seo\GPlaces; 
use App\Entity\Seo\IntelQueue; 
use App\Entity\Seo\CompetitorPivot; 
use App\Entity\Seo\Locations; 
use App\Entity\Fp\FPTasks; 
use App\Form\SEOTasksType; 
use Doctrine\ORM\EntityManagerInterface; 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Routing\Annotation\Route; 
use Symfony\Component\Filesystem\Filesystem; 
use Psr\Log\LoggerInterface; 
use App\Service\D4SeoService; 
use App\Service\D4SeoReturns; 
use App\Service\CommonService; 
use App\Repository\Seo\FPTasksRepository; 
 
class SEOTasksController extends AbstractController 
{ 
    public $logger; 
    public $d4seo; 
    public $d4return; 
    public $seoinfoLogger; 
    protected $d4SeoService; 
    protected $d4SeoReturns; 
 
    function __construct(CommonService $commonService, D4SeoService $d4SeoService, D4SeoReturns $d4SeoReturns, LoggerInterface $logger,  LoggerInterface $seoinfoLogger, EntityManagerInterface $em) { 
 
        if(!strstr($_SERVER['REQUEST_URI'], '/d4return/') && !strstr($_SERVER['REQUEST_URI'], '/d4sheet/')) { 
            $custInfo = $commonService->custInfo(); 
            $this->counts = $custInfo['counts']; 
            $this->userinfo = $custInfo['info']; 
        }  
        $this->seologger = $seoinfoLogger; 
        // FOR ERROR and CRITICAL  
        // $this->seologger->error("COME INFORMATION HERE - ".__FUNCTION__." ".__LINE__); 
        // FOR FLOW INFORMAITON 
        // $this->seologger->info("WHAT WERE DOING - ".__FUNCTION__."->businessDataStoreG");  
 
        $this->logger = $logger; 
        $this->d4seo = $d4SeoService; 
        $this->d4return = $d4SeoReturns; 
        $this->entityManager = $em; 
    } 
 
    /** 
     * @Route("/seotasks", name="seotasks") 
     */ 
    public function index(): Response 
    { 
        $content = json_decode($this->d4seo->getUserInfo()); 
        $apinfo = $content->tasks[0]->result[0]; 
        return $this->render('seo_tasks/seotasksmain.html.twig', [ 
            'page_name' => 'SEO Tasks', 
            'breadcrumbs' => array('SEO Tasks' => '/seotasks', 'API Info' => '' ), 
            'user' => $this->userinfo, 
            'counts' => $this->counts, 
            'results' => $apinfo, 
        ]); 
    } 
 
    /** 
     * @Route("/seotasks/businessdata/new", name="businessdata_new", methods={"GET","POST"}) 
     */ 
    public function bizdatanew(Request $request): Response 
    { 
        $seoTask = new SEOTasks(); 
        $form = $this->createForm(SEOTasksType::class, $seoTask); 
        $form->handleRequest($request); 
 
        if ($form->isSubmitted() && $form->isValid()) { 
            $request = Request::createFromGlobals(); 
            $content = $request->request->all(); 
            $params = (object) $content['seo_tasks']; 
            $taskinfo = (object) array( 
                'language_code' => $params->language_code, 
                'location_code' => $params->location_code, 
                'keyword' => trim($params->keyword), 
                'purpose' => $params->purpose, 
                'device' => $params->device, 
                'se_type' => 'gmbusiness', 
                'priority' => 2, 
            ); 
 
            $result = $this->d4seo->businessData($taskinfo); 
            $mess = $result->status; 
            return $this->redirectToRoute('business_data', array('message' => $mess)); 
        } 
 
        return $this->render('seo_tasks/newgmb.html.twig', [ 
            'seo_tasks' => $seoTask, 
            'form' => $form->createView(), 
            'page_name' => 'New Task GMB Info', 
            'breadcrumbs' => array('SEO Tasks' => '/seotasks', 'GMB Info' => '/seotasks/businessdata/', 'New Task' => '' ), 
            'user' => $this->userinfo, 
            'counts' => $this->counts, 
        ]); 
    } 
 
    /** 
     * @Route("/seotasks/businessmaps/new", name="businessmaps_new", methods={"GET","POST"}) 
     */ 
    public function bizmapsnew(Request $request): Response   
    { 
        $seoTask = new SEOTasks(); 
        $form = $this->createForm(SEOTasksType::class, $seoTask); 
        $form->handleRequest($request); 
 
        if ($form->isSubmitted() && $form->isValid()) { 
            $request = Request::createFromGlobals(); 
            $content = $request->request->all(); 
            $params = (object) $content['seo_tasks']; 
            $taskinfo = (object) array( 
                'language_code' => $params->language_code, 
                'location_code' => $params->location_code, 
                'keyword' => trim($params->keyword), 
                'purpose' => $params->purpose, 
                'device' => $params->device, 
                'se_type' => 'maps', 
                'priority' => 2, 
            ); 
 
            $result = $this->d4seo->businessMaps($taskinfo); 
            $mess = $result->status; 
            return $this->redirectToRoute('business_maps', array('message' => $mess)); 
        } 
 
        return $this->render('seo_tasks/newmaps.html.twig', [ 
            'seo_tasks' => $seoTask, 
            'form' => $form->createView(), 
            'page_name' => 'New Task GMB Maps', 
            'breadcrumbs' => array('SEO Tasks' => '/seotasks', 'GMB Info' => '/seotasks/businessmaps/', 'New Task' => '' ), 
            'user' => $this->userinfo, 
            'counts' => $this->counts, 
        ]); 
    } 
 
    /** 
     * @Route("/seotasks/businessdata", name="business_data") 
     * This is simply how to create a direct GMB task request. Returns business and several competitors 
     */ 
    public function businessData(Request $request): Response 
    { 
        //$request = Request::createFromGlobals(); 
 
        if($request->get('message')) { 
            $mess = $request->get('message'); 
        } else {  
            $mess = '';  
        } 
        return $this->render('seo_tasks/bizdata.html.twig', [ 
            'page_name' => 'GMB Info Tasks', 
            'breadcrumbs' => array('SEO Tasks' => '/seotasks', 'GMB Data' => '' ), 
            'user' => $this->userinfo, 
            'counts' => $this->counts, 
            'message' => $mess, 
        ]); 
    } 
 
    /** 
     * @Route("/seotasks/businessmaps", name="business_maps") 
     * This is simply how to create a direct GMB task request. Returns business and several competitors 
     */ 
    public function businessMaps(Request $request): Response 
    { 
        /*$postinfo = (object) array( 
            'language_code' => 'en', 
            'location_code' => '1025622', 
            'keyword' => 'plumbers', 
            'purpose' => 'discovery', 
            'device' => 'desktop', 
            'priority' => 2, 
        ); 
 
        if(!$this->checkThirty($postinfo->keyword, $postinfo->location_code, 'maps', 'sent')) { 
            $taskinfo = $this->d4seo->businessMaps($postinfo); 
        } else { 
            $postinfo->status = "too soon to send"; 
            $taskinfo = $postinfo; 
        }*/ 
        if($request->get('message')) { 
            $mess = $request->get('message'); 
        } else {  
            $mess = '';  
        } 
 
        return $this->render('seo_tasks/bizmaps.html.twig', [ 
            'page_name' => 'Google Maps Tasks', 
            'breadcrumbs' => array('SEO Tasks' => '/seotasks', 'Maps Data' => '' ), 
            'user' => $this->userinfo, 
            'counts' => $this->counts, 
            'message' => $mess, 
        ]); 
    } 
 
    /** 
     * @Route("/d4sheet/{api}/{se}/{function}/{report}/{d4taskid}/", name="seotasks_sheet", methods={"GET","POST"}) 
     * Temporarily not in use, ignore errors. 
     */ 
    public function task4sheet(string $api, string $se, string $function, string $report,  string $d4taskid): Response 
    { 
        $thispost = file_get_contents('php://input'); 
        $this->seologger->info("Sheet Returned Result ID: ".$d4taskid." - ".$api." / ".$se." / ".$function." - ".$thispost['status_code']." ".$thispost['status_message']." "); 
        //dd($thispost); 
         
        $newtaskid = $this->d4seo->getUUID(); 
        $task = $em->getRepository(SEOTasks::class)->findOneBy(array('d4id' => $d4taskid, 'status' => 'returned')); 
        if (!$task) { 
            $taskinfo->purpose = "discovery"; 
            $taskinfo->task_id = $newtaskid; 
            $taskinfo->d4id = $d4taskid; 
             
        } 
            
        if($postinfo->status == 'sent') { 
            $this->d4seo->storeTask($taskinfo); 
        } 
 
        $postinfo->task_id = $task_id; 
        $taskback = (object) json_decode($content); 
        $taskback = $taskback->tasks[0]; 
        $postinfo->d4id = $taskback->id; 
        $postinfo->api = $taskback->data->api; 
        $postinfo->function = $taskback->data->function; 
        $postinfo->se = $taskback->data->se; 
        $postinfo->se_type = 'gmbusiness'; 
        $postinfo->device = $taskback->data->device; 
        $postinfo->os = $taskback->data->os; 
        if ($taskback->status_message == 'Task Created.') { 
            $postinfo->status = 'sent'; 
        } else { 
            $postinfo->status = 'failed'; 
        } 
        $postinfo->created = date('Y-m-d H:i:s'); 
 
    } 
 
    /** 
     * @Route("/d4return/{purpose}/{api}/{se}/{function}/{task_id}/", name="seotasks_return", methods={"GET","POST"}) 
     */ 
    public function taskreturn(string $purpose, string $api, string $se, string $function, string $task_id): Response 
    { 
        $thispost = file_get_contents('php://input'); 
        $em = $this->getDoctrine()->getManager(); 
        $seotask = $em->getRepository(SEOTasks::class)->findOneBy(array('task_id' => $task_id)); 
        if (!$seotask) { 
            throw $this->createNotFoundException("Task Not Found With ID: {$task_id} - ".__FUNCTION__." ".__LINE__); 
        } else { 
            $d4taskid = $seotask->getD4id(); 
            $purpose = $seotask->getPurpose(); 
        } 
         
        if (!empty($thispost)) { 
            $postback = json_decode(gzdecode($thispost), true); 
            if (isset($postback['status_code'])) { 
                $this->seologger->info("D4API Returned Result ID: ".$purpose."/".$d4taskid."/".$task_id." - ".$api." / ".$se." / ".$function." - ".$postback['status_code']." ".$postback['status_message']." "); 
            } 
            $d4result = $postback;   
        } else { 
            // This is a MANUAL PULL. In other words this is check for D4Seo errors logged. It will fix lost returns. 
            if($function == 'my_business_info') { 
                $thispost = $this->d4seo->getFetchTask('/'.$api.'/'.$se.'/'.$function.'/task_get/'.$d4taskid); 
            } elseif($function == 'local_pack') { 
                $thispost = $this->d4seo->getFetchTask('/'.$api.'/'.$se.'/'.$function.'/task_get/regular/'.$d4taskid); 
            } elseif($function == 'maps') { 
                $thispost = $this->d4seo->getFetchTask('/'.$api.'/'.$se.'/'.$function.'/task_get/advanced/'.$d4taskid); 
            } elseif($function == 'reviews') { 
                $thispost = $this->d4seo->getFetchTask('/'.$api.'/'.$se.'/'.$function.'/task_get/'.$d4taskid); 
            } elseif($function == 'backlinkchk') { 
                $thispost = $this->d4seo->getFetchTask('/'.$api.'/'.$se.'/organic/task_get/regular/'.$d4taskid); 
            } else { 
                $thispost = $this->d4seo->getFetchTask('/'.$api.'/'.$se.'/'.$function.'/task_get/regular/'.$d4taskid); 
            } 
             
            if (empty($postback)) { 
                $this->seologger->info("Manual Fetch : ".$d4taskid."/".$task_id." - ".__FUNCTION__." ".__LINE__); 
            } 
            $d4result = json_decode($thispost, true); 
        } 
 
        if(isset($d4result['tasks'][0]['result'])) { 
            $d4result = $d4result['tasks'][0]['result']; 
        } else { 
            $em = $this->getDoctrine()->getManager(); 
            $task = $em->getRepository(SEOTasks::class)->findOneBy(array('d4id' => $d4taskid)); 
            $task->setStatus('not found'); 
            $em->persist($task); 
            $em->flush(); 
            if($purpose == 'footprint') { 
                $fptask = $em->getRepository(FPTasks::class)->findOneBy(array('uuid' => $task_id)); 
                $fptask->setStatus('not found'); 
                $em->persist($fptask); 
                $em->flush(); 
                unset($fptask); 
            } 
            unset($task); 
            $this->seologger->error("Returning Task : ".$d4taskid."/".$task_id." - Returned no results- ".__FUNCTION__." ".__LINE__); 
            return new Response(); 
        } 
         
        if (isset($d4result[0]['items_count']) && ($function != 'backlinkchk') ) { 
            if (0 == $d4result[0]['items_count']) { 
                $em = $this->getDoctrine()->getManager(); 
                $task = $em->getRepository(SEOTasks::class)->findOneBy(array('d4id' => $d4taskid)); 
                $task->setStatus('not found'); 
                $em->persist($task); 
                $em->flush(); 
                if($purpose == 'footprint') { 
                    $fptask = $em->getRepository(FPTasks::class)->findOneBy(array('uuid' => $task_id)); 
                    $fptask->setStatus('not found'); 
                    $em->persist($fptask); 
                    $em->flush(); 
                    unset($fptask); 
                }                 
                unset($task); 
                $this->seologger->error("Returning Task : ".$d4taskid."/".$task_id." - Returned no results - ".__FUNCTION__." ".__LINE__); 
                return new Response(); 
            } 
        } 
         
        if('business_data' == $api) { 
            if('google' == $se) { 
                if('my_business_info' == $function)  
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to businessDataStoreG - ".__FUNCTION__." ".__LINE__); 
                  $this->businessDataStoreG($d4result, $d4taskid, $purpose); } 
                elseif('my_business_updates' == $function)  
                { return new Response(); } 
                elseif('reviews' == $function)  
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningReviews - ".__FUNCTION__." ".__LINE__); 
                $this->d4return->returningReviews($d4result, $d4taskid, $purpose, 'google'); } 
            } elseif('yelp' == $se) { 
                if('reviews' == $function) 
                { return new Response(); } 
            } 
        } elseif('serp' == $api) { 
            if('google' == $se) { 
                if('organic' == $function) 
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningOrganics - ".__FUNCTION__." ".__LINE__); 
                  $this->d4return->returningOrganics($d4result, $d4taskid, $purpose, 'google'); } 
                elseif('maps' == $function)  
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningMapSerp - ".__FUNCTION__." ".__LINE__); 
                $this->d4return->returningMapSerp($d4result, $d4taskid, $purpose, 'google'); } 
                elseif('backlinkchk' == $function)  
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningBacklinkChk - ".__FUNCTION__." ".__LINE__); 
                $this->d4return->returningBacklinkChk($d4result, $d4taskid, $purpose, 'google'); } 
                elseif('news' == $function)  
                { return ''; } 
                elseif('images' == $function)  
                { return ''; }  
            } elseif('bing' == $se) { 
                if('organic' == $function) 
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningOrganics - ".__FUNCTION__." ".__LINE__); 
                $this->d4return->returningOrganics($d4result, $d4taskid, $purpose, 'bing'); } 
                elseif('local_pack' == $function)  
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningMapSerp - ".__FUNCTION__." ".__LINE__); 
                $this->d4return->returningMapSerp($d4result, $d4taskid, $purpose, 'bing'); } 
                elseif('backlinkchk' == $function)  
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningBacklinkChk - ".__FUNCTION__." ".__LINE__); 
                $this->d4return->returningBacklinkChk($d4result, $d4taskid, $purpose, 'bing'); } 
            } elseif('yahoo' == $se) { 
                if('organic' == $function) 
                { $this->seologger->info("Transferring {$task_id} for {$purpose} to returningOrganics - ".__FUNCTION__." ".__LINE__); 
                $this->d4return->returningOrganics($d4result, $d4taskid, $purpose, 'yahoo');  } 
            }   
        } elseif('reviews' == $api) { 
            if('google' == $se)  
                { return ''; } 
            elseif('yelp' == $se)  
                { return ''; } 
        } elseif('keywords_data' == $api) { 
            if('google' == $se) { 
                if('search_volume' == $function) 
                { $this->d4return->returningVolumes($d4result, $d4taskid, $purpose, 'google'); } 
                elseif('keywords_for_site' == $function) 
                { return ''; } 
                elseif('keywords_for_keywords' == $function) 
                { return ''; } 
                elseif('keywords_for_category' == $function) 
                { return ''; } 
                elseif('ad_traffic_by_keywords' == $function) 
                { return ''; } 
                elseif('ad_traffic_by_platforms' == $function) 
                { return ''; } 
            } elseif('google_trends' == $se) { 
                if('explore' == $function) 
                { return ''; } 
            } elseif('bing' == $se) { 
                if('search_volume' == $function) 
                { return ''; } 
                elseif('keywords_for_site' == $function) 
                { return ''; } 
                elseif('keywords_for_keywords' == $function) 
                { return ''; } 
                elseif('keywords_for_category' == $function) 
                { return ''; } 
                elseif('keyword_performance' == $function) 
                { return ''; } 
            }  
         
        } elseif('merchant' == $api) { 
            if('google' == $se) { 
                if('products' == $function) 
                { return ''; } 
                elseif('sellers' == $function) 
                { return ''; } 
                elseif('product_spec' == $function) 
                { return ''; } 
            } elseif('amazon' == $se) { 
                if('products' == $function) 
                { return ''; } 
                elseif('asin' == $function) 
                { return ''; } 
            } 
        } elseif('on_page' == $api) { 
            if('ping' == $se) { 
                if('back' == $function) 
                { return ''; } 
            } 
        } 
        return new Response('Success', 200, array('Content-Type' => 'text/html')); 
    } 
 
    public function businessDataStoreG($d4result, $d4taskid, $purpose) { 
        // This guy will process and store GMB Business and GMB Map Serps 
        $taskready = explode('-', $d4taskid); 
        $itemcount = $d4result[0]['items_count']; 
        $keyword = $d4result[0]['keyword']; 
 
        if($itemcount >= 1 && isset($d4result[0]['items'][0]['cid']) && !empty($d4result[0]['items'][0]['title']))  
        { 
            $folder = 'data/gmb/'.substr($taskready[4], 0, 2); 
            $filename = $folder.'/'.$taskready[4].'-gmbadvanced.json'; 
            if(!is_dir($_ENV["HOMEDIR"].'/'.$folder)) { 
                mkdir($_ENV["HOMEDIR"].'/'.$folder, 0766, true ); 
            } 
            if(file_exists($_ENV["HOMEDIR"].'/'.$filename)) { 
                $this->seologger->info("Updating {$filename} - ".__FUNCTION__." ".__LINE__);  
            } else { 
                $this->seologger->info("Saving {$filename} - ".__FUNCTION__." ".__LINE__);  
            } 
            file_put_contents($_ENV["HOMEDIR"].'/'.$filename, json_encode($d4result)); 
             
        } else { 
            $this->seologger->error("Task {$d4taskid} had no resulting items - ".__FUNCTION__." ".__LINE__);  
            $em = $this->getDoctrine()->getManager(); 
            $task = $em->getRepository(SEOTasks::class)->findOneBy(array('d4id' => $d4taskid)); 
            if(isset($task)) { 
                $em->remove($task); 
                $this->seologger->info("Removing task {$d4taskid} - ".__FUNCTION__." ".__LINE__);  
                $em->flush(); 
            } 
            $intel = $em->getRepository(IntelQueue::class)->json_like($keyword); 
            if(isset($intel)) { 
                $em->remove($intel); 
                $this->seologger->info("Removing intel queue {$keyword} - ".__FUNCTION__." ".__LINE__); 
                $em->flush(); 
            } 
            return; 
        } 
 
        $check_url = $d4result[0]['check_url']; 
        $location_code = $d4result[0]['location_code']; 
 
        $this->seologger->info("Keyword '{$keyword}' - ".__FUNCTION__." ".__LINE__); 
        foreach($d4result[0]['items'] as $item) { 
            $em = $this->getDoctrine()->getManager(); 
            if(isset($item['cid'])  && $item['cid'] >= 1) { 
                $place = $em->getRepository(Gplaces::class)->findOneBy(array('cid' => $item['cid'])); 
            } else { 
                $this->seologger->error("Keyword '{$keyword}' for task {$d4taskid} had no CID - ".__FUNCTION__." ".__LINE__);  
                $task = $em->getRepository(SEOTasks::class)->findOneBy(array('d4id' => $d4taskid)); 
                if(isset($task)) { 
                    $em->remove($task); 
                    $this->seologger->info("Removing task {$d4taskid} - ".__FUNCTION__." ".__LINE__);  
                    $em->flush(); 
                } 
                $intel = $em->getRepository(IntelQueue::class)->json_like($keyword); 
                if(isset($intel)) { 
                    $em->remove($intel); 
                    $this->seologger->info("Removing intel queue {$keyword} - ".__FUNCTION__." ".__LINE__);  
                    $em->flush(); 
                } 
                break; 
            } 
             
            if (!$place && isset($item['cid'])) { 
                $place = new Gplaces(); 
                $recheck = 0; 
                 
                $this->seologger->info("Adding NEW Place '{$item['title']}' {$item['cid']} - ".__FUNCTION__." ".__LINE__); 
                if(isset($item['latitude']) && isset($item['latitude'])) { 
                    $place->setLat($item['latitude']); 
                    $place->setLng($item['longitude']); 
                } else { 
                    $recheck = 1; 
                } 
                $place->setCid($item['cid']); 
                $place->setFeatureID($item['feature_id']); 
                $place->setPlaceId($item['place_id']); 
                if(isset($item['address'])) { 
                    $address_all = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAbTq8g-XSRuqwjMltfCKf1BI-PziP_ym0&address='.urlencode($item['address'])); 
                    if(isset($address_all)) { 
                        $rawaddy = json_decode($address_all, TRUE); 
                        if($rawaddy['status'] != 'OVER_QUERY_LIMIT' && $rawaddy['status'] != 'ZERO_RESULTS') { 
                            $rawaddy = $rawaddy['results'][0]; 
                        } 
                    } 
                } 
                if($recheck == 1 && isset($item['address']) && isset($rawaddy['results'][0])) { 
                    if(isset($rawaddy['geometry']['location']['lat']) && isset($rawaddy['geometry']['location']['lng'])) { 
                        $place->setLat($rawaddy['geometry']['location']['lat']); 
                        $place->setLng($rawaddy['geometry']['location']['lng']); 
                    } 
                } 
            }  
 
            if(isset($rawaddy['results'][0])) { 
                $place->setAddressAll($rawaddy); 
                $bestlocation = $this->getLocCode($rawaddy,$location_code); 
            } else { 
                $rawaddy = $place->getAddressAll(); 
                $bestlocation = $location_code; 
            } 
 
            $place->setKeyword($keyword); 
            if(!empty($item['address'])) { 
                $place->setAddress($item['address']); 
            } 
            $place->setLocation($bestlocation); 
            if(isset($item['additional_categories'])) {  
                $place->setAddcats($item['additional_categories']); 
            }  
             
            $place->setTitle($item['title']); 
            $place->setPrimarycat($item['category']); 
            if(!empty($item['phone'])) { 
                $place->setPhone($item['phone']);  
            } 
            $place->setWorktime($item['work_time']); 
            if($item['url']) { 
                $place->setUrl($item['url']); 
                $place->setDomain($item['domain']); 
            } 
            $place->setMainImage($item['main_image']); 
            $place->setSnippet($item['snippet']); 
            if(isset($item['rating'])) { 
                $place->setRatingType($item['rating']['rating_type']); 
                $place->setRatingValue($item['rating']['value']); 
                $place->setVotesCount($item['rating']['votes_count']); 
                if(isset($item['rating']['rating_max'])) { 
                    $place->setRatingMax($item['rating']['rating_max']); 
                } 
            } 
 
            $check_url = "https://www.google.com/maps?cid=".$item['cid']."&hl=en&gl=US"; 
            $place->setCheckUrl($check_url); 
 
            if(isset($item['description'])) { 
                $place->setDescription($item['description']); 
            } 
            if(isset($item['logo'])) { 
                $place->setLogo($item['logo']); 
            } 
            if(isset($item['attributes'])) { 
                $place->setAttributes($item['attributes']); 
            } 
            if(isset($item['people_also_search'])) { 
                $place->setCompetitors($item['people_also_search']); 
            } 
            $place->setModified(\DateTime::createFromFormat('Y-m-d H:i:s', date('Y-m-d H:i:s'))); 
            $em->persist($place); 
            $em->flush(); 
 
            $task = $em->getRepository(SEOTasks::class)->findOneBy(array('d4id' => $d4taskid)); 
             
            $task->setStatus('returned'); 
            $em->persist($task); 
            $em->flush(); 
 
            if(isset($item['people_also_search'])) { 
                $complist = array(); 
                foreach($item['people_also_search'] as $competitor)  { 
                    // First check if we already know about the listing via CID. If not we add the listing to the IntelQueue  
                    // so tasks can be created over time. Not right away for sure. Reminder: $130 reasons why not, lol. 
                    $em = $this->getDoctrine()->getManager(); 
 
                    if(!empty($competitor['title']) && !empty($competitor['cid'])) { 
                        $cid = (string) $competitor['cid']; 
                        $cidcheck = $em->getRepository(GPlaces::class)->doesGPlaceExist($cid); 
 
                        if (!$cidcheck) { 
                            $more = array( 
                                'language_code' => 'en', 
                                'se' => 'google', 
                                'location_code' => $location_code, 
                                'keyword' => $competitor['title'], 
                                'cid' => $competitor['cid'], 
                                'purpose' => $purpose, 
                            ); 
                            $qinfo = (object) array( 
                                'purpose' => $purpose, 
                                'location_code' => $location_code, 
                                'actionapi' => 'business_data', 
                                'function' => 'my_business_info', 
                                'content' =>  $competitor['title'], 
                                'more' => json_encode($more), 
                            ); 
                            $this->seologger->info("Storing intel queue for '{$competitor['title']}' {$competitor['cid']} - ".__FUNCTION__." ".__LINE__);  
 
                            $this->d4seo->storeQueue($qinfo); 
                        } 
                        array_push($complist, $competitor['cid']); 
                    } 
                } 
 
                $cpivot = $em->getRepository(CompetitorPivot::class)->findOneBy(array('cid' => $item['cid'])); 
                if (!$cpivot) { 
                    $cpivot = new CompetitorPivot(); 
                    $cpivot->setCid($item['cid']); 
                    $cpivot->setEngine('google'); 
                } else { 
                    if(is_array($cpivot->getCompCids())) { 
                        $complist = array_unique(array_merge($complist, json_decode($cpivot->getCompCids())), SORT_REGULAR); 
                    } else { 
                        $complist = array(); 
                    } 
                } 
                $cpivot->setCompCids(json_encode($complist)); 
                $em->persist($cpivot); 
                $em->flush(); 
            } 
        } 
    } 
 
    private function getLocCode($addyin, $current) { 
        $key = 'United States'; 
        foreach($addyin['address_components'] as $component) { 
            if (in_array('locality', $component['types'])) {  
                $city = $component['short_name']; 
            } elseif (in_array('administrative_area_level_1', $component['types'])) {  
                $state = $component['long_name']; 
            } elseif (in_array('postal_code', $component['types'])) {  
                $zipcode = $component['short_name']; 
            } 
        } 
        if (isset($city)) { 
            $key= $city.','; } 
        if (isset($state)) { 
            $key.= $state.','; } 
 
        $key.='United States'; 
        $em = $this->getDoctrine()->getManager(); 
        $location = $em->getRepository(Locations::class)->findOneBy(array('location_name' => $key)); 
        if (!$location && $zipcode) { 
            $location = $em->getRepository(Locations::class)->findOneBy(array('location_name' => $zipcode.','.$state.',United States')); } 
        if($location) { 
            return $location->getLocationCode(); 
        } else { 
            return $current; 
        } 
    } 
 
 
}