<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use App\Modules\Stock\Stock;
use App\Console\Commands\AbstractCommand;

ini_set('auto_detect_line_endings', true);

class StockImportCommand extends AbstractCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'stock:import';

    /**
     * A friendly name of the command that will be used when loggin messages.
     *
     * @var string
     */
    protected $command_title = 'Import Stock';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Imports stock from an excel / csv file.';

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

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $file = fopen($this->argument('file'), 'r');
        $count = 0;

        while ($row = fgetcsv($file)) {
            if ($count < $this->option('skip')) {
                $count++;
                continue;
            }

            if (empty($row[0])) {
                continue;
            }

            // Find the stock with this name
            if ($stock = Stock::where('name', $row[0])->first()) {
                $stock->model_number = $row[4];
                if ($stock->save()) {
                    $this->info('Update stock '.$stock->name);
                } else {
                    $this->error('Failed to update stock '.$stock->name);
                }
            }

            $count++;
        }

        fclose($file);
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['file', InputArgument::REQUIRED, 'The path to the file to import data from.'],
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['skip', 's', InputOption::VALUE_OPTIONAL, 'Rows to skip starting from the top.', 1],
        ];
    }
}
