<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\StringOperation;
use App\Model\Category;
use App\Model\Tag;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Model\WordpressPost;
use Auth;
use DB;
use App\Model\WordpressCategory;
use App\Model\Article;

use File;
use Illuminate\Support\Str;
use Image;

class ImportController extends BaseController
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

//   $photos =     Article\ArticlePhoto::all();
//   foreach ($photos as $photo) {
//       $photo_root_path = StringOperation::getCompletePathFromNumber($photo->article_id, 'articles', false);
//
//       if (!is_file($photo_root_path . $photo->filename)) {
//           dump('file not found', $photo);
//       }
//   }

        if (request('fix_photos_order')) {

            $articles = Article::with('photos')->recipe()
//                ->where('id', 300)
//                ->take(3)
                ->get();
            foreach ($articles as $article) {
                $main_photo = $article->photos->where('id', $article->photo_id)->first();
                if (empty($main_photo->id)) {
                    dd($article);
                }
                if ($main_photo->id == $article->photo_id) {

                    $main_photo->priority = 0;
                    $main_photo->save();
                }
            }
        }

        if (request('fix_main_photo')) {

            foreach (WordpressPost:: with('photo')
                         ->with('photo.post')
                         ->with('meta')
                         ->active()
                         ->where('ID', 16591)
                         ->limit(2)
                         ->get() as $post) {

                $article = Article::where(['wp_id' => $post->ID])->first();

//                if ($article->photo->filename != )
//                dump($article->photo->filename, basename($post->photo->post->guid));
            }
        }

//        dd('Done already.');

        $wp_root_path = base_path('wp-content');

        // steps:

        // sunt mai multe tipuri de retete.. !!


//        1. ia fields de baza (titlu, descrirere, timp creare,etc)
//        2. extrage INGREDIENTS
//        3. extrange STEPS (pt cele care au... UNELE AU SI POZE.. deci si astea trebuisc salvate si asociate!!)
//        4. extrage params (timp executare, etc)
//        5. extrage tipul de cusine (in tabele si alte info extra)
//        6. extrage pozele din galerie (alte tabele extra, de analizat: inspiry_recipe_slider_image, inspiry_recipe_recipe_images, inspiry_recipe_recipe_images )
//        7. extrage categoria si creaz-o (cu parent_id de la retete)
//        8. extrage poza de reteta / lista


        dd('we are ready. daca importi tre manual sa pui ALIAS la retetele duplicate. dezactivare sync tags + activare save articol');
        set_time_limit(0);
        ini_set('memory_limit', '2048M');

        $do_import_categories = false;

        // import categories to a human readable form.... 
        if ($do_import_categories) {
            $category_posts = DB::select(DB::raw('SELECT wp_term_relationships.*, post_title, ID, taxonomy,  slug
                                    FROM `wp_term_relationships` 
                                    LEFT JOIN wp_posts ON (wp_posts.ID = object_id) 
                                    LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) 
                                    LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
                                    WHERE taxonomy = "category"
                                    AND wp_terms.term_id != "1"
                                    ORDER BY `object_id` DESC'));
            dd($category_posts);
            foreach ($category_posts as $category_post) {
                //
                (new WordpressCategory)->findAndSave($category_post->slug, $category_post->object_id);
            }
        }


        // process posts.

        foreach (WordpressPost::with('photo')
                     ->with('meta')
                     ->active()
//                     ->offset(0)
//                     ->limit(10000)
                     ->limit(10000)
//                     ->where('ID', '16814') // tort snikers 2
//                     ->where('ID', '16951')
//                     ->where('ID', '4759')
                     // check STEPS: 4309 https://superchef.ro/reteta/supa-de-ciuperci-cu-legume-si-galuste-de-faina/
                     // step cu POZE & CAT: 4759 https://superchef.ro/reteta/supa-de-pui-cu-galuste-pufoase-de-gris/
                     // step cu POZE: 4787 https://superchef.ro/reteta/supa-de-linte-rosie-cu-pui-bacon-si-smantana/
                     ->get() as $post) {

            // get meta data
            $meta = (object)$post->meta->pluck('meta_value', 'meta_key')->toArray();


            $append_to_body = '';
            $tips = '';

            if (!empty($meta->inspiry_recipe_tips_variations)) {
                $tips = unserialize($meta->inspiry_recipe_tips_variations);
                $tips = implode('\r\n', $tips);
                $tips = preg_replace('#[\r\n]{1,}#', '<br/>', $tips);

                if ($tips == '""') {
                    $tips = '';
                }
            }

            // cuisine summary (skill, cuisine, course, etc)
            $terms = collect(DB::select(DB::raw("SELECT wp_terms.*, taxonomy
                                    FROM `wp_term_relationships` 
                                    LEFT JOIN wp_posts ON (wp_posts.ID = object_id) 
                                    LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) 
                                    LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
                                    WHERE 
                                        taxonomy IN ('skill-level', 'recipe-type', 'inspiry-course', 'inspiry-cuisine')
                                        AND
                                        object_id = '{$post->ID}'")));

            $tags = collect(DB::select(DB::raw("SELECT wp_terms.*, taxonomy
                                    FROM `wp_term_relationships` 
                                    LEFT JOIN wp_posts ON (wp_posts.ID = object_id) 
                                    LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) 
                                    LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
                                    WHERE 
                                        taxonomy IN ('post_tag')
                                        AND
                                        object_id = '{$post->ID}'")))
                ->pluck('name');

            $tags = $tags->map(function ($item) {
                return Tag::firstOrCreate([
                    'slug' => Str::slug($item),
                ], [
                    'name' => $item,
                ])->id;
            })->unique();

            $categories = $terms->where('taxonomy', 'recipe-type')->pluck('name')->toArray();
            $terms = $terms->pluck('name', 'taxonomy');

            $category_id = null;
            $category = reset($categories);
            if ($category) {
                $category_id = Category::firstOrCreate([
                    'name' => $category,
                    'parent_id' => '2',
                ])->id;
            }


            // ingredients
            $ingredients = $meta->inspiry_recipe_ingredient_sections_group ?? null;
            if ($ingredients) {
                $ingredients = unserialize($ingredients);

                if (isset($ingredients[0]['inspiry_recipe_ingredient_set_list'])) {

                    $aux = [];
                    foreach ($ingredients as $ingredient_group) {
                        $aux_group = [
                            'name' => $ingredient_group['inspiry_recipe_ingredient_set_title'] ?? '',
                            'items' => [],
                        ];

                        if ($ingredient_group['inspiry_recipe_ingredient_set_list']) {
                            $aux_group['items'] = array_filter(array_filter(explode("\r\n", $ingredient_group['inspiry_recipe_ingredient_set_list'])));
                        }
                        $aux[] = $aux_group;
                    }
                    $ingredients = $aux;

                } else {
                    $ingredients = null;
                }
            }

            // steps
            $steps = $meta->inspiry_recipe_method_steps_group ?? '';
            $steps_photos_ids = [];
            if ($steps) {
                $steps = unserialize($steps);

                if (count($steps)) {
                    $steps = collect($steps);
                    // extract all photos ids, used later
                    $steps_photos_ids = $steps->pluck('inspiry_recipe_step_image')->flatten()->unique()->toArray();

                    $steps = [
                        [
                            'name' => $meta->inspiry_recipe_method_steps_title ?? 'Pasi',
                            'steps' => collect($steps)->map(function ($item) {
//
                                if (!empty($item['inspiry_recipe_step_title'])) {
                                    $text = $item['inspiry_recipe_step_title'] . "\r\n" . $item['inspiry_recipe_step_details'];
                                } else {
                                    $text = $item['inspiry_recipe_step_details'] ?? null;
                                }
                                return [
                                    'filename' => isset($item['inspiry_recipe_step_image']) ? reset($item['inspiry_recipe_step_image']) : null,
                                    'text' => $text,
                                ];
                            })
                        ]
                    ];
                }

            }

            // get all photos related to this recipe.
            $photos = $post->photos()
                ->when(count($steps_photos_ids), function ($q) use ($steps_photos_ids) {
                    $q->orWhereIn('ID', $steps_photos_ids);
                })
                ->get()
                ->pluck('src', 'ID');


            // get photos filename for steps
            if (!empty($steps)) {
                $steps = collect($steps)->map(function ($item) use ($photos) {
                    $item['steps'] = collect($item['steps'])->map(function ($item) use ($photos) {
                        $id = $item['filename'];
                        $item['filename'] = isset($photos[$id]) ? basename($photos[$id]) : null;
                        return $item;
                    });
                    return $item;
                })->toArray();
            }

//
//            if (empty($meta->inspiry_recipe_prep_time)) {
//                dd($post, $post->meta->pluck('meta_value', 'meta_key'), $terms);
//            }


            $article_data = [
                'wp_id' => $post->ID,
                'user_id' => Auth::id(),
                'created_at' => $post->post_date,
                'published_at' => $post->post_date,
                'updated_at' => $post->post_modified,
                'title' => $post->post_title,
                'body' => $post->post_content . $append_to_body,
                'status' => 'active',
                'ingredients' => $ingredients,
                'steps' => $steps,
                'params' => [
                    'yield' => $meta->inspiry_recipe_yield ?? '',
                    'servings' => $meta->inspiry_recipe_servings ?? '',
                    'time_preparing' => trim($meta->inspiry_recipe_prep_time ?? '0'),
                    'time_cooking' => trim($meta->inspiry_recipe_cook_time ?? '0'),
                    'time_ready' => trim($meta->inspiry_recipe_ready_in ?? '0'),
                    'cuisine' => $terms['inspiry-cuisine'] ?? '',
                    'course' => $terms['inspiry-course'] ?? '',
                    'skill' => $terms['skill-level'] ?? '',
                ],
                'categories' => $categories,
                'category_id' => $category_id,
                'photos' => $photos,
                'tips' => $tips,
            ];


//            dump($article['category']);
//            dump($article['steps']);

//            dump($article);
//            continue;

            // process current post

//            if (!Article::where('wp_id', $post->ID)->first()) {
            $article = Article::firstOrCreate(['wp_id' => $post->ID]);
            echo "Processing $post->ID<br/>";


            // create new article
//            $article->fill($article_data);

            $article->tags()->sync([]);
            $article->tags()->sync($tags);
//            $article->save();

            // add categories
//                foreach ($categories as $category) {
//                    DB::table('article_category')->insert([
//                        'category_id' => $category,
//                        'article_id' => $article->id,
//                    ]);
//                }

            // now save the photos!
            if (empty($article->photo_id)) {
                $photo_root_path = StringOperation::getCompletePathFromNumber($article->id, 'articles', '');
                // check if folder exists and create it recursively if N/a
                if (!File::isDirectory($photo_root_path)) {
                    File::makeDirectory($photo_root_path, 0755, true);
                }


                foreach ($article_data['photos'] as $photo_id => $path) {
                    if (!is_file($wp_root_path . $path)) {
                        dd('fisier nu exista', $wp_root_path . $path);
                    }

                    $photo = Article\ArticlePhoto::firstOrCreate([
                        'article_id' => $article->id,
                        'filename' => basename($path),
                    ]);

                    Image::make($wp_root_path . $path)
                        ->resize(1980, null, function ($constraint) {
                            $constraint->aspectRatio();
                            $constraint->upsize();
                        })
                        ->save($photo_root_path . $photo->filename)
                        ->resize(420, null, function ($constraint) {
                            $constraint->aspectRatio();
                            $constraint->upsize();
                        })
                        ->save($photo_root_path . 'thumb_' . $photo->filename);

                    usleep(1000);


                    // save the main photo for the article.
                    if ($post->photo && $photo_id == $post->photo->meta_value
                        && $article->photo_id != $photo->id) {
                        $article->photo_id = $photo->id;
                        $article->save();
                    }

                }
            }

        }
//        }
    }

}
