<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\DB;
use Crypt;

class Nominee extends Model
{

    private $generic_condition;


    public function __construct()
    {

       $this->setCondition(['is_recycle' => '0']);
    }

    public function setCondition($condition = [])
    {
        $this->generic_condition = $condition;
    }

    public function getCondition()
    {
        return $this->generic_condition;
    }

    public function storeNominee($object,$branch_label)
    {
        return  \DB::transaction(function () use ($object,$branch_label)  {

            $user = new User;

            if(isset($object['user_id'])){
                $curr_user = $user->getUserById($object['user_id']);
            }
            else{
                $curr_user = $user->storeUser($object,$branch_label);
            }

            if(isset($curr_user->id))
            {

                    $nominee = new Nominee;

                    $nominee->relation_ship = $object['relation_ship'];
                    $nominee->nok_type      = $object['nok_type'];
                    $nominee->booking_id    = $object['booking_id'];
                    $nominee->relation_id   = $object['relation_id'];
                    $nominee->user_id       = $curr_user->id;

                     $nominee->save();
            }

            return with($curr_user);

        });
    }


    public function updateNominee($object,$branch_label)
    {
            return \DB::transaction(function () use ($object,$branch_label)  {

            $nominee = Nominee::find($object['nok']);
            $nominee->relation_ship = $object['relation_ship'];
            $nominee->nok_type = $object['nok_type'];
            $user_id = $nominee->user_id;
            $user = new User;

            $object['user_id'] = $user_id;

            $user->updateUser($object,$branch_label);


            $nominee->update();

            return with($nominee);



        });

    }
    public function getBookingNok($id,$relation_id,$type = ["Nominee","Co-Owner"])
    {
        $condition = $this->getCondition();
        $condition += ['booking_id'=>$id, 'relation_id'=>$relation_id];

        $nominee_list = Nominee::where($condition)->whereIn('nok_type',$type)->orderBy('id','desc')->get();

        return $nominee_list;

    }
    // FORIGN KEY TYPE FUNCTION LIST
    public function user()
    {
        return $this->belongsTo(User::class,'user_id')->withDefault();
    }


    // END FORIGN KEY TYPE FUNCTION LIST

}
