<?php

namespace Gisplus\Package\EstatechVendor\Models;

use Illuminate\Database\Eloquent\Model;

use DB;

use App\User;

class Vendor extends Model
{

    public function storeVendor($object)
    {
        return  DB::transaction(function () use ($object)  {

            $user                  = new User;
            $user->branch_id       = $object['branch_id'];
            $user->name            = $object['full_name'];
            $user->email           = $user->autoGenerateEmail($object['email']);
            $user->password        = $user->autoGeneratePassword($object['password']);
            $user->cnic            = ($object['cnic']);
            $user->contact         = $object['contact'];
            $user->temp_address    = $object['temporary_address'];
            $user->per_address     = $object['permanent_address'];
            $user->dp              = $user->generateImage($object['user_image']);
            $user->status          = 'Active';
            
            if(isset($object['ntn'])){
                $user->ntn     = $object['ntn'];
            }

            if(isset($object['stn'])){
                $user->stn     = $object['stn'];
            }
          
            $user->save();

            $user->saveRoleValue($user, $object['type']);

            return with($user);


        });

    }

    public function updateVendor($object)
    {

        return DB::transaction(function () use ($object) {
          
            $user                  = new User;

            $user = User::find($object['user']);

            if(isset($user->id))
            {
                $user->name            = $object['full_name'];
                $user->cnic            = ($object['cnic']);
                $user->contact         = $object['contact'];
                $user->temp_address    = $object['temporary_address'];
                $user->per_address     = $object['permanent_address'];
                $user->dp              = $user->generateImage($object['user_image'],$user->dp);               
                $user->status          = 'Active';
                $user->ntn             = $object['ntn'];
                $user->stn             = $object['stn'];
                
                $user->update();

                return with($user);

            }


        });
    }

    public function removeVendor($id)
    {
        return DB::transaction(function () use ($id) {
            
            $user = User::find($id);

            if(isset($user->id))
            {
                $user->status       = 'Deactive';

                $user->update();

                return 1;
            }

            return 0;
        });
    }

   
}
