<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class UsersTableSeeder extends Seeder
{
    /**
     * Create the initial admin user from environment variables.
     *
     * Required env vars:
     *  - ADMIN_NAME
     *  - ADMIN_EMAIL
     *  - ADMIN_PASSWORD
     * Optional:
     *  - ADMIN_TYPE (default: Owner)
     */
    public function run()
    {
        $email = env('ADMIN_EMAIL');
        $pass  = env('ADMIN_PASSWORD');
        $name  = env('ADMIN_NAME');
        $type  = env('ADMIN_TYPE', 'Owner');

        // Don't seed if env vars aren't set.
        if (!$email || !$pass || !$name) {
            return;
        }

        // Don't duplicate.
        $exists = DB::table('users')->where('email', $email)->exists();
        if ($exists) {
            return;
        }

        DB::table('users')->insert([
            'name' => $name,
            'email' => $email,
            'type' => $type,
            'password' => bcrypt($pass),
            'remember_token' => Str::random(10),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
