<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\MorphTo;

use App\Models\Photo;

use App\Models\Version;
use App\Models\Slideshow;
use App\Models\EmbedVideo;
use App\Models\InlinePhoto;
use App\Models\InquiryForm;
use App\Models\PhotoBlock;
use App\Models\Quote;
use App\Models\TextBlock;
use App\Models\YoutubeVideo;

class RefreshPhotos extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'brentwood:refresh-photos {--clear} {--info} {ids?*}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate new versions of photos from the original upload';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $ids = $this->argument('ids');
        $pages = collect();

        if ($ids) {
            if (!is_array($ids)) {
                $ids = collect([$ids]);
            }
            $photos = Photo::whereIn('id', $ids)->get();
        } else {
            $all_photos = Photo::with(['content' => function (MorphTo $morphTo) {
                $morphTo->morphWith([
                    Version::class => ['versionable'],
                    Slideshow::class => ['contentElement.contentables.pageable.publishedVersion'],
                    EmbedVideo::class => ['contentElement.contentables.pageable.publishedVersion'],
                    InlinePhoto::class => ['contentElement.contentables.pageable.publishedVersion'],
                    InquiryForm::class => ['contentElement.contentables.pageable.publishedVersion'],
                    PhotoBlock::class => ['contentElement.contentables.pageable.publishedVersion'],
                    Quote::class => ['contentElement.contentables.pageable.publishedVersion'],
                    TextBlock::class => ['contentElement.contentables.pageable.publishedVersion'],
                    YoutubeVideo::class => ['contentElement.contentables.pageable.publishedVersion'],
                ]);
            }])->get();

            $photos = collect();

            $this->info('Finding Active Images');
            $missing = collect();
            $this->withProgressBar($all_photos, function ($photo) use ($photos, $missing, $pages) {
                if ($photo->content) {
                    if ($photo->content->contentElement) {
                        $content_element = $photo->content->contentElement;

                        if ($content_element && $content_element->getPublishedVersion() && $content_element->id === $content_element->getPublishedVersion()->id) {
                            $photos->push($photo);

                            if ($content_element->contentables && $this->option('info')) {
                                foreach ($content_element->contentables as $contentable) {
                                    if ($contentable->pageable?->type === 'page') {
                                        $page_name = $contentable->pageable->publishedVersion?->name;
                                        if ($page_name && !$pages->contains($page_name)) {
                                            $pages->push($page_name);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        $class = class_basename($photo->content);

                        // Footers
                        if ($class === 'Version') {
                            if ($photo->content && $photo->content->versionable && $photo->content->id === $photo->content->versionable->published_version_id) {
                                $photos->push($photo);
                            }
                        } else {
                            $classes = collect(['Livestream', 'TimetableContent', 'StaffProfile', 'InlinePhoto']);
                            if ($classes->contains($class)) {
                                $photos->push($photo);
                            } else {
                                if (!$missing->contains($class)) {
                                    $missing->push($class);
                                }
                            }
                        }
                    }
                }
            });

            $this->newLine();
            $this->info($photos->count().' Images Found');
        }

        if ($this->option('info')) {
            $this->info('--- Pages Found ---');
            $this->newLine();

            if ($pages->count()) {
                foreach ($pages->sort() as $page_name) {
                    $this->info($page_name);
                }
            }
        }

        $this->newLine();
        $this->info('--- Queuing Images ---');
        $this->withProgressBar($photos, function ($photo) {
            if ($this->option('info')) {
                $this->info($photo->id);
            }

            // Handle null values safely
            if ($photo) {
                $photo->regenerate($this->option('clear') ? true : false);
            } else {
                $this->warn("Skipping null photo.");
            }
        });

        $this->newLine();
        $this->call('cache:clear');
        $this->info('PHOTO REFRESH COMPLETE');

        return Command::SUCCESS;
    }
}

