<?php

use Illuminate\Database\Seeder;

function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();

    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($str = fgets($handle, 1000)) !== FALSE)
        {
            $str = iconv( "Windows-1250", "UTF-8", $str);
            
            $row = str_getcsv ($str,$delimiter);
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}


class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call('UsersTableSeeder');
    }
}

class UsersTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();
        $aa = csv_to_array(dirname(__FILE__). '/Users.csv',';');
        $na = [];

        foreach ($aa as $r) {
            $s = $r["MENO"];
            $a = explode(" ", $s);
            $a[0] = str_slug($a[0]);
            $a[1] = str_slug($a[1]);
            
            $l =  strtolower($a[0]);
            $r["PASS"] = Hash::make(strtoupper($a[1][0]).$r["OC"].$a[0][0]);
            $r["EMAIL"] = ucfirst($a[1]).".".ucfirst($a[0])."@minv.sk";
            $r["LOGIN"] = $l.$r["OC"];
            $na[] = $r;
            
        }

        foreach ($na as $r) {
            DB::insert('insert into users (name,full_name,email,password,ou) values (?, ?, ?, ?, ?)', [$r["LOGIN"], $r["MENO"],$r["EMAIL"], $r["PASS"], $r["OU"]]); 
        }
    }

}
