<?php
 namespace VnChocola\Module\Api\Carsinfo;
 use TCMS\APIController;
 use Model;
 use VnChocola\Model\CarsInfoModel;
 class IndexController extends APIController {
 public function getList() {
 $model = Model::load('CarsInfoModel');
 $limit = \Request::get('limit', 0);
 if($limit > 0){
 $model->limit($limit);
 }
 $data = $model->toList();
 return $this->ok($data);
 }
 public function find($id) {
 $model = Model::load('CarsInfoModel');
 $data = $model->find($id);
 if(!$data) return $this->notFound();
 return $this->ok($data);
 }
 private function formatPlateNumber($plate) {
 if($plate) {
 $plate = trim(strtolower($plate));
 $plate = str_replace('-', "", $plate);
 $plate = str_replace('.', "", $plate);
 $plate = str_replace(' ', "", $plate);
 return $plate;
 }
 return '';
 }
 public function create(CarsInfoModel $model) {
 if($model->isValid()) {
 $model->search_plate = $this->formatPlateNumber($model->plate);
 $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(CarsInfoModel $model) {
 if($model->isValid()) {
 if($model->plate) {
 $model->search_plate = $this->formatPlateNumber($model->plate);
 }
 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());
 }
 public function delete() {
 $id = \Request::get('data');
 $model = Model::load('CarsInfoModel');
 if($model->delete($id)) return $this->ok(['success' => true]);
 return $this->error('Xóa thất bại');
 }
 public function searchFrm(){
 $customerID = \Request::get('customerID', "");
 $carModel = Model::load("CarsInfoModel");
 if(strlen($customerID)>0){
 $data = $carModel->where("customerID",$customerID)->toList();
 return $this->ok(json_encode($data));
 }
 }
 public function getCarOfCustomer() {
 $customerID = \Request::get('cusId', "");
 $branchId = \Request::get('branchId', "");
 if(!$customerID || !$branchId) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $auth = load_auth();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 $user = $auth->getUser();
 if($user->branchID != $branchId) return $this->unauthorized(lang('unauthorized.branch'));
 }
 $model = Model::load('CarsInfoModel');
 $model->select('plate', 'type', 'color');
 $model->where('customerID', $customerID);
 return $this->ok($model->toList());
 }
 }
