<?php
 namespace VnChocola\Module\Api\Seats;
 use TCMS\APIController;
 use Model;
 use VNChocola\Model\SeatsModel;
 class IndexController extends APIController {
 public function getList() {
 $model = Model::load('SeatsModel');
 $limit = \Request::get('limit', 0);
 if($limit > 0){
 $model->limit($limit);
 }
 $data = $model->toList();
 return $this->ok($data);
 }
 public function getByFloor() {
 $floorId = \Request::get('floorId');
 if(!$floorId) return $this->badRequest('Vui lòng truyền floorId');
 $model = Model::load('SeatsModel');
 $data = $model->where('foorID', $floorId)->toList();
 return $this->ok($data);
 }
 public function getByBranch() {
 $branchID = \Request::get('branchID');
 $floorIds = (array)\Request::get('floorIds');
 if(!$branchID || !$floorIds) return $this->badRequest('Vui lòng truyền branchID');
 $auth = load_auth();
 $user = $auth->getUser();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 if($user->branchID != $branchID) return $this->unauthorized(lang('unauthorized.branch'));
 }
 $model = Model::load('SeatsModel');
 $data = $model->whereIn('foorID', $floorIds)->toList();
 return $this->ok($data);
 }
 public function find() {
 $id = \Request::get('data');
 $model = Model::load('SeatsModel');
 $data = $model->find($id);
 if(!$data) return $this->notFound();
 return $this->ok($data);
 }
 public function save() {
 $floorId = \Request::get('floorId');
 if(!$floorId) {
 return $this->badRequest('Vui lòng truyền floorId');
 }
 $seatDels = json_decode(\Request::get('delItems'));
 $seats = json_decode(\Request::get('data'));
 $seatModel = Model::load('SeatsModel');
 $seatInserts = [];
 foreach($seats as $seatConfig) {
 if(isset($seatConfig->id)) {
 $s = $seatModel->find($seatConfig->id);
 if($s) {
 if(isset($seatConfig->config) && isset($seatConfig->config->name)) {
 $s->title = $seatConfig->config->name;
 }
 else if(isset($seatConfig->config) && isset($seatConfig->config->text)) {
 $s->title = $seatConfig->config->text;
 }
 $s->config = json_encode($seatConfig);
 $seatModel->update($s);
 }
 else {
 $title = '';
 if(isset($seatConfig->config) && isset($seatConfig->config->name)) {
 $title = $seatConfig->config->name;
 }
 else if(isset($seatConfig->config) && isset($seatConfig->config->text)) {
 $title = $seatConfig->config->text;
 }
 $seatInserts[] = [ '_id' => $seatConfig->id, 'title' => $title, 'config' => json_encode($seatConfig), 'foorID' => $floorId ];
 }
 }
 }
 if($seatInserts) {
 $seatModel->inserts($seatInserts);
 }
 if($seatDels) {
 $seatModel->deletes($seatDels);
 }
 return $this->ok([ 'success' => true ]);
 }
 }
