<?php

namespace App\Http\Controllers;

use App;
use App\Models\Application;
use Goutte\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Intervention\Image\ImageManagerStatic as Image;

class AppCrawlerController extends Controller
{
    public function __construct()
    {
        // List of categories
        $platforms = DB::table('platforms')->get();

        foreach ($platforms as $platform) {
            $platform_name[$platform->title] = $platform->id;
        }

        // Site Settings
        $site_settings = DB::table('settings')->get();

        foreach ($site_settings as $setting) {
            $settings[$setting->name] = $setting->value;
            $setting_name = $setting->name;
            $this->$setting_name = $setting->value;
        }

        $allowed_categories = array();

        foreach (json_decode($this->crawler_categories) as $crawler_name => $crawler_id) {
            if (!empty($crawler_id)) {
                $allowed_categories[$crawler_name] = $crawler_id;
            }
        }

        $this->allowed_categories = $allowed_categories;
        $this->android_platform_id = $platform_name['Android'];

    }

    /** Index */
    public function index($slug)
    {

        if ($this->auto_submission == '1') {

            // Grab crontab code
            $crontab_check = DB::table('settings')->where('name', 'submission_crontab_code')->first();

            // Check if crontab code is valid
            if ($crontab_check->value == $slug) {

                $app_query = DB::table('applications')->inRandomOrder()->where('url', 'LIKE', 'https://play.google.com/store/apps/details?id=%')->limit(1)->get();
                $searchquery = $app_query[0]->title;

                $client = new Client();
                $crawler = $client->request('GET', "https://play.google.com/store/search?q=$searchquery&hl=$this->google_play_default_language&gl=$this->google_play_default_country");

                $crawler_array = $crawler->filter('.VfPpkd-aGsRMb')->each(function ($node) {
                    $app = array();
                    $app['url'] = getAbsoluteUrl($node->filter('a.Si6A0c')->attr('href'));
                    $app['id'] = substr($app['url'], strpos($app['url'], '=') + 1);
                    $app['title'] = $node->filter('.ubGTjb')->text();
                    $app['image'] = getAbsoluteUrl($node->filter('.stzEZd')->attr('src'));
                    $app['image'] = str_replace("=s64", "=s128", $app['image']);
                    $app['author'] = $node->filter('.wMUdtb')->text();
                    $ratingNode = $node->filter('.aCy7Gf [aria-label]');
                    $app['rating'] = '0.0';
                    $app['price'] = null;

                    return $app;
                });

                $crawler_head = $crawler->filter('.ipRz4')->each(function ($node) {
                    $app = array();
                    $app['url'] = getAbsoluteUrl($node->filter('a.Qfxief')->attr('href'));
                    $app['id'] = substr($app['url'], strpos($app['url'], '=') + 1);
                    $app['title'] = $node->filter('.vWM94c')->text();
                    $app['image'] = getAbsoluteUrl($node->filter('.KvQfUd')->attr('src'));
                    $app['image'] = str_replace("=s52", "=s128", $app['image']);
                    $app['author'] = $node->filter('.LbQbAe')->text();
                    $ratingNode = $node->filter('.aCy7Gf');
                    $app['rating'] = '0.0';
                    $app['price'] = null;

                    return $app;
                });

                if (isset($crawler_head[0])) {
                    array_unshift($crawler_array, $crawler_head[0]);
                }

                $apps = $crawler_array;

                $count = count($apps);

                $exit = 0;

                for ($x = 0; $x <= $count - 1; $x++) {

                    if ($exit == '1') {
                        echo "OK";

                        // Clear cache
                        Cache::flush();
                        exit;
                    }

                    $app_id = $apps[$x]['id'];

                    $app_count = DB::table('applications')
                        ->where('url', 'LIKE', "%$app_id")
                        ->count();

                    if ($app_count == '0') {
                        $gplay = new \Nelexa\GPlay\GPlayApps($defaultLocale = $this->google_play_default_language, $defaultCountry = $this->google_play_default_country);
                        $app = $gplay->getAppInfo($app_id);

                        $categories = $app->getCategory()->getId();

                        if (array_key_exists($categories, $this->allowed_categories)) {

                            $screenshots = implode(',', $app->getScreenshots());

                            // Explode description into two pieces, first paragraph for description and rest of it for detailed description
                            $first_p = explode("\n", $app->getDescription(), 2);

                            // Set first paragraph as description
                            $description = strip_tags($first_p[0]);

                            // If not empty use second part as detailed description
                            if (isset($first_p[1])) {
                                $detailed_description = $first_p[1];
                            } else {
                                $detailed_description = null;
                            }

                            // Remove if first line of detailed description contains <br>
                            $detailed_description = str_replace("\n", '<br>', $detailed_description);
                            $detailed_description = @preg_replace('/^(?:<br\s*\/?>\s*)+/', '', $detailed_description);

                            $max_screenshots = $this->screenshot_count;

                            if ($max_screenshots != '0') {

                                $explode_screenshots = explode(",", $screenshots);
                                $total_screenshots = count($explode_screenshots);

                                if ($total_screenshots >= $max_screenshots) {
                                    $total_screenshots = $max_screenshots;
                                }

                                $ss_array = array();

                                for ($x = 0; $x <= $total_screenshots - 1; $x++) {

                                    if ($this->save_as_webp == '1') {
                                        $ss_filename = time() . '.webp';
                                    } else {
                                        $ss_filename = rand(111111111, 999999999999) . '.jpg';
                                    }

                                    // Download screenshots from Google Play Store to temp folder

                                    Image::make($explode_screenshots[$x])->
                                        save(public_path('screenshots/temp/' . $ss_filename));
                                    $ss_tempimage = "screenshots/temp/$ss_filename";
                                    $ss_location = "screenshots/$ss_filename";

                                    Image::make($ss_tempimage)->save($ss_location, $this->image_quality); // Resize image

                                    unlink($ss_tempimage); // Unlink temp image

                                    array_push($ss_array, $ss_filename);

                                }

                                $screenshots_list = implode(',', $ss_array);

                            } else {
                                $screenshots_list = '';
                            }

                            if (is_null($app->getPriceText())) {
                                $app_price = __('admin.free');
                            } else {
                                $app_price = $app->getPriceText();
                            }

                            $image = $app->getIcon();
                            $path = $image;

                            if ($this->save_as_webp == '1') {
                                $file_name = time() . '.webp';
                            } else {
                                $file_name = rand(1111111, 9999199) . '.png';
                            }

                            // Download image from Google Play Store to temp folder
                            Image::make($path)->save(public_path('images/temp/' . $file_name));
                            $tempimage = "images/temp/$file_name";
                            $location = "images/$file_name";

                            Image::make($tempimage)->resize(200, 200)->save($location, $this->image_quality); // Resize image

                            $last_id = DB::table('applications')->insertGetId(array(
                                'title' => $app->getName(),
                                'description' => $description,
                                'details' => $detailed_description,
                                'image' => $file_name,
                                'file_size' => $app->getSize(),
                                'license' => $app_price,
                                'developer' => $app->getDeveloper()->getName(),
                                'url' => $app->getUrl(),
                                'type' => '2',
                                'platform' => $this->android_platform_id,
                                'category' => $this->allowed_categories[$categories],
                                'slug' => rand(1111111, 22222222222),
                                'screenshots' => $screenshots_list,
                                'created_at' => \Carbon\Carbon::now(),
                            ));

                            $app = Application::find($last_id);
                            $app->slug = null;
                            $app->save();
                            $app->update(['title' => $app->title]);

                            $exit = 1;

                        }
                    }
                }
            }
        }
    }

}
