<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Models\Country;
use App\User;

class CreateTableUsers extends Migration
{
	private $convert = 'App\Models\Old\Account';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
	    Schema::dropIfExists('users');
        Schema::create('users', function (Blueprint $table) {
	        $table->increments('id');
	        $table->timestamps();
	        $table->integer('site_id');
	        $table->string('email');
	        $table->string('password')->nullable();
	        $table->rememberToken();
	        $table->boolean('active');
	        $table->string('title')->nullable();
	        $table->string('firstname');
	        $table->string('lastname');
	        $table->integer('country_id');
	        $table->string('address1')->nullable();
	        $table->string('address2')->nullable();
	        $table->string('city')->nullable();
	        $table->string('state')->nullable();
	        $table->string('postcode')->nullable();
	        $table->boolean('emailable')->default(TRUE);

	        $table->unique(['site_id','email']);
        });

	    if ($this->convert)
		    foreach (($this->convert)::where('id','>',0)->get() as $o)
		    {
		    	$co = Country::where('name',$o->country->name)->firstOrFail();
		    	$oo = User::where('email',$o->email)->first();

		    	if ($oo) {
		    		if ($oo->updated_at > date('Y-m-d H:i:s',$o->date_last))
		    		    continue;

		    		//printf("Updating user [%s]\n",$oo->email);
			    } else {
			        $oo = new User;
				    //printf("New user [%s]\n",$o->email);
			    }

			    $oo->site_id = $o->site_id;
			    $oo->email = $o->email;
			    $oo->password = $o->password;
			    $oo->firstname = $o->first_name;
			    $oo->lastname = $o->last_name;
			    $oo->address1 = $o->address1;
			    $oo->address2 = $o->address2;
			    $oo->city = $o->city;
			    $oo->state = $o->state;
			    $oo->postcode = $o->zip;
			    $oo->active = $o->active;
			    $oo->created_at = date('Y-m-d H:i:s',$o->date_orig);
			    $oo->updated_at = $o->date_last ? date('Y-m-d H:i:s',$o->date_last) : NULL;
			    //$oo->country_id = $co->id;
			    $co->users()->save($oo);
		    }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
	    Schema::dropIfExists('users');
    }
}