<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Artwork;
use App\Models\Episode;
use Illuminate\Support\Facades\DB;

class AddMissingArtworkIdsToEpisodes extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'naart:artwork-to-episodes';

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $oldEpisodes = DB::connection('legacy')->select('SELECT * FROM episodes WHERE artwork_id IS NOT NULL AND published = 1');
        foreach($oldEpisodes as $oldEpisode) {
            $this->info('Checking old episode ' . $oldEpisode->show_date);
            $episode = Episode::where('legacy_id', $oldEpisode->id)->first();
            $artwork = Artwork::where('legacy_id', $oldEpisode->artwork_id)->first();
            if ($episode && $artwork) {
                $this->line('Have artwork ' . $artwork->title . ' for episode ' . $episode->title);
                $episode->artwork_id = $artwork->id;
                $episode->timestamps = false;
                if ($episode->isDirty()) {
                    $this->info('I need to update this.');
                    //$episode->save();
                } else {
                    $this->line('No Change Needed.');
                }
            } else {
                $this->error('I am lost.');
            }
        }
    }
}