/home/mip/mip/app/Modules/Client/Repositories/Principals/PrincipalRepository.php
<?php

namespace QxCMS\Modules\Client\Repositories\Principals;

use QxCMS\Modules\AbstractRepository;
use QxCMS\Modules\Client\Repositories\Principals\PrincipalRepositoryInterface;
use QxCMS\Modules\Client\Models\Principals\Principal;
use QxCMS\Modules\Client\Models\Settings\UserLogs\UserLogs as Log;
use DB;

class PrincipalRepository extends AbstractRepository implements PrincipalRepositoryInterface
{
    protected $model;
    protected $log;

    function __construct(Principal $model, Log $log)
    {
        $this->model = $model;
        $this->log = $log;
    }

    public function getPrincipalStatusLists()
    {
        return $this->model->principal_status;
    }

    public function create(array $request)
    {
        $user = auth()->user();
        $model = $this->model->fill($request);
        $model->save();
        $this->log->saveLog(['action' => 'Create', 'module_id' => $this->getModuleId(), 'user_id' => $user->id, 'data_id' => $model->id]);
        return $model;
    }

    public function update($id, array $request)
    {
        $user = auth()->user();
        $model = $this->model->find($id);
        $model->fill($request);
        if($model->isDirty()) {
            $model->save();
            session()->flash('success', 'Successfully updated.');
            $this->log->saveLog(['action' => 'Update', 'module_id' => $this->getModuleId(), 'user_id' => $user->id, 'data_id' => $model->id]);
        }
        return $model;
    }

    public function delete($id)
    {
        $user = auth()->user();
        $model = $this->findById($id);
        $model->contacts->each(function($value){
            $value->numbers()->delete();
        });

        $model->contacts()->delete();
        $model->delete();
        $this->log->saveLog(['action' => 'Delete', 'module_id' => $this->getModuleId(), 'user_id' => $user->id, 'data_id' => $model->id]);
        return $this->getAjaxResponse('success', 'Successfully deleted.');
    }


    public function select2($params = array())
    {
        if(!isset($params['name'])) $params['name'] = '';
        $model = $this->model
                        ->select(['name as text', 'id'])
                        ->searchByName($params['name'])
                        ->get();

        if(isset($params['placeholder'])) {
            $placeholder = array('text' => ' - All -', 'id' => '-1');
            if(isset($params['placeholder']['text'])) $placeholder = array('text' => $params['placeholder']['text'], 'id' => '-1');
             
            return  response(
                   array_prepend($model->toArray(), $placeholder)
                )->header('Content-Type', 'application/json');
        }
       
        return  response(
                       $model->toArray()
                    )->header('Content-Type', 'application/json');

       
    }
}