<?php
 namespace VnChocola\Module\Api\Notification;
 use TCMS\APIController;
 use Model;
 use VnChocola\Model\NotificationModel;
 class IndexController extends APIController {
 public function getList() {
 $model = Model::load('NotificationModel');
 $data = $model->toList();
 return $this->ok($data);
 }
 public function detail($id) {
 $model = Model::load('NotificationModel');
 $data = $model->find($id);
 if(!$data) return $this->notFound();
 return $this->ok($data);
 }
 public function create(NotificationModel $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(NotificationModel $model) {
 if($model->isValid()) {
 if($model->save()) return $this->ok(['success' => true, 'message' => 'Cập nhật thành công']);
 return $this->badRequest('Lưu dữ liệu thất bại');
 }
 return $this->error($model->getErrors());
 }
 public function delete() {
 $id = \Request::get('data');
 $model = Model::load('NotificationModel');
 if($model->delete($id)) return $this->ok(['success' => true, 'message' => 'Xóa thành công']);
 return $this->badRequest('Xóa thất bại');
 }
 public function searchFrm(){
 $key = \Request::get('key','');
 $auth = load_auth();
 $user = $auth->getUser();
 $limit = \Request::get('limit','');
 $model = Model::load('NotificationModel');
 if(strlen($key)>0){
 if($key == 'all'){
 $model->where('staffID',$user->staffId);
 }
 else{
 $model->where('key',$key)->where('staffID',$user->staffId);
 }
 if($limit>0){
 $model->limit(intval($limit));
 }
 $model->orderByDesc('created_at');
 $this->updateStatus($key,$user->staffId);
 return $this->ok($model->toList());
 }
 return $this->ok([]);
 }
 private function updateStatus($key,$staffId){
 $model = Model::load('NotificationModel');
 $model->where('key',$key)->where('staffID',$staffId);
 $model->status = true;
 $model->update();
 }
 }
