<?php
 namespace VnChocola\Module\Api\Visitcustomers;
 use Exception;
 use TCMS\APIController;
 use Model;
 use VNChocola\Model\VisitCustomersModel;
 use VnChocola\Module\Api\Reserves;
 class IndexController extends APIController {
 public function getList() {
 $model = Model::load('VisitCustomersModel');
 $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('VisitCustomersModel');
 $data = $model->find($id);
 if (!$data) return $this->notFound();
 return $this->ok($data);
 }
 public function create(VisitCustomersModel $model) {
 if ($model->isValid()) {
 if ($model->branchID) {
 $auth = load_auth();
 if (!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 $user = $auth->getUser();
 if ($user->branchID != $model->branchID) return showUnauthorized();
 }
 }
 $fromCompartment = \Request::get('fromCompartment');
 $model->search_plate = $this->formatPlateNumber($model->plate);
 $addByUser = \Request::get('addByUser');
 $reserveId = \Request::get('reserve_id');
 if ($addByUser) {
 $model->where('search_plate', $model->search_plate);
 $date = date('Y-m-d');
 $model->where("branchID", $model->branchID);
 $model->where("created_at", $date . ' 00:00:00', '>=');
 $model->where("created_at", $date . ' 23:59:59', '<=');
 $visit = $model->first();
 if ($visit) {
 if ($fromCompartment) {
 if (isset($visit->compartmentStatus) && $visit->compartmentStatus != 10) {
 return $this->error(lang('visit.enter_on_today'));
 }
 else {
 $model->compartmentStatus = 0;
 $model->id = $visit->id;
 $model->compartmentID = '';
 }
 }
 else {
 if ($visit->status != 10) {
 return $this->error(lang('visit.enter_on_today'));
 }
 else {
 $model->status = 0;
 $model->id = $visit->id;
 }
 }
 }
 }
 if ($addByUser && $reserveId) {
 $rModel = Model::load("ReservesModel");
 $r = $rModel->join("Staffs", "staffID", "id")->find($reserveId);
 if ($r && !empty($r->jbt_Staffs)) {
 $model->staff = $r->jbt_Staffs[0]->name;
 }
 $r = $rModel->join("Staffs", "CVDV", "id")->find($reserveId);
 if ($r && !empty($r->jbt_Staffs)) {
 $model->sa = $r->jbt_Staffs[0]->name;
 $model->saId = $r->CVDV;
 }
 if ($r && isset($r->purposeID)) {
 $modelPurposes = Model::load('PurposesModel');
 $modelPurposes->where('id', $r->purposeID);
 $purposes = $modelPurposes->first();
 if ($purposes) $model->purpose = isset($purposes->title) ? $purposes->title : '';
 }
 if ($r) {
 $model->reserves = 1;
 if (isset($r->nameCustomer) && $r->nameCustomer != 'Không tên') $model->customerName = isset($r->nameCustomer) ? $r->nameCustomer : '';
 $model->staffID = isset($r->staffID) ? $r->staffID : '';
 }
 }
 else if ($addByUser) {
 $modelReserves = Model::load('ReservesModel');
 $modelReserves->where('search_plate', $model->search_plate);
 $modelReserves->where('fromDate', date('Y-m-d') . ' 00:00:00');
 $reserve = $modelReserves->first();
 if ($reserve) {
 $model->reserves = 1;
 if (isset($reserve->nameCustomer) && $reserve->nameCustomer != 'Không tên') $model->customerName = $reserve->nameCustomer;
 $model->staffID = isset($reserve->staffID) ? $reserve->staffID : '';
 if ($model->staffID) {
 $modelStaffs = Model::load('StaffsModel');
 $modelStaffs->select('name')->where('id', $reserve->staffID);
 $staffs = $modelStaffs->first();
 if ($staffs) $model->staff = isset($staffs->name) ? $staffs->name : '';
 }
 if (!empty($reserve->CVDV)) {
 $modelStaffs = Model::load('StaffsModel');
 $modelStaffs->select('name')->where('id', $reserve->CVDV);
 $staffs = $modelStaffs->first();
 if ($staffs) {
 $model->sa = isset($staffs->name) ? $staffs->name : '';
 $model->saId = $reserve->CVDV;
 }
 }
 if (isset($reserve->purposeID)) {
 $modelPurposes = Model::load('PurposesModel');
 $modelPurposes->where('id', $reserve->purposeID);
 $purposes = $modelPurposes->toList();
 if (count($purposes) > 0) {
 $model->purpose = isset($purposes[0]->title) ? $purposes[0]->title : '';
 }
 }
 }
 }
 $toDay = new \DateTime();
 $timeTo = \Request::get('timeTo');
 if ($timeTo) {
 if (strlen($timeTo) == 5) $timeTo .= ":00";
 $toDay = new \DateTime($toDay->format('Y-m-d ') . $timeTo);
 }
 if (trim($model->sa)) {
 $model->saId = $this->findSAIdByName(trim($model->sa));
 }
 $model->created_at = $toDay;
 $model->updated_at = $toDay;
 $model->startJobTime = $toDay;
 $model->returnDateTime = $toDay;
 $model->startDrinkTime = $toDay;
 $model->drinkNotify = 1;
 $model->dateTime = $toDay;
 $model->fromTime = ((int) $toDay->format('H') * 3600) + ((int) $toDay->format('i') * 60) + (int) $toDay->format('s');
 if (!$model->cityID) $model->cityID = '';
 if (!$model->districtID) $model->districtID = '';
 if (!$model->address) $model->address = '';
 if (!$model->birthday) $model->birthday = '';
 if (!$model->address) $model->address = '';
 if (!$model->email) $model->email = '';
 if (!$model->phone) $model->phone = '';
 if (!$model->loanCarId) $model->loanCarId = '';
 if (!$model->insurranceId) $model->insurranceId = '';
 $this->saveToCustomer($model);
 if ($model->customerID) {
 $cusModel = \Model::load('CustomersModel');
 $ccus = $cusModel->find($model->customerID);
 if ($ccus) {
 $model->cityID = isset($ccus->cityID) ? $ccus->cityID : '';
 $model->districtID = isset($ccus->districtID) ? $ccus->districtID : '';
 $model->address = isset($ccus->address) ? $ccus->address : '';
 $model->birthday = isset($ccus->birthday) ? $ccus->birthday : '';
 $model->loanCarId = isset($ccus->loanCarId) ? $ccus->loanCarId : '';
 $model->insurranceId = isset($ccus->insurranceId) ? $ccus->insurranceId : '';
 $model->notify = isset($ccus->notify) ? $ccus->notify : 1;
 if (!$model->email && isset($ccus->email)) $model->email = $ccus->email;
 if (!$model->phone && isset($ccus->phone)) $model->phone = $ccus->phone;
 if (!$model->sex && isset($ccus->sex)) $model->sex = $ccus->sex;
 }
 }
 $saveRes = $model->save();
 if ($saveRes) {
 if ($addByUser) {
 if ($model->birthday && $model->birthday instanceof \DateTime) {
 $model->birthday = $model->birthday->format('Y-m-d H:i:s');
 }
 return $this->ok([ 'success' => true, 'message' => $model->id, 'toDay' => $toDay->format('Y-m-d H:i:s'), 'cityID' => $model->cityID, 'districtID' => $model->districtID, 'address' => $model->address, 'phone' => $model->phone, 'email' => $model->email, 'sex' => $model->sex, 'loanCarId' => $model->loanCarId, 'insurranceId' => $model->insurranceId, 'birthday' => $model->birthday, 'customerName' => $model->customerName ]);
 }
 return $this->ok(['success' => true, 'message' => $saveRes]);
 }
 return $this->badRequest('Lưu dữ liệu thất bại');
 }
 return $this->error($model->getErrors());
 }
 private function randomCusCode($length = 5) {
 $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 $charactersLength = strlen($characters);
 $randomString = '';
 for ($i = 0;
 $i < $length;
 $i++) {
 $randomString .= $characters[rand(0, $charactersLength - 1)];
 }
 return $randomString;
 }
 private function saveToCustomer(VisitCustomersModel $model) {
 $cusModel = Model::load('CustomersModel');
 $carModel = Model::load('CarsInfoModel');
 if ($model->customerID) {
 $updateData = [];
 if ($model->id && $model->search_plate) {
 $car = $carModel->select('customerID')->where('search_plate', $model->search_plate)->first();
 if ($car->customerID != $model->customerID) {
 $model->customerID = $car->customerID;
 }
 }
 if ($model->customerName && $model->customerName != 'Không tên') $updateData['name'] = $model->customerName;
 if ($model->email) $updateData['email'] = $model->email;
 if ($model->phone) $updateData['phone'] = $model->phone;
 if ($model->sex) $updateData['sex'] = (int)$model->sex;
 if ($model->birthday) $updateData['birthday'] = $model->birthday;
 if ($model->cityID) $updateData['cityID'] = $model->cityID;
 if ($model->districtID) $updateData['districtID'] = $model->districtID;
 if ($model->address) $updateData['address'] = $model->address;
 if ($model->id || $model->loanCarId) $updateData['loanCarId'] = $model->loanCarId ? $model->loanCarId : '';
 if ($model->id || $model->insurranceId) $updateData['insurranceId'] = $model->insurranceId ? $model->insurranceId : '';
 if ($updateData) {
 $updateData['id'] = $model->customerID;
 $cusModel->update($updateData);
 }
 if ($model->search_plate) {
 $car = $carModel->where('search_plate', $model->search_plate)->first();
 if (!$car) {
 $carModel->insert([ 'code' => $model->plate, 'name' => $model->carType, 'color' => $model->carColor, 'plate' => $model->plate, 'search_plate' => $model->search_plate, 'customerID' => $model->customerID ]);
 }
 }
 }
 else if ($model->search_plate) {
 $car = $carModel->where('search_plate', $model->search_plate)->first();
 if ($car && $car->customerID) {
 $updateData = [];
 if ($model->customerName) $updateData['name'] = $model->customerName;
 if ($model->email) $updateData['email'] = $model->email;
 if ($model->phone) $updateData['phone'] = $model->phone;
 if ($model->sex) $updateData['sex'] = (int)$model->sex;
 if ($model->birthday) $updateData['birthday'] = $model->birthday;
 if ($model->cityID) $updateData['cityID'] = $model->cityID;
 if ($model->districtID) $updateData['districtID'] = $model->districtID;
 if ($model->address) $updateData['address'] = $model->address;
 if ($updateData) {
 $updateData['id'] = $car->customerID;
 $cusModel->update($updateData);
 }
 $model->customerID = $car->customerID;
 }
 else {
 if ($model->phone) {
 $cus = $cusModel->where('phone', $model->phone)->where('name', $model->customerName)->first();
 if ($cus) {
 $updateData = [];
 if ($model->email) $updateData['email'] = $model->email;
 if ($model->sex) $updateData['sex'] = (int)$model->sex;
 if ($model->birthday) $updateData['birthday'] = $model->birthday;
 if ($model->cityID) $updateData['cityID'] = $model->cityID;
 if ($model->districtID) $updateData['districtID'] = $model->districtID;
 if ($model->address) $updateData['address'] = $model->address;
 if ($updateData) {
 $updateData['id'] = $cus->id;
 $cusModel->update($updateData);
 }
 $model->customerID = $cus->id;
 $carModel->insert([ 'code' => $model->plate, 'name' => $model->carType, 'color' => $model->carColor, 'plate' => $model->plate, 'search_plate' => $model->search_plate, 'customerID' => $model->customerID ]);
 return;
 }
 }
 $user = load_auth()->getUser();
 $cusId = $cusModel->insert([ 'code' => 'KH-' . $this->randomCusCode(), 'name' => $model->customerName, 'email' => $model->email, 'phone' => $model->phone, 'sex' => (int)$model->sex, 'birthday' => $model->birthday, 'cityID' => $model->cityID, 'districtID' => $model->districtID, 'address' => $model->address, 'staffID' => $user->staffId, 'branchID' => $user->branchID ]);
 if ($cusId) {
 $model->customerID = $cusId;
 $carModel->insert([ 'code' => $model->plate, 'name' => $model->carType, 'color' => $model->carColor, 'plate' => $model->plate, 'search_plate' => $model->search_plate, 'customerID' => $model->customerID ]);
 }
 }
 }
 }
 private function findSAIdByName($name) {
 $model = Model::load('StaffsModel');
 $sa = $model->select('id', 'name')->where('name', $name)->first();
 if ($sa) return $sa->id;
 return '';
 }
 public function update(VisitCustomersModel $model) {
 if ($model->isValid()) {
 if ($model->plate) $model->search_plate = $this->formatPlateNumber($model->plate);
 $this->saveToCustomer($model);
 if (trim($model->sa)) {
 $model->saId = $this->findSAIdByName(trim($model->sa));
 }
 if ($model->loanCarId) {
 $loanCarModel = \Model::load('LoanCarModel');
 $loanCar = $loanCarModel->find($model->loanCarId);
 if ($loanCar && $loanCar->status != 3) {
 $loanCarModel->update([ 'id' => $model->loanCarId, 'status' => 2, 'borrower' => $model->customerName . ($model->plate ? (" (" . $model->plate . ")") : '') ]);
 }
 }
 else {
 $visitCusModel = \Model::load('VisitCustomersModel');
 $oldVisitCus = $visitCusModel->select('loanCarId')->find($model->id);
 if (isset($oldVisitCus->loanCarId) && $oldVisitCus->loanCarId) {
 $loanCarModel = \Model::load('LoanCarModel');
 $loanCar = $loanCarModel->find($oldVisitCus->loanCarId);
 if ($loanCar && $loanCar->status != 3) {
 $loanCarModel->update([ 'id' => $oldVisitCus->loanCarId, 'status' => 1, 'borrower' => '' ]);
 }
 }
 }
 if ($model->customerID) {
 $cusModel = Model::load('CustomersModel');
 $cus = $cusModel->find($model->customerID);
 if ($cus) {
 if ($model->customerName && $model->customerName == 'Không tên') $model->customerName = $cus->name;
 if (!$model->cityID && isset($cus->cityID)) $model->cityID = isset($cus->cityID) ? $cus->cityID : '';
 if (!$model->districtID && isset($cus->districtID)) $model->districtID = isset($cus->districtID) ? $cus->districtID : '';
 if (!$model->address && isset($cus->address)) $model->address = isset($cus->address) ? $cus->address : '';
 if (!$model->birthday && isset($cus->birthday)) $model->birthday = isset($cus->birthday) ? $cus->birthday : '';
 if (!$model->loanCarId && isset($cus->loanCarId)) $model->loanCarId = isset($cus->loanCarId) ? $cus->loanCarId : '';
 if (!$model->insurranceId && isset($cus->insurranceId)) $model->insurranceId = isset($cus->insurranceId) ? $cus->insurranceId : '';
 if (!$model->notify && isset($cus->notify)) $model->notify = isset($cus->notify) ? $cus->notify : 1;
 if (!$model->email && isset($cus->email)) $model->email = $cus->email;
 if (!$model->phone && isset($cus->phone)) $model->phone = $cus->phone;
 if (!$model->sex && isset($cus->sex)) $model->sex = $cus->sex;
 }
 }
 if ($model->search_plate) {
 $modelReserves = Model::load('ReservesModel');
 $modelReserves->where('search_plate', $model->search_plate);
 $modelReserves->where('fromDate', date('Y-m-d') . ' 00:00:00');
 $reserve = $modelReserves->first();
 if ($reserve) {
 $model->reserves = 1;
 if (!$model->staff && !empty($reserve->staffID)) {
 $modelStaffs = Model::load('StaffsModel');
 $modelStaffs->select('name')->where('id', $reserve->staffID);
 $staffs = $modelStaffs->first();
 if ($staffs) $model->staff = isset($staffs->name) ? $staffs->name : '';
 }
 if (!$model->sa && !empty($reserve->CVDV)) {
 $modelStaffs = Model::load('StaffsModel');
 $modelStaffs->select('name')->where('id', $reserve->CVDV);
 $staffs = $modelStaffs->first();
 if ($staffs) {
 $model->sa = isset($staffs->name) ? $staffs->name : '';
 $model->saId = $reserve->CVDV;
 }
 }
 if (!$model->purpose && !empty($reserve->purposeID)) {
 $modelPurposes = Model::load('PurposesModel');
 $modelPurposes->where('id', $reserve->purposeID);
 $purposes = $modelPurposes->toList();
 if (count($purposes) > 0) {
 $model->purpose = isset($purposes[0]->title) ? $purposes[0]->title : '';
 }
 }
 }
 else {
 $model->reserves = 0;
 }
 }
 else {
 $model->reserves = 0;
 }
 if ($model->save()) {
 if ($model->birthday && $model->birthday instanceof \DateTime) {
 $model->birthday = $model->birthday->format('Y-m-d H:i:s');
 }
 return $this->ok( [ 'success' => true, 'customerID' => $model->customerID, 'customerName' => $model->customerName, 'cityID' => $model->cityID, 'districtID' => $model->districtID, 'address' => $model->address, 'birthday' => $model->birthday, 'loanCarId' => $model->loanCarId, 'insurranceId' => $model->insurranceId, 'email' => $model->email, 'phone' => $model->phone, 'sex' => $model->sex, 'purpose' => $model->purpose, 'sa' => $model->sa, 'saId' => $model->saId, 'staff' => $model->staff, 'reserves' => $model->reserves ] );
 }
 return $this->badRequest('Lưu dữ liệu thất bại');
 }
 return $this->error($model->getErrors());
 }
 public function delete() {
 $fromCompartment = \Request::get('fromCompartment');
 $id = \Request::get('data');
 if (!$id) return $this->error('Xóa thất bại');
 $model = Model::load('VisitCustomersModel');
 $visitCus = $model->select('id', 'compartmentStatus', 'status', 'sa')->find($id);
 if (!$visitCus) {
 return $this->ok(['success' => true]);
 }
 if ($fromCompartment) {
 if (!isset($visitCus->status) || $visitCus->status == 10) {
 if ($model->delete($id)) return $this->ok(['success' => true]);
 return $this->error('Xóa thất bại. Khách không tồn tại hoặc đã bị xóa!');
 }
 }
 else {
 if (!isset($visitCus->compartmentStatus) || $visitCus->compartmentStatus == 10 || !isset($visitCus->sa) || !$visitCus->sa) {
 if ($model->delete($id)) return $this->ok(['success' => true]);
 return $this->error('Xóa thất bại. Khách không tồn tại hoặc đã bị xóa!');
 }
 }
 if ($fromCompartment) {
 if ($model->update([ 'id' => $id, 'compartmentStatus' => 10 ])) return $this->ok(['success' => true]);
 return $this->error('Xóa thất bại. Khách không tồn tại hoặc đã bị xóa!');
 }
 else {
 if ($model->update([ 'id' => $id, 'status' => 10 ])) return $this->ok(['success' => true]);
 return $this->error('Xóa thất bại. Khách không tồn tại hoặc đã bị xóa!');
 }
 }
 public function postGetTimelineData() {
 $branchID = \Request::get('branchID', "");
 $fromDate = \Request::get('fromDate', "");
 $toDate = \Request::get('toDate', "");
 $model = Model::load('VisitCustomersModel');
 if (strlen($fromDate) > 0 && strlen($toDate) > 0) {
 $fromDate = $this->convertStringToDate($fromDate);
 $toDate = $this->convertStringToDate($toDate);
 $model->where("branchID", $branchID);
 }
 $model->where("compartmentStatus", 10, "<>");
 $model->orderByDesc("_id")->select( "id", "created_at", "search_plate", "outDateTime", "customerName", "image", "plate", "purpose", "staff", "carColor", "carType", "camera", "branchID", "km", "sa", "compartmentID", "compartmentStatus", "dateTime", "deliveryTime" );
 $data = $model->toList();
 return $this->ok(json_encode($data));
 }
 public function searchFrm() {
 $id = \Request::get('id', "");
 $branchID = \Request::get('branchID', "");
 $fromDate = \Request::get('fromDate', "");
 $toDate = \Request::get('toDate', "");
 $plate = \Request::get('plate', "");
 $customerID = \Request::get('customerID', "");
 $plateNumber = \Request::get('plateNumber', "");
 $model = Model::load('VisitCustomersModel');
 if (strlen($id) > 0) {
 return $this->ok(json_encode($model->find($id)));
 }
 if (strlen($plate) > 0) {
 $model->where("plate", $plate);
 }
 if (strlen($customerID) > 0) {
 $model->where("customerID", $customerID);
 }
 if ($plateNumber) {
 $model->where("search_plate", $plateNumber);
 }
 if (strlen($fromDate) > 0 && strlen($toDate) > 0) {
 $fromDate = $this->convertStringToDate($fromDate);
 $toDate = $this->convertStringToDate($toDate);
 $model->where("branchID", $branchID);
 $model->where("created_at", $fromDate . ' 00:00:00', '>=');
 $model->where("created_at", $toDate . ' 23:59:59', '<=');
 }
 $model->orderByDesc("_id")->select( "id", "created_at", "search_plate", "outDateTime", "customerName", "image", "plate", "purpose", "staff", "carColor", "carType", "camera", "branchID", "km", "sa", "compartmentID", "compartmentStatus", "dateTime", "countDownTime", "downTime", "stopDownTime", "isVisited", "deliveryTime" );
 $data = $model->toList();
 foreach ($data as $item) {
 if (!isset($item->search_plate)) {
 $item->search_plate = "";
 }
 $item->visitNumber = $this->countVisitNumber($item->search_plate);
 if (!isset($item->image) || strlen($item->image) <= 0) {
 $item->image = asset('/img/noimg.jpg');
 }
 $item->image = $this->convertTobase64($item->image);
 }
 return $this->ok(json_encode($data));
 }
 private function countVisitNumber($search_plate) {
 $model = Model::load('VisitCustomersModel');
 $model->where("search_plate", $search_plate);
 return $model->count();
 }
 private function convertTobase64($url) {
 return base_url($url);
 try {
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, base_url($url));
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_TIMEOUT, 1);
 $json = curl_exec($ch);
 if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
 curl_close($ch);
 return asset('/img/noimg.jpg');
 }
 else {
 curl_close($ch);
 $image = file_get_contents(base_url($url));
 if ($image !== false) {
 return 'data:image/jpg;base64,' . base64_encode($image);
 }
 return asset('/img/noimg.jpg');
 }
 }
 catch (Exception $ex) {
 return asset('/img/noimg.jpg');
 }
 }
 private function convertStringToDate($value) {
 if (strpos($value, '(') !== false) {
 $startIndex = strpos($value, ' (');
 $value = trim(substr($value, 0, $startIndex));
 $value = date('Y-m-d', strtotime($value));
 return $value;
 }
 return date('Y-m-d', strtotime($value));
 }
 function home_base_url($url) {
 $base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https://' : 'http://';
 $tmpURL = dirname(__FILE__);
 $tmpURL = str_replace(chr(92), '/', $tmpURL);
 $tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'], '', $tmpURL);
 $tmpURL = ltrim($tmpURL, '/');
 $tmpURL = rtrim($tmpURL, '/');
 if (strpos($tmpURL, '/')) {
 $tmpURL = explode('/', $tmpURL);
 $tmpURL = $tmpURL[0];
 }
 if ($tmpURL !== $_SERVER['HTTP_HOST']) $base_url .= $_SERVER['HTTP_HOST'];
 else $base_url .= $tmpURL . '/';
 return $base_url . $url;
 }
 public function getVisitToDay() {
 $branchID = \Request::get('branchId');
 if (!$branchID) return $this->badRequest('Vui lòng truyền chi nhánh');
 $auth = load_auth();
 if (!$auth->hasRole(\RoleGlobal::$role->viewFloorManager)) {
 return showUnauthorized();
 }
 if (!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 $user = $auth->getUser();
 if ($user->branchID != $branchID) return $this->unauthorized(lang('unauthorized.branch'));
 }
 $visitModel = Model::load('VisitCustomersModel');
 $coll = $visitModel->getCollection();
 $data = $coll->find([ '$and' => [ [ '$or' => [ ['status' => 2], ['created_at' => new \MongoDB\BSON\Regex('^' . date('Y-m-d'), 'i')] ] ], [ 'branchID' => $branchID, 'notify' => 1 ] ] ], [ 'sort' => [ 'created_at' => -1 ] ])->toArray();
 $purposesModel = \Model::load('PurposesModel');
 $reservesModel = Model::load('ReservesModel');
 $reservesModel->like('fromDate', date('Y-m-d') . '%');
 $reservesModel->where('branchID', $branchID)->where('status', 4, '<>');
 $reservesModel->orderByDesc('id');
 $reservesModel->join('Staffs', 'staffID', 'id');
 $reservesModel->join('Purposes', 'purposeID', 'id');
 $reserveCus = $reservesModel->toList();
 $visitCus = [];
 $doneCus = [];
 $custodyCus = [];
 $gooutCus = [];
 $seatCus = [];
 foreach ($data as $visit) {
 $visit->id = $visit->_id . '';
 $visit->_id = '';
 if (!empty($visit->plate)) {
 $rK = false;
 foreach ($reserveCus as $k => $reserve) {
 if (empty($reserve->plate)) continue;
 if (empty($reserve->fromDate)) continue;
 if (substr($reserve->fromDate, 0, 10) != substr($visit->created_at, 0, 10)) continue;
 if ($visit->status != 10 && $this->formatPlateNumber($reserve->plate) == $this->formatPlateNumber($visit->plate)) {
 $rK = $k;
 break;
 }
 }
 if ($rK !== false) {
 if (!$visit->purpose && $reserveCus[$rK]->purposeID) {
 $pp = $purposesModel->find($reserveCus[$rK]->purposeID);
 if ($pp) $visit->purpose = $pp->title;
 }
 unset($reserveCus[$rK]);
 $visit->reserves = 1;
 }
 }
 if (!isset($visit->staff)) $visit->staff = '';
 switch ($visit->status) {
 case 0: $visitCus[] = $visit;
 break;
 case 1: $seatCus[] = $visit;
 break;
 case 2: $custodyCus[] = $visit;
 break;
 case 3: $gooutCus[] = $visit;
 break;
 case 4: $doneCus[] = $visit;
 break;
 }
 }
 $cardInfoModel = \Model::load('CarsInfoModel');
 $reserves = [];
 foreach ($reserveCus as $reserve) {
 if (empty($reserve->jbt_Staffs)) continue;
 $staff = $reserve->jbt_Staffs[0]->name;
 if (!empty($reserve->jbt_Purposes)) {
 $purpose = $reserve->jbt_Purposes[0]->title;
 }
 else {
 $purpose = '';
 }
 $fromTime = $reserve->fromTime;
 $toTime = $reserve->toTime;
 if ($reserve->fromDate) {
 $date = explode(' ', $reserve->fromDate)[0];
 $fromTime = $date . ' ' . $fromTime;
 $toTime = $date . ' ' . $toTime;
 }
 $carType = '';
 if (!empty($reserve->plate)) {
 $p = $cardInfoModel->where('search_plate', $this->formatPlateNumber($reserve->plate))->first();
 if ($p) $carType = isset($p->type) ? $p->type : '';
 }
 $reserves[] = [ 'id' => $reserve->id, 'customerName' => $reserve->nameCustomer, 'plate' => isset($reserve->plate) ? $reserve->plate : '', 'carType' => $carType, 'image' => '', 'fromTime' => $fromTime, 'toTime' => $toTime, 'staff' => $staff, 'purpose' => $purpose ];
 }
 $purposeModel = Model::load('PurposesModel');
 $_purposes = $purposeModel->select('id', 'title', 'color')->where('branchID', $branchID)->toList();
 $serverTime = new \DateTime();
 $serverTime = $serverTime->format('Y-m-d H:i:s');
 return $this->ok([ 'visitCus' => $visitCus, 'doneCus' => $doneCus, 'custodyCus' => $custodyCus, 'gooutCus' => $gooutCus, 'seatCus' => $seatCus, 'reserves' => $reserves, 'serverTime' => $serverTime, 'timezone' => date('P'), 'purposes' => $_purposes ]);
 }
 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 findById() {
 $id = \Request::get('id');
 $branchID = \Request::get('branchId');
 if (!$id || !$branchID) return $this->badRequest('Vui lòng truyền đầy đủ thông số');
 $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('VisitCustomersModel');
 $data = $model->where('id', $id)->where('branchID', $branchID)->first();
 if (!$data) return $this->ok([]);
 return $this->ok($data);
 }
 private function convertStringToDateTime($dateTime) {
 if (strpos($dateTime, '(') !== false) {
 $startIndex = strpos($dateTime, ' (');
 $dateTime = trim(substr($dateTime, 0, $startIndex));
 $dateTime = date('Y-m-d H:i:s', strtotime($dateTime));
 }
 return $dateTime;
 }
 public function updateCusSeat() {
 $seatId = \Request::get('seatId');
 $cusId = \Request::get('cusId');
 $index = \Request::get('index', -1);
 $startJobTime = \Request::get('startJobTime');
 if (!$seatId || !$cusId || $index == -1) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $auth = load_auth();
 if (!$auth->hasRole(\RoleGlobal::$role->viewFloorManager)) {
 return $this->unauthorized('Bạn không có quyền quản lý chỗ ngồi');
 }
 $visitModel = Model::load('VisitCustomersModel');
 $updateData = [ 'id' => $cusId, 'status' => 1, 'seatIndex' => $index, 'seatID' => $seatId, 'updated_at' => new \DateTime() ];
 if ($startJobTime) $updateData['startJobTime'] = new \DateTime();
 $visitModel->update($updateData);
 if ($startJobTime) {
 return $this->ok([ 'success' => true, 'startJobTime' => $updateData['startJobTime']->format('Y-m-d H:i:s') ]);
 }
 else {
 return $this->ok([ 'success' => true ]);
 }
 }
 public function updateCusStatus() {
 $cusId = \Request::get('cusId');
 $status = (int) \Request::get('status', -1);
 $purpose = \Request::get('purpose');
 $custody = (int) \Request::get('custody', -1);
 $updateTimeOut = \Request::get('updateTimeOut');
 $fromCompartment = \Request::get('fromCompartment');
 $hold = (int)\Request::get('hold', -1);
 $oldCmStatus = (int)\Request::get('oldCmStatus', -1);
 $reserveids = \Request::get('reserveids', '');
 if (!$cusId || $status == -1) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $auth = load_auth();
 if (!$fromCompartment && !$auth->hasRole(\RoleGlobal::$role->viewFloorManager)) {
 showUnauthorized();
 }
 if (!$fromCompartment && !$auth->hasRole(\RoleGlobal::$role->viewCompartmentManager)) {
 showUnauthorized();
 }
 $visitModel = Model::load('VisitCustomersModel');
 $updateData = [ 'id' => $cusId, 'updated_at' => new \DateTime() ];
 $updateData[$fromCompartment ? 'compartmentStatus' : 'status'] = $status;
 if ($hold != -1) $updateData['dateTime'] = new \DateTime();
 if ($purpose) $updateData['purpose'] = $purpose;
 if ($custody != -1 && !$fromCompartment) $updateData['custody'] = $custody ? 1 : 0;
 if ($status != 1 && !$fromCompartment) $updateData["startDrinkTime"] = date("Y-m-d H:i:s", time() - 7200);
 if ($updateTimeOut && !$fromCompartment) $updateData["returnDateTime"] = new \DateTime();
 if ($updateTimeOut && $fromCompartment) $updateData["compartmentEndJobTime"] = new \DateTime();
 if ($oldCmStatus != -1 && $oldCmStatus != 2 && $status == 2) {
 $updateData["startWashTime"] = new \DateTime();
 $updateData["endWashTime"] = "";
 }
 if ($oldCmStatus != -1 && $oldCmStatus == 2 && $status != 2) $updateData["endWashTime"] = new \DateTime();
 $svrTime = new \DateTime();
 $visitModel->update($updateData);
 if ($reserveids) {
 $this->updateReserveStatus($reserveids, $status);
 }
 return $this->ok([ 'success' => true, 'server_time' => $svrTime->format('Y-m-d H:i:s') ]);
 }
 public function updateDrinks() {
 $drinks = \Request::get('drinks', false);
 $branchID = \Request::get('branchID');
 $cusId = \Request::get('cusId');
 $drinkNotify = (int) \Request::get('drinkNotify', -1);
 $numberOfVisitors = (int) \Request::get('numberOfVisitors', -1);
 $isNewWater = \Request::get('isNewWater');
 $changeDrinkNotify = \Request::get('changeDrinkNotify');
 $multiCus = \Request::get('multiCus');
 if ($drinks === false || !$branchID || !$cusId || $drinkNotify == -1 || $numberOfVisitors == -1) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $auth = load_auth();
 if (!$auth->hasRole(\RoleGlobal::$role->viewFloorManager)) {
 return $this->unauthorized('Bạn không có quyền quản lý chỗ ngồi');
 }
 if (!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 $user = $auth->getUser();
 if ($user->branchID != $branchID) return $this->unauthorized(lang('unauthorized.branch'));
 }
 $visitModel = Model::load('VisitCustomersModel');
 $updateData = [ 'drinkID' => $drinks, 'drinkNotify' => $drinkNotify, "numberOfVisitors" => $numberOfVisitors ];
 if ($changeDrinkNotify == "true") {
 $updateData['startDrinkTime'] = new \DateTime('2020-01-10 00:00:00');
 }
 else {
 if ($isNewWater && $isNewWater == "true") {
 $updateData['startDrinkTime'] = new \DateTime();
 }
 }
 $serverTime = new \DateTime();
 $serverTime = $serverTime->format('Y-m-d H:i:s');
 $saveSuccess = false;
 if ($multiCus) $saveSuccess = $visitModel->whereIn('id', $cusId)->update($updateData);
 else $saveSuccess = $visitModel->where('id', $cusId)->update($updateData);
 return $this->ok([ 'success' => $saveSuccess, 'serverTime' => $serverTime ]);
 }
 public function resetDrinkTime() {
 $branchID = \Request::get('branchID');
 $cusId = \Request::get('cusId');
 if (!$branchID || !$cusId) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $auth = load_auth();
 if (!$auth->hasRole(\RoleGlobal::$role->viewFloorManager)) {
 return $this->unauthorized('Bạn không có quyền quản lý chỗ ngồi');
 }
 if (!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 $user = $auth->getUser();
 if ($user->branchID != $branchID) return $this->unauthorized(lang('unauthorized.branch'));
 }
 $visitModel = Model::load('VisitCustomersModel');
 $updateData = [ 'id' => $cusId, 'startDrinkTime' => new \DateTime('2020-01-10 00:00:00') ];
 return $this->ok([ 'success' => $visitModel->update($updateData) ]);
 }
 private function updateReserveStatus($reseverIds, $status) {
 $reseverIds = explode(',', $reseverIds);
 if (!$reseverIds) return;
 $model = Model::load('ReservesModel');
 $s = 6;
 switch ($status) {
 case 1: $s = 6;
 break;
 case 2: $s = 7;
 break;
 case 3: case 4: $s = 3;
 break;
 }
 foreach ($reseverIds as $id) $model->orWhere('id', $id);
 $model->update(['status' => $s]);
 }
 public function updateCusCompartment() {
 $compartmentID = \Request::get('compartmentID');
 $cusId = \Request::get('cusId');
 $compartmentJobTime = \Request::get('compartmentJobTime');
 $oldCmStatus = (int)\Request::get('oldCmStatus', -1);
 $hold = (int)\Request::get('hold', -1);
 $reserveids = \Request::get('reserveids', '');
 if (!$compartmentID || !$cusId) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $auth = load_auth();
 if (!$auth->hasRole(\RoleGlobal::$role->viewCompartmentManager)) {
 showUnauthorized();
 }
 $visitModel = Model::load('VisitCustomersModel');
 $updateData = [ 'id' => $cusId, 'compartmentStatus' => $hold == -1 ? 1 : 5, 'compartmentID' => $compartmentID, 'updated_at' => new \DateTime() ];
 if ($compartmentJobTime) $updateData['compartmentJobTime'] = new \DateTime();
 if ($oldCmStatus != -1 && $oldCmStatus == 2) $updateData['endWashTime'] = new \DateTime();
 $visitModel->update($updateData);
 if ($reserveids) {
 $this->updateReserveStatus($reserveids, 1);
 }
 $serverTime = new \DateTime();
 if ($compartmentJobTime) {
 return $this->ok([ 'success' => true, 'compartmentJobTime' => $updateData['compartmentJobTime']->format('Y-m-d H:i:s'), 'server_time' => $serverTime->format('Y-m-d H:i:s') ]);
 }
 else {
 return $this->ok([ 'success' => true, 'server_time' => $serverTime->format('Y-m-d H:i:s') ]);
 }
 }
 public function startDownTime() {
 $cusId = \Request::get('cusId');
 $hours = \Request::get('hours', -1);
 $minutes = \Request::get('minutes', -1);
 $seconds = \Request::get('seconds', -1);
 $hold = \Request::get('hold', -1);
 if (!$cusId || $minutes == -1 || $seconds == -1) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $date = new \DateTime();
 date_add($date, date_interval_create_from_date_string($hours . ' hours ' . $minutes . ' minutes ' . $seconds . ' seconds'));
 $nextTime = date_format($date, 'Y-m-d H:i:s');
 $model = Model::load('VisitCustomersModel');
 $upData = [ 'id' => $cusId, 'downTime' => $nextTime, 'runDownTime' => 1, 'deliveryTime' => $nextTime, 'stopDownTime' => $nextTime, 'countDownTime' => (($hours < 10 ? '0' : '') . $hours) . ':' . (($minutes < 10 ? '0' : '') . $minutes) . ':' . (($seconds < 10 ? '0' : '') . $seconds) ];
 if ($hold != -1 && $hold == 1) {
 $upData['compartmentStatus'] = 1;
 $upData['dateTime'] = new \DateTime();
 }
 $model->update($upData);
 return $this->ok([ 'success' => true, 'downTime' => $nextTime ]);
 }
 public function stopDownTime() {
 $cusId = \Request::get('cusId');
 if (!$cusId) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $model = Model::load('VisitCustomersModel');
 $model->update([ 'id' => $cusId, 'runDownTime' => 0, 'stopDownTime' => new \DateTime() ]);
 return $this->ok([ 'success' => true ]);
 }
 public function holdOnCompartment() {
 $cusId = \Request::get('cusId');
 $isHold = \Request::get('hold', -1);
 if (!$cusId || $isHold == -1) return $this->badRequest('Vui lòng truyền đầy đủ thông tin!');
 $model = Model::load('VisitCustomersModel');
 if ($isHold) {
 $model->update([ 'id' => $cusId, 'compartmentStatus' => 5 ]);
 }
 else {
 $model->update([ 'id' => $cusId, 'compartmentStatus' => 1, 'dateTime' => new \DateTime() ]);
 }
 return $this->ok([ 'success' => true ]);
 }
 public function visitcustomer_dashboard() {
 $type = \Request::get('type', "Month");
 $datatime = \Request::get('date', date("Y-m-d"));
 $model = Model::load('VisitCustomersModel');
 $auth = load_auth();
 $user = $auth->getUser();
 if (!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 $model->where('branchID', $user->branchID);
 }
 else {
 $model->whereIn('branchID', $user->getBranchsId());
 }
 if (!$auth->hasRole(\RoleGlobal::$role->viewVisitCustomerAll)) {
 $model->where('staffID', $user->staffId);
 }
 $d = date_create_from_format('Y-m-d', $datatime);
 $day = $d->format('t');
 $month = $d->format('m');
 $year = $d->format('Y');
 if ($type == "Month") {
 $model->where("dateTime", date($year . "-" . $month . "-01 00:00:00"), '>=');
 $model->where("dateTime", date($year . "-" . $month . "-" . $day . " 23:59:59"), '<=');
 }
 else {
 $model->where("dateTime", date($year . "-01-01 00:00:00"), '>=');
 $model->where("dateTime", date($year . "-12-31 23:59:59"), '<=');
 }
 $data = $model->toList();
 $datadashboard = array();
 if ($type == "Month") {
 for ($i = 1;
 $i <= $day;
 $i++) {
 array_push($datadashboard, ["time" => $i, "data" => 0, "dataold" => 0, "datanew" => 0]);
 }
 foreach ($data as $value) {
 $time = date_create_from_format('Y-m-d H:i:u', $value->dateTime);
 $daytime = $time->format('d');
 $datadashboard[intval($daytime) - 1]['data'] = $datadashboard[intval($daytime) - 1]['data'] + 1;
 if (isset($value->customerID)) {
 $datadashboard[intval($daytime) - 1]['dataold'] = $datadashboard[intval($daytime) - 1]['dataold'] + 1;
 }
 else {
 $datadashboard[intval($daytime) - 1]['datanew'] = $datadashboard[intval($daytime) - 1]['datanew'] + 1;
 }
 }
 }
 else {
 for ($i = 1;
 $i <= 12;
 $i++) {
 array_push($datadashboard, ["time" => $i, "data" => 0, "dataold" => 0, "datanew" => 0]);
 }
 foreach ($data as $value) {
 $time = date_create_from_format('Y-m-d H:i:u', $value->dateTime);
 $monthtime = $time->format('m');
 $datadashboard[intval($monthtime) - 1]['data'] = $datadashboard[intval($monthtime) - 1]['data'] + 1;
 if (isset($value->customerID)) {
 $datadashboard[intval($monthtime) - 1]['dataold'] = $datadashboard[intval($monthtime) - 1]['dataold'] + 1;
 }
 else {
 $datadashboard[intval($monthtime) - 1]['datanew'] = $datadashboard[intval($monthtime) - 1]['datanew'] + 1;
 }
 }
 }
 return $this->ok(json_encode($datadashboard));
 }
 public function kpiServiceAdvisor() {
 $type = \Request::get('type', "Day");
 $datatime = \Request::get('date', date("Y-m-d"));
 $d = date_create_from_format('Y-m-d', $datatime);
 $day = $d->format('t');
 $month = $d->format('m');
 $year = $d->format('Y');
 if ($type == "Day") {
 $dayTimeFrom = $datatime;
 $dayTimeto = $datatime;
 }
 else if ($type == "Month") {
 $dayTimeFrom = $year . "-" . $month . "-01";
 $dayTimeto = $year . "-" . $month . "-31";
 }
 else {
 $dayTimeFrom = $year . "-01-01";
 $dayTimeto = $year . "-12-31";
 }
 $auth = load_auth();
 $user = $auth->getUser();
 $model = Model::load('StaffsModel');
 $collection = $model->getCollection();
 $data = $collection->aggregate([ [ '$addFields' => [ 'id' => [ '$toString' => '$_id' ] ] ], [ '$lookup' => [ 'from' => 'users', 'localField' => 'id', 'foreignField' => 'staffId', 'as' => 'users' ] ], [ '$unwind' => [ 'path' => '$users', 'preserveNullAndEmptyArrays' => true ] ], [ '$addFields' => [ '_groupId' => [ '$toObjectId' => '$users.groupId' ] ] ], [ '$lookup' => [ 'from' => 'GroupUsers', 'localField' => '_groupId', 'foreignField' => '_id', 'as' => 'GroupUsers' ] ], [ '$unwind' => [ 'path' => '$GroupUsers', 'preserveNullAndEmptyArrays' => true ] ], [ '$lookup' => [ 'from' => 'Reserves', 'let' => [ 'staffId' => '$id' ], 'pipeline' => [ [ '$match' => [ '$expr' => [ '$and' => [ [ '$eq' => [ '$$staffId', '$CVDV' ] ], [ '$gte' => [ $dayTimeto . ' 23:59:59', '$fromDate' ], ], [ '$gte' => [ '$fromDate', $dayTimeFrom . ' 00:00:00' ], ] ] ] ] ] ], 'as' => 'Reserves' ] ], [ '$lookup' => [ 'from' => 'Reserves', 'let' => [ 'staffId' => '$id' ], 'pipeline' => [ [ '$match' => [ '$expr' => [ '$and' => [ [ '$eq' => [ '$$staffId', '$CVDV' ] ], [ '$ne' => [ '$status', 4 ] ], [ '$ne' => [ '$status', 5 ] ], [ '$ne' => [ '$status', 0 ] ], [ '$gte' => [ $dayTimeto . ' 23:59:59', '$fromDate' ], ], [ '$gte' => [ '$fromDate', $dayTimeFrom . ' 00:00:00' ], ] ] ] ] ] ], 'as' => 'ReservesDone' ] ], [ '$lookup' => [ 'from' => 'Visit_Customers', 'let' => [ 'userId' => '$id' ], 'pipeline' => [ [ '$match' => [ '$expr' => [ '$and' => [ [ '$eq' => [ '$$userId', '$saId' ] ], [ '$gte' => [ $dayTimeto . ' 23:59:59', '$dateTime' ], ], [ '$gte' => [ '$dateTime', $dayTimeFrom . ' 00:00:00' ], ] ] ] ] ] ], 'as' => 'VisitCustomersTotal' ] ], [ '$lookup' => [ 'from' => 'Visit_Customers', 'let' => [ 'userId' => '$id' ], 'pipeline' => [ [ '$match' => [ '$expr' => [ '$and' => [ [ '$eq' => [ '$$userId', '$saId' ] ], [ '$eq' => [ '$status', 4 ] ], [ '$gte' => [ $dayTimeto . ' 23:59:59', '$dateTime' ], ], [ '$gte' => [ '$dateTime', $dayTimeFrom . ' 00:00:00' ], ] ] ] ] ] ], 'as' => 'VisitCustomersDone' ] ], [ '$match' => [ 'GroupUsers.cvdv' => 1, 'branchID' => $user->branchID ] ], [ '$project' => [ '_id' => 0, 'id' => '$id', 'name' => '$name', 'staffId' => '$staffId', 'groupId' => '$groupId', 'storeID' => '$storeID', 'branchID' => '$branchID', 'Reserves' => '$Reserves', 'VisitCustomersTotal' => '$VisitCustomersTotal', 'VisitCustomersDone' => '$VisitCustomersDone', 'VisitCustomersTotalSum' => [ '$size' => '$VisitCustomersTotal' ], 'VisitCustomersDoneSum' => [ '$size' => '$VisitCustomersDone' ], 'ReservesSum' => [ '$size' => '$Reserves' ], 'ReservesDoneSum' => [ '$size' => '$ReservesDone' ] ] ], [ '$sort' => [ 'VisitCustomersTotalSum' => -1, 'ReservesSum' => -1 ] ] ])->toArray();
 return $this->ok($data);
 }
 public function listCustomerVisit() {
 $datatime = \Request::get('date', date("Y-m-d"));
 $auth = load_auth();
 $user = $auth->getUser();
 $model = Model::load('VisitCustomersModel');
 $collection = $model->getCollection();
 $data = $collection->aggregate([ [ '$match' => [ '$or' => [ [ '$and' => [[ 'dateTime' => [ '$gt' => $datatime ], 'status' => [ '$ne' => 0 ], ]], ], [ 'status' => 2 ], [ 'status' => 3 ], [ 'updated_at' => [ '$gt' => $datatime ] ] ] ] ], [ '$addFields' => [ '_seatID' => [ '$convert' => [ 'input' => '$seatID', 'to' => 'objectId', 'onError' => null ] ], '_customerID' => [ '$convert' => [ 'input' => '$customerID', 'to' => 'objectId', 'onError' => null ] ] ] ], [ '$lookup' => [ 'from' => 'Seats', 'localField' => '_seatID', 'foreignField' => '_id', 'as' => 'Seats' ] ], [ '$unwind' => [ 'path' => '$Seats', 'preserveNullAndEmptyArrays' => True ] ], [ '$lookup' => [ 'from' => 'Visit_Customers', 'localField' => 'plate', 'foreignField' => 'plate', 'as' => 'historyVisit' ] ], [ '$unwind' => [ 'path' => '$historyVisit' ] ], [ '$addFields' => [ 'historyVisit._branchID' => [ '$toObjectId' => '$historyVisit.branchID' ] ] ], [ '$lookup' => [ 'from' => 'Branchs', 'localField' => 'historyVisit._branchID', 'foreignField' => '_id', 'as' => 'historyVisit.Branch' ] ], [ '$unwind' => [ 'path' => '$historyVisit.Branch' ] ], [ '$group' => [ '_id' => '$_id', 'plate' => [ '$first' => '$plate' ], 'customerID' => [ '$first' => '$customerID' ], 'customerName' => [ '$first' => '$customerName' ], 'carType' => [ '$first' => '$carType' ], 'carColor' => [ '$first' => '$carColor' ], 'km' => [ '$first' => '$km' ], 'dateTime' => [ '$first' => '$dateTime' ], 'purpose' => [ '$first' => '$purpose' ], 'email' => [ '$first' => '$email' ], 'phone' => [ '$first' => '$phone' ], 'status' => [ '$first' => '$status' ], 'numberOfVisitors' => [ '$first' => '$numberOfVisitors' ], 'sex' => [ '$first' => '$sex' ], 'image' => [ '$first' => '$image' ], 'sa' => [ '$first' => '$sa' ], 'saId' => [ '$first' => '$saId' ], '_customerID' => [ '$first' => '$_customerID' ], 'Seats' => [ '$first' => '$Seats' ], 'REGISTERNO' => [ '$first' => '$REGISTERNO' ], 'historyVisit' => [ '$push' => '$historyVisit' ] ] ], [ '$lookup' => [ 'from' => 'Customers', 'let' => [ 'customerID' => '$_customerID' ], 'pipeline' => [ [ '$match' => [ '$expr' => [ '$eq' => [ '$_id', '$$customerID' ] ] ] ] ], 'as' => 'Customers' ] ], [ '$unwind' => [ 'path' => '$Customers' ] ], [ '$sort' => [ 'dateTime' => -1 ] ] ])->toArray();
 return $this->ok($data);
 }
 }
 