<?php

namespace App\Repositories;

use App\Models\PaymentMethod;
use App\Models\UserAccount;
use App\User;
use Illuminate\Support\Facades\Hash;



class UserRepository extends BaseRepository {


    public function __construct(User $model)
    {
        $this->model = $model;
    }



    public function update($data)
    {

        if($data['user_id'] === "new" || $data['user_id'] == 0){

            $this->model = User::create([
                'email' => $data['email'],
                'password' => env('APP_KEY'),
            ]);
            $this->model->payment_methods = PaymentMethod::getDefaultAsArray();
            $this->model->save();


        }
        else{
            $this->model = $this->getById($data['user_id']);
        }

        if(!$this->model->account_id){
            $account = new UserAccount();
        }else{
            $account = $this->model->account;
        }

        $data['same_as_billing'] = !isset($data['same_as_billing']) ? 0 : 1;

        $account->fill($data)->save();

        if(!$this->model->account_id){
            $this->model->account_id = $account->id;
            $this->model->save();
        }

        return true;
    }

    public function create($data){

        $this->model = User::create([
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        $account = UserAccount::create([
            'm_salutation' => $data['salutation'],
            'm_first_name' => $data['first_name'],
            'm_last_name' => $data['last_name'],
            'salutation' => $data['salutation'],
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'data_protection' => now(),
        ]);

        $this->model->account_id = $account->id;
        $this->model->payment_methods = PaymentMethod::getDefaultAsArray();
        $this->model->save();


        return $this->model;
    }

    public function deleteUser(User $user)
    {
        if($user->account){
            $user->account->delete();
        }
        $user->email = "delete".time();
        $user->password = "delete".time();
        $user->confirmed = 0;
        $user->confirmation_code = "delete".time();
        $user->confirmation_date = null;
        $user->confirmation_code_to = null;
        $user->confirmation_code_remider = 2;
        $user->agreement = null;
        $user->active = 0;
        $user->remember_token = '';
        $user->active_date = null;
        $user->admin = 0;
        $user->deleted_at = now();
        $user->save();

        return true;
    }


}