<?php

namespace App\Console\Commands;

use App\Models\Article;
use Illuminate\Console\Command;

class ExportPosts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'export:posts {--type= : The type}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export posts';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $status = $this->option('type') ? $this->option('type') : 'all';
        if (! in_array($status, ['all', 'old', 'publish', 'new', 'draft'])) {
            $this->error('Invalid status');

            return;
        }

        $articles = Article::with(['primaryCategory'])->where('type', 0);
        if ($status == 'old') {
            $articles->whereNotNull('wp_id');
        } elseif ($status == 'publish') {
            $articles->whereNotNull('wp_id')
                ->where('status', 'publish');
        } elseif ($status == 'new') {
            $articles->whereNull('wp_id');
        } elseif ($status == 'draft') {
            $articles->whereNotNull('wp_id')
                ->where('status', '!=', 'publish');
        }

        $articles = $articles->get();
        $fileName = public_path('articles_' . $status . '_' . date('YmdHis') . '.csv');
        $fp = fopen($fileName, 'w');
        fputcsv($fp, ['ID', 'Title', 'Slug', 'URL', 'New URL']);

        foreach ($articles as $article) {
            $categorySlug = 'detail';
            if ($article->primaryCategory) {
                $categorySlug = $article->primaryCategory->full_slug ?? $article->primaryCategory->slug;
            }

            fputcsv($fp, [
                $article->id,
                $article->title,
                urldecode($article->slug),
                ('https://mattock.jp/blog/' . $categorySlug . '/' . $article->slug . '/'),
                url('blog/' . $categorySlug . '/' . $article->slug) . '/',
            ]);
        }

        fclose($fp);

        $this->info('Posts exported successfully: ' . $fileName);
    }
}
