<?php

namespace App\Console\Commands;

use App\Libs\Facades\ContentTypes;
use App\Libs\Facades\Localization;
use Entry;
use Website;
use Illuminate\Support\Facades\Storage;
use Illuminate\Console\Command;

class ExportChangedContent extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'content:changed';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Exports a list of changed content';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->exportContents();
        return 0;
    }

    protected function exportContents()
    {
        $website = Website::find(1);
        $this->website = $website;

        $contentTypes = ContentTypes::all();
        $data = [];
        foreach ($contentTypes as $contentType) {
            if ($contentType->hasWebsite($website->id)) {
                $modelName = $contentType->getModelType();
                $tableName = app($modelName)->getTable();

                $query = $modelName::full()->select([$tableName . '.updated_at', $tableName . '.created_at','content_type','id','lang_slug','title'])
                  ->where($tableName . '.updated_at', '>=', '2022-01-01');

                $objects = $query->get();
                foreach ($objects as $object) {
                  $data[] = [
                    'type' => $object->content_type,
                    'id' => $object->id,
                    'created_at' => $object->created_at,
                    'updated_at' => $object->updated_at,
                    'slug' => $object->lang_slug,
                    'title' => $object->title
                  ];
                }
            }
           
        }

        /* Build csv */

        $out = "Type,Object ID,Created Date,Updated Date,Slug,Title\n";
        foreach ($data as $content) {
            $out .= $content['type'] . ',' . $content['id'] . ',' . $content['created_at'] . ',' . $content['updated_at'] . ',"' . str_replace('"', '""', $content['slug']) . '","' . str_replace('"', '""', $content['title']) . '"' . "\n";
        }

        Storage::put('changed_content'.$website->id.'.csv', $out);
    }
}
