<?php
namespace Mtc\Shop;

use Illuminate\Database\Eloquent\Model;

/**
 * @author Uldis Zvirbulis <uldis.zvirbulis@mtcmedia.co.uk>
 */
class MedicalCondition extends Model
{
    protected $fillable = [
        'name',
    ];

    public static function importMedicalConditions()
    {
        $result = validate_csv_upload('import');
        $errors = $result['errors'];
        $handle = $result['handle'];
        $success = '';
        if (empty($errors)) {
            // Perform import
            $created_count = 0;
            self::query()->truncate();
            while(($row = fgetcsv($handle, null, ',')) !== FALSE) {
                (new self())->create([
                    'name' => $row[0],
                ]);
                ++$created_count;
            }
            if (file_exists($_FILES['import']['tmp_name'])) {
                unlink($_FILES['import']['tmp_name']);
            }
            fclose($handle);
            $success .= 'Import successful!<br />';
            $success .= 'Imported medications: ' . $created_count . '<br />';
        }
        return [
            'errors' => $errors,
            'success' => $success,
        ];
    }
}
