<?php namespace Eae\Command;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Slideshow;
use DB;


class ExportSlideshowCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'cronologias:export-slideshow';

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {

        $now = Carbon::now()->format('YmdHis');
        $filename = storage_path("slideshow-{$now}.csv");
        $file = fopen($filename, 'w');

        if ($file === false) {
            die('Error opening the file '.$filename);
        }

        fputs($file, (chr(0xEF).chr(0xBB).chr(0xBF))); // support unicode

        $headerRow = [
            'id', 'photographer', 'cases', 'description', 'date', 'image'
        ];

        fputcsv($file, $headerRow);

        Slideshow::full()->with('image')->orderBy('website_objects.position', 'asc')->chunk(
            500,
            function ($slideshow) use ($file) {
                foreach ($slideshow as $slide) {
                    $row = [
                        $slide->id,
                        $slide->photographer,
                        $slide->cases,
                        $slide->description,
                        $slide->date,
                        $slide->image->filename
                    ];

                    fputcsv($file, $row);
                }


            });

        fclose($file);
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array();
    }

}
