<?php
 namespace VnChocola\Module\Api\CallHistory;
 use TCMS\APIController;
 use Model;
 use VNChocola\Model\CallHistorysModel;
 class IndexController extends APIController {
 public function get() {
 $auth = load_auth();
 $user = $auth->getUser();
 $model = Model::load('CallHistorysModel');
 $collection = $model->getCollection();
 $viewAllBranch = $auth->hasRole(\RoleGlobal::$role->viewAllBranch);
 $data = $collection->aggregate([ [ '$match' => [ ($viewAllBranch ? 'storeID' : 'branchID') => ($viewAllBranch ? $user->storeID : $user->branchID), 'staffID' => $user->staffId ] ], [ '$addFields'=> [ 'id' => [ '$toString' => '$_id' ], 'customerID' => [ '$toObjectId' => '$customerID' ], 'hotCustomerID'=> [ '$toObjectId' => '$hotCustomerID' ], ] ], [ '$lookup'=> [ 'from' => 'Customers', 'localField' => 'customerID', 'foreignField' => '_id', 'as' => 'Customers' ] ], [ '$lookup'=> [ 'from' => 'Hot_Customers', 'localField' => 'hotCustomerID', 'foreignField' => '_id', 'as' => 'Hot_Customers' ] ], [ '$sort'=> [ 'timeStart' => -1 ] ], ])->toArray();
 return $this->ok($data);
 }
 public function find($id) {
 $auth = load_auth();
 $user = $auth->getUser();
 $model = Model::load('CallHistorysModel');
 $collection = $model->getCollection();
 $viewAllBranch = $auth->hasRole(\RoleGlobal::$role->viewAllBranch);
 $data = $collection->aggregate([ [ '$addFields'=> [ 'id' => [ '$toString' => '$_id' ], 'customerID' => [ '$toObjectId' => '$customerID' ], 'hotCustomerID'=> [ '$toObjectId' => '$hotCustomerID' ], ] ], [ '$match' => [ ($viewAllBranch ? 'storeID' : 'branchID') => ($viewAllBranch ? $user->storeID : $user->branchID), 'staffID' => $user->staffId, 'id' => $id ] ], [ '$lookup'=> [ 'from' => 'Customers', 'localField' => 'customerID', 'foreignField' => '_id', 'as' => 'Customers' ] ], [ '$lookup'=> [ 'from' => 'Hot_Customers', 'localField' => 'hotCustomerID', 'foreignField' => '_id', 'as' => 'Hot_Customers' ] ], [ '$sort'=> [ 'timeStart' => -1 ] ], ])->toArray();
 return $this->ok($data);
 }
 public function create(CallHistorysModel $model) {
 if($model->isValid()) {
 $saveRes = $model->save();
 if($saveRes) return $this->ok(['success' => true, 'message' => $saveRes]);
 return $this->badRequest('Lưu dữ liệu thất bại');
 }
 return $this->error($model->getErrors());
 }
 public function update(CallHistorysModel $model) {
 if($model->isValid()) {
 if($model->save()) return $this->ok(['success' => true]);
 return $this->badRequest('Lưu dữ liệu thất bại');
 }
 return $this->error($model->getErrors());
 }
 }
