<?php

namespace App\Console\Commands;

use App\Models\Article;
use App\Models\ArticleCategory;
use App\Models\ArticleTag;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ImportPostsLost extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'import:pipopa-posts-lost';
	
	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Import posts from WordPress system';
	
	/**
	 * Execute the console command.
	 */
	public function handle()
	{
		$posts = DB::connection('pipopa_old')
			->table('articles')
			->select('*')
			->get();
		
		$missingPosts = [];
		$this->warn('Checking missing posts...');
		$bar = $this->output->createProgressBar($posts->count());
		$bar->setFormat("%current%/%max% [%bar%] %percent:3s%%\nProcessing: %message%");
		$bar->setMessage('Starting...');
		$bar->start();
		
		collect($posts)->chunk(100)->each(function ($chunk) use (&$missingPosts, &$bar) {
			foreach ($chunk as $post) {
				$postId = $post->id;
				$postTitle = $post->title;
				$postSlug = $post->slug;
				
				$bar->setMessage("Article ID [{$postId}] - Title: {$postTitle}...");
				$bar->advance();
				
				$article = Article::withTrashed()->where('title', $postTitle)->first();
				if (!$article) {
					if (!isset($missingPosts[$postId])) {
						$missingPosts[$postId] = $post;
					}
				}
				
				$article = Article::withTrashed()->where('slug', $postSlug)->first();
				if (!$article) {
					if (!isset($missingPosts[$postId])) {
						$missingPosts[$postId] = $post;
					}
				}
			}
		});
		
		$bar->setMessage('Found ' . count($missingPosts) . ' posts');
		$bar->advance();
		$bar->setMessage('Checking Done!');
		$bar->advance();
		$bar->finish();
		$this->newline();
		
		if (count($missingPosts) <= 0) {
			$this->info('No posts found.');
			return;
		}
		
		$continue = $this->confirm('Found ' . count($missingPosts) . ' posts. Do you want to continue processing these articles?', false);
		if (!$continue) {
			$this->warn('Operation cancelled.');
			return;
		}
		
		$bar2 = $this->output->createProgressBar(count($missingPosts));
		$bar2->setFormat("%current%/%max% [%bar%] %percent:3s%%\nProcessing: %message%");
		$bar2->setMessage('Importing...');
		$bar2->start();
		
		$logsMattockPosts = "";
		$logsPipopaPosts = "";
		foreach ($missingPosts as $post) {
			$bar2->setMessage("Article ID [{$post->id}] - Title: {$post->title}...");
			$bar2->advance();
			
			// Import article here
			$newArticle = $this->importMissingPost($post);
			
			$postType = ($post->type == 0) ? 'mattock' : 'pipopa';
			$oldUrl = "Old url: https://mattock.jp/admin/{$postType}/articles/{$post->id}/edit";
			$oldUrl = str_pad($oldUrl, 68, ' ');
			if ($post->type == 0) {
				$logsMattockPosts .= $oldUrl . "\t ===> \t New url: https://mattock.jp/admin/{$postType}/articles/{$newArticle->id}/edit\n";
			} else {
				$logsPipopaPosts .= $oldUrl . "\t ===> \t New url: https://mattock.jp/admin/{$postType}/articles/{$newArticle->id}/edit\n";
			}
		}
		
		file_put_contents(public_path('import-posts-lost.log'), $logsMattockPosts . "\n" . $logsPipopaPosts);
		
		$bar2->setMessage('Imported ' . count($missingPosts) . ' posts.');
		$bar2->advance();
		$bar2->finish();
		$this->newline();
		
		$ids = array_keys($missingPosts);
		$this->warn('Missing ' . count($missingPosts) . ' posts: [' . implode(',', $ids) . ']');
		$this->info('All articles have been checked successfully. Please check the log file: ' . public_path('import-posts-lost.log'));
	}
	
	private function importMissingPost($post)
	{
		$postSlug = $post->slug;
		$checkSlug = Article::withTrashed()
			->where('type', $post->type)
			->where('slug', $postSlug)
			->exists();
		
		// Generate unique slug
		if ($checkSlug) {
			$postSlug = $postSlug . uniqid();
			$this->error('[Error] Slug already exists, generating new slug: ' . $postSlug);
			$this->newline();
		}
		
		$articleData = [
			'type'                => $post->type,
			'title'               => $post->title,
			'slug'                => $postSlug,
			'image'               => $post->image,
			'description'         => $post->description,
			'content'             => $post->content,
			'excerpt'             => $post->excerpt,
			'primary_category_id' => $post->primary_category_id,
			'focus_keyword'       => $post->focus_keyword,
			'robots'              => $post->robots,
			'canonical_url'       => $post->canonical_url,
			'og_image'            => $post->og_image,
			'seo_score'           => $post->seo_score,
			'views'               => $post->views,
			'status'              => $post->status,
			'user_id'             => $post->user_id,
			'wp_id'               => $post->wp_id,
			'sync_status'         => $post->sync_status,
			'sync_at'             => $post->sync_at,
			'created_at'          => $post->created_at,
			'updated_at'          => $post->updated_at,
			'deleted_at'          => $post->deleted_at,
		];
		
		$article = Article::create($articleData);
		
		$categoryIds = DB::connection('pipopa_old')
			->table('article_categories as ac')
			->where('ac.article_id', $post->id)
			->pluck('ac.category_id')
			->toArray();
		foreach ($categoryIds as $categoryId) {
			ArticleCategory::create([
				'article_id'  => $article->id,
				'category_id' => $categoryId,
			]);
		}
		
		$tagIds = DB::connection('pipopa_old')
			->table('article_tags as at')
			->where('at.article_id', $post->id)
			->pluck('at.tag_id')
			->toArray();
		foreach ($tagIds as $tagId) {
			ArticleTag::create([
				'article_id' => $article->id,
				'tag_id'     => $tagId,
			]);
		}
		
		return $article;
	}
}
