<?php
 namespace VnChocola\Module\Api\Customers;
 use TCMS\APIController;
 use Model;
 use VNChocola\Model\CustomersModel;
 class IndexController extends APIController {
 public function getList() {
 $limit = \Request::get('limit', 0);
 $model = Model::load('CustomersModel');
 $auth = load_auth();
 if($auth->hasRole(\RoleGlobal::$role->viewCustomer)){
 $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->viewCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 if($limit > 0){
 $model->limit(intval($limit));
 }
 $data = $model->toList();
 return $this->ok($data);
 }
 return showUnauthorized();
 }
 public function find($id) {
 $model = Model::load('CustomersModel');
 $auth = load_auth();
 if($auth->hasRole(\RoleGlobal::$role->viewCustomer)){
 $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->viewCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 $data = $model->find($id);
 if(!$data) return $this->notFound();
 return $this->ok($data);
 }
 return showUnauthorized();
 }
 public function create(CustomersModel $model) {
 $auth = load_auth();
 if($auth->hasRole(\RoleGlobal::$role->createCustomer)){
 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());
 }
 return showUnauthorized();
 }
 public function update(CustomersModel $model) {
 $auth = load_auth();
 if($auth->hasRole(\RoleGlobal::$role->updateCustomer)){
 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());
 }
 return showUnauthorized();
 }
 public function delete() {
 $id = \Request::get('data');
 $auth = load_auth();
 if($auth->hasRole(\RoleGlobal::$role->deleteCustomer)){
 $model = Model::load('CustomersModel');
 if($model->delete($id)) return $this->ok(['success' => true]);
 return $this->error('Xóa thất bại');
 }
 return showUnauthorized();
 }
 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 searchWidthField(){
 $auth = load_auth();
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomer)){
 return $this->ok([]);
 }
 $all = \Request::get('all', "");
 $id = \Request::get('id', "");
 $phone = \Request::get('phone', "");
 $name = \Request::get('name', "");
 $code = \Request::get('code', "");
 $cityID = \Request::get('cityID', "");
 $districtID = \Request::get('districtID', "");
 $model = Model::load('CustomersModel');
 $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->viewCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 if(strlen($all) > 0 && $all == 'true'){
 return $this->ok(json_encode($model->toList()));
 }
 if(strlen($id) > 0){
 return $this->ok(json_encode($model->find($id)));
 }
else if(strlen($code)>0){
 $model->where("code",$code);
 }
 else if(strlen($phone)>0){
 $model->where("phone",$phone);
 }
 else if(strlen($name)>0){
 $model->where("name",$name);
 }
 else if(strlen($districtID)>0){
 $model->where("districtID",$districtID);
 }
 else if(strlen($cityID)>0){
 $model->where("cityID",$cityID);
 }
 return $this->ok(json_encode($model->toList()));
 }
 public function searchWithCarField(){
 $plate = \Request::get('plate', "");
 if(strlen($plate) > 0){
 $this->getCustomerWithCarField("search_plate",$this->formatPlateNumber($plate));
 }
 }
 private function getCustomerWithCarField($field,$value){
 $data =[];
 $carsData = $this->searchCarsField($field,$value);
 $customersData = $this->searchCustomersWithCars($carsData);
 $data["carsInfo"] = $carsData;
 $data["customers"] = $customersData;
 return $this->ok(json_encode($data));
 }
 private function searchCarsField($field,$value) {
 switch($field){
 case "frames": $dataMode = Model::load('CarsInfoModel');
 return $dataMode->where("frames", $value)->toList();
 case "plate": $dataMode = Model::load('CarsInfoModel');
 return $dataMode->where("search_plate",$this->formatPlateNumber($value))->toList();
 default: return [];
 }
 }
 public function searchWithCar(){
 $plate = \Request::get('plate', "");
 if(strlen($plate) > 0){
 $this->getCustomerWithCar("search_plate",$this->formatPlateNumber($plate));
 }
 }
 private function getCustomerWithCar($field,$value){
 $data =[];
 $carsData = $this->searchCarsInfo($field,$value);
 $customersData = $this->searchCustomersWithCars($carsData);
 $data["carsInfo"] = $carsData;
 $data["customers"] = $customersData;
 return $this->ok(json_encode($data));
 }
 public function searchFrm() {
 $auth = load_auth();
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomer)){
 return $this->ok([]);
 }
 $id = \Request::get('id', "");
 $phone = \Request::get('phone', "");
 $plate = \Request::get('plate', "");
 $name = \Request::get('name', "");
 $code = \Request::get('code', "");
 $frames = \Request::get('frames', "");
 $today = \Request::get('today', "");
 $tomorrow = \Request::get('tomorrow', "");
 $fromDate = \Request::get('fromDate', "");
 $toDate = \Request::get('toDate', "");
 $fromTime = \Request::get('fromTime', "");
 $toTime = \Request::get('toTime', "");
 $TMSS = \Request::get('TMSS', "");
 $user = $auth->getUser();
 if(strlen($id) > 0){
 $model = Model::load('CustomersModel');
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $model->where('branchID',$user->branchID);
 }
 else {
 $model->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 return $this->ok(json_encode($model->find($id)));
 }
 if(strlen($today) > 0 && strlen($tomorrow) > 0 ){
 $model = Model::load('CustomersModel');
 $today = $this->getDateMonth($this->convertStringToDate($today));
 $tomorrow = $this->getDateMonth($this->convertStringToDate($tomorrow));
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $model->where('branchID',$user->branchID);
 }
 else {
 $model->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 $model->like('birthday','%'. $today);
 $cusBirthDayToDays = $model->toList();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $model->where('branchID',$user->branchID);
 }
 else {
 $model->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 $model->like('birthday','%'. $tomorrow);
 $cusBirthDayTomorrows = (array)$model->toList();
 return $this->ok(array_merge($cusBirthDayToDays, $cusBirthDayTomorrows));
 }
 $VisitCustomersModel = Model::load("VisitCustomersModel");
 if(strlen($fromDate)>0 && strlen($toDate)>0){
 $fromDate = $this->convertStringToDate($fromDate);
 $toDate = $this->convertStringToDate($toDate);
 $VisitCustomersModel->where("created_at", $fromDate . ' 00:00:00', '>=');
 $VisitCustomersModel->where("created_at", $toDate . ' 23:59:59', '<=');
 }
 if(strlen($fromTime)>0 && strlen($toTime)>0){
 $VisitCustomersModel->where("fromTime", intval($fromTime), '>=');
 $VisitCustomersModel->where("fromTime", intval($toTime), '<=');
 }
 if((strlen($fromDate)>0 && strlen($toDate)>0)||(strlen($fromTime)>0 && strlen($toTime)>0)){
 $visitCustomersData = $VisitCustomersModel->toList();
 $data = [];
 $customersData = $this->searchCustomersWithHistoryVisit($visitCustomersData);
 $data["carsInfo"] = [];
 $data["visitCustomers"] = [];
 $data["customers"] = $customersData;
 return $this->ok(json_encode($data));
 }
 if(strlen($frames)>0){
 $this->getDataJsonByField("CarsInfoModel","frames",$frames);
 }
else if(strlen($plate)>0){
 $this->getDataJsonByField("CarsInfoModel","search_plate",$this->formatPlateNumber($plate), $TMSS);
 }
else if(strlen($code)>0){
 $this->getDataJsonByField("CustomersModel","code",$code);
 }
else if(strlen($name)>0){
 $this->getDataJsonByField("CustomersModel","name",$name);
 }
 else if(strlen($phone)>0){
 $this->getDataJsonByField("CustomersModel","phone",$phone);
 }
 else{
 $this->getDataJsonByField("CustomersModel");
 }
 }
 private function getDataFromTMSS($plate) {
 $plate = $this->formatPlateNumber($plate);
 $url = env('tmss_url', '') . '?registerNo=' . $plate . '&vinNo=';
 if($url){
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
 $output = curl_exec($ch);
 $obj = json_decode($output);
 if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
 return [];
 }
 curl_close($ch);
 if ($obj) {
 return $obj[0];
 }
 return $obj;
 }
 return [];
 }
 public function getCustomer() {
 $auth = load_auth();
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomer)){
 return $this->ok([]);
 }
 $name = \Request::get('getCustomer', "");
 $plate = "";
 $phone = "";
 $data = [];
 $data=$this->getDataJsonByField("CustomersVisitedModel","name",$name);
 if(!$data){
 $plate=$name;
 }
 if(strlen($plate)>0){
 $data=$this->getDataJsonByField("CustomersVisitedModel","plate",$plate);
 if(!$data){
 $phone=$plate;
 }
 }
 if(strlen($phone)>0){
 $data=$this->getDataJsonByField("CustomersVisitedModel","phone",$phone);
 }
 if(!$data){
 $data["customers"] = "";
 $data["historyVisitInfo"] = "";
 $data["BuriDateHisVisit"] = 0;
 $data["countDateHisVisit"] = 0;
 $data["branch"] = "";
 }
 return $this->ok(json_encode($data));
 }
 private function countDateIn($dateFrom,$dateTo){
 $dateFrom = strtotime($dateFrom);
 $dateTo = strtotime($dateTo);
 $datediff = $dateTo - $dateFrom;
 return round($datediff / (60 * 60 * 24));
 }
 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));
 }
 private function getDateMonth($value) {
 return substr($value,5) . " 00:00:00";
 }
 private function getDataJsonByField($model,$field=null,$value=null,$TMSS=null){
 $data = [];
 switch($model){
 case "CustomersModel": $customersData = $this->searchCustomersInfo($field,$value);
 $carsData = $this->searchCarsWithCustomers($customersData);
 $data["carsInfo"] = $carsData;
 $data["customers"] = $customersData;
 return $this->ok(json_encode($data));
 case "CarsInfoModel": $carsData = $this->searchCarsInfo($field,$value);
 $customersData = $this->searchCustomersWithCars($carsData);
 $data["carsInfo"] = $carsData;
 $data["customers"] = $customersData;
 if ($TMSS == '1') {
 $data["TMSS"] = $this-> getDataFromTMSS($value);
 }
 return $this->ok(json_encode($data));
 case "CustomersVisitedModel": if($field!="phone" && $field!="name"){
 $visitedInfo = $this->searchHistoryVisitWithPlate($value);
 if(!count($visitedInfo)) return false;
 $customersData = $this->searchCustomersWithHistoryVisit($visitedInfo);
 if(!count($customersData)) return false;
 $visitedBranchInfo = $this->searchBranchsWithHistoryVisit($visitedInfo);
 }
else{
 $dataMode = Model::load('CustomersModel');
 $customersData = $dataMode->where($field,$value)->toList();
 if(!count($customersData)) return false;
 $visitedInfo = $this->searchHistoryVisitWithCustomers($customersData[0]->id);
 if(count($visitedInfo)){
 $visitedBranchInfo = $this->searchBranchsWithHistoryVisit($visitedInfo);
 }
else{
 $visitedBranchInfo = 0;
 }
 }
 $data["customers"] = $customersData;
 $data["historyVisitInfo"] = $visitedInfo;
 if(count($visitedInfo)>=2){
 $data["BuriDateHisVisit"] = $this->countDateIn($visitedInfo[1]->created_at,$visitedInfo[0]->created_at);
 }
else{
 $data["BuriDateHisVisit"] = 0;
 }
 $data["countDateHisVisit"] = count($visitedInfo);
 $data["branch"] = $visitedBranchInfo;
 return $data;
 default : $data["carsInfo"] = [];
 $data["customers"] = [];
 return $this->ok(json_encode($data));
 }
 }
 private function searchCarsInfo($field,$value){
 switch($field){
 case "frames": $dataMode = Model::load('CarsInfoModel');
 return $dataMode->where("frames", $value)->toList();
 case "search_plate": $dataMode = Model::load('CarsInfoModel');
 return $dataMode->like("search_plate", $value)->toList();
 case "plate": $dataMode = Model::load('CarsInfoModel');
 return $dataMode->where("plate", $value,"=")->toList();
 default: return [];
 }
 }
 public function updateCusCommonMemo() {
 $cusId = \Request::get('cusId');
 $startJobTime = \Request::get('startJobTime');
 if (!$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');
 }
 $visitModel = Model::load('VisitCustomersModel');
 $updateData = [ 'id' => $cusId, 'commonMemo' => "", 'updated_at' => new \DateTime() ];
 $result=$visitModel->update($updateData);
 if ($result) {
 return $this->ok([ 'success' => true ]);
 }
 else {
 return $this->ok([ 'success' => false ]);
 }
 }
 public function updateCusNotifyVisit() {
 $cusId = \Request::get('cusId');
 $notifyVisit = \Request::get('updateCusNotifyVisit');
 if (!$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');
 }
 $visitModel = Model::load('VisitCustomersModel');
 $updateData = [ 'id' => $cusId, 'notify_visit' => $notifyVisit, 'updated_at' => new \DateTime() ];
 $result=$visitModel->update($updateData);
 if ($result) {
 return $this->ok([ 'success' => true ]);
 }
 else {
 return $this->ok([ 'success' => false ]);
 }
 }
 private function searchCustomersInfo($field,$value){
 $dataMode = Model::load('CustomersModel');
 $auth = load_auth();
 $user = $auth->getUser();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $dataMode->where('branchID',$user->branchID);
 }
else {
 $dataMode->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $dataMode->where('staffID',$user->staffId);
 }
 switch($field){
 case "name": return $dataMode->like("name", $value)->toList();
 case "code": return $dataMode->like("code", $value)->toList();
 case "phone": return $dataMode->like("phone", $value)->toList();
 default: $dataMode->limit(100);
 return $dataMode->toList();
 }
 }
 private function searchCarsWithCustomers($customers){
 $carsData = [];
 $carInforMode = Model::load('CarsInfoModel');
 foreach($customers as $customer){
 $carDatas = $carInforMode->where("customerID",$customer->id)->toList();
 foreach($carDatas as $carData) if(!in_array($carData,$carsData)) array_push($carsData,$carData);
 }
 return $carsData;
 }
 private function searchCustomersWithCars($cars){
 $customersData = [];
 $dataMode = Model::load('CustomersModel');
 $auth = load_auth();
 $user = $auth->getUser();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $dataMode->where('branchID',$user->branchID);
 }
 else {
 $dataMode->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $dataMode->where('staffID',$user->staffId);
 }
 $customers = $dataMode->toList();
 if(count($customers)>0){
 foreach($cars as $car){
 foreach($customers as $customer){
 if($customer->id == $car->customerID){
 if(!in_array($customer,$customersData)) array_push($customersData,$customer);
 }
 }
 }
 }
 return $customersData;
 }
 private function searchCustomersWithHistoryVisit($data){
 $customersData = [];
 $dataMode = Model::load('CustomersModel');
 $auth = load_auth();
 $user = $auth->getUser();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $dataMode->where('branchID',$user->branchID);
 }
 else {
 $dataMode->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $dataMode->where('staffID',$user->staffId);
 }
 foreach($data as $item){
 if(isset($item->customerID)){
 $customerData = $dataMode->find($item->customerID);
 if($customerData != ""){
 if(!in_array($customerData,$customersData)) array_push($customersData,$customerData);
 }
 }
 }
 return $customersData;
 }
 private function searchBranchsWithHistoryVisit($data){
 $branchData = [];
 $branchsMode = Model::load('BranchsModel');
 foreach($data as $history){
 $branchDatas = $branchsMode->where("id",$history->branchID)->toList();
 foreach($branchDatas as $branchsData) if(!in_array($branchsData,$branchData)) array_push($branchData,$branchsData);
 }
 return $branchData;
 }
 private function searchHistoryVisitWithPlate($plate){
 $dataMode = Model::load('VisitCustomersModel');
 $auth = load_auth();
 $user = $auth->getUser();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $dataMode->where('branchID',$user->branchID);
 }
else {
 $dataMode->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $dataMode->where('staffID',$user->staffId);
 }
 $dataMode->where("plate",$plate,"=");
 $dataMode->orderByDesc("created_at");
 $historyVisitData = $dataMode->toList();
 return $historyVisitData;
 }
 private function searchHistoryVisitWithCustomers($customerId){
 $dataMode = Model::load('VisitCustomersModel');
 $auth = load_auth();
 $user = $auth->getUser();
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $dataMode->where('branchID',$user->branchID);
 }
else {
 $dataMode->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $dataMode->where('staffID',$user->staffId);
 }
 $dataMode->where("customerID",$customerId,"=");
 $dataMode->orderByDesc("created_at");
 $historyVisitData = $dataMode->toList();
 return $historyVisitData;
 }
 public function check_code(){
 $code = \Request::get('code', "");
 $model = Model::load('CustomersModel');
 $model->where("code", $code);
 $data = $model->count();
 return $this->ok($data);
 }
 public function get_code(){
 $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 $charactersLength = strlen($characters);
 do {
 $randomString = 'KH-';
 for ($i = 0;
 $i < 6;
 $i++) {
 $randomString .= $characters[rand(0, $charactersLength - 1)];
 }
 $model = Model::load('CustomersModel');
 $model->where("code", $randomString);
 $data = $model->count();
 }
 while ($data != 0);
 return $this->ok($randomString);
 }
 public function searchWithKey() {
 $key = \Request::get('key');
 $branchID = \Request::get('branchID');
 if(!$key || !$branchID) 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'));
 }
 $model = Model::load('CustomersModel');
 $coll = $model->getCollection();
 $customers = $coll->find( [ '$and' => [ [ '$or' => [ ['code' => $key], ['name' => new \MongoDB\BSON\Regex($key, 'i')], ['email' => new \MongoDB\BSON\Regex($key, 'i')], ['phone' => new \MongoDB\BSON\Regex($key . '$', 'i')] ] ], [ 'branchID' => $branchID ] ] ], [ 'projection' => [ '_id' => 1, 'name' => 1, 'sex' => 1, 'phone' => 1, 'email' => 1 ], 'sort' => [ 'name' => 1 ], 'limit' => 20 ] )->toArray();
 if(!$customers) $customers = [];
 foreach($customers as &$cus) {
 $cus->id = $cus->_id . '';
 }
 $carModel = Model::load('CarsInfoModel');
 $cars = $carModel->select('customerID')->like('search_plate', $this->formatPlateNumber($key))->toList();
 $cusIds = [];
 foreach($cars as $car) {
 $isExist = false;
 foreach($customers as $cus) {
 if($cus->id == $car->customerID) {
 $isExist = true;
 break;
 }
 }
 if(!$isExist) $cusIds[] = $car->customerID;
 }
 if($cusIds) {
 $cusList = $model->select('name', 'sex', 'phone', 'email')->whereIn('id', $cusIds)->toList();
 foreach($cusList as $cus) {
 $customers[] = $cus;
 }
 }
 return $this->ok($customers);
 }
 public function searchWithPlateNumber() {
 $plate = $this->formatPlateNumber(\Request::get('plate'));
 $branchID = \Request::get('branchId');
 if(!$plate || !$branchID) 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'));
 }
 $model = Model::load('CarsInfoModel');
 $model->select('customerID', 'type')->where('search_plate', $plate);
 $carInfo = $model->first();
 if(!$carInfo) return $this->ok(['success' => false]);
 $cusModel = Model::load('CustomersModel');
 $cus = $cusModel->select('name', 'phone', 'email', 'sex', 'loanCarId', 'insurranceId', 'cityID', 'districtID', 'address', 'birthday')->find($carInfo->customerID);
 if(!$cus) return $this->ok(['success' => false, 'not_found' => true]);
 return $this->ok([ 'name' => isset($cus->name) ? $cus->name : '', 'phone' => isset($cus->phone) ? $cus->phone : '', 'email' => isset($cus->email) ? $cus->email : '', 'sex' => isset($cus->sex) ? $cus->sex : 0, 'cardType' => isset($carInfo->type) ? $carInfo->type : '', 'loanCarId' => isset($cus->loanCarId) ? $cus->loanCarId : '', 'insurranceId' => isset($cus->insurranceId) ? $cus->insurranceId : '', 'cityID' => isset($cus->cityID) ? $cus->cityID : '', 'districtID' => isset($cus->districtID) ? $cus->districtID : '', 'address' => isset($cus->address) ? $cus->address : '', 'birthday' => isset($cus->birthday) ? $cus->birthday : '', ]);
 }
 public function LoadData(){
 $customers = \Request::get('customers',"");
 $citys = \Request::get('citys',"");
 $districts = \Request::get('districts',"");
 $positions = \Request::get('positions',"");
 $companyType = \Request::get('companyType',"");
 $staffs = \Request::get('staffs',"");
 $branchs = \Request::get('branchs',"");
 $cars = \Request::get('cars',"");
 $codeWorks = \Request::get('codeWorks',"");
 $purposes = \Request::get('purposes',"");
 $cvdvs = \Request::get('cvdvs',"");
 $carcompartments = \Request::get('carcompartments',"");
 $auth = load_auth();
 $user = $auth->getUser();
 $customerData = [];
 if(strlen($customers)>0){
 $model = Model::load('CustomersModel');
 if($auth->hasRole(\RoleGlobal::$role->viewCustomer)){
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $model->where('branchID',$user->branchID);
 }
 else {
 $model->whereIn('branchID', $user->getBranchsId());
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 $model->limit(1000);
 $customerData = $model->toList();
 }
 }
 $cvdvData = [];
 if(strlen($cvdvs)>0){
 $groupUserModel = Model::load('GroupUserModel');
 $groupUserModel->where('branchID',$user->branchID);
 $groupUsers = $groupUserModel->select('id','name')->where('cvdv', 1)->toList();
 $groupUserIds = [];
 foreach($groupUsers as $g) {
 $groupUserIds[] = $g->id;
 }
 $model = Model::load('UserModel');
 $users = $model->select('id', 'staffId')->whereIn('groupId', $groupUserIds)->toList();
 $userIds = [];
 foreach($users as $u) {
 if(isset($u->staffId)) {
 $userIds[] = $u->staffId;
 }
 }
 $model = Model::load('StaffsModel');
 $cvdvData = $model->whereIn('id', $userIds)->toList();
 }
 $citysData = [];
 if(strlen($citys)>0){
 $model = Model::load('CitysModel');
 $citysData = $model->toList();
 }
 $districtsData = [];
 if(strlen($districts)>0){
 $model = Model::load('DistrictsModel');
 $districtsData = $model->toList();
 }
 $positionsData = [];
 if(strlen($positions)>0){
 $model = Model::load('PositionsModel');
 $model->where("storeID",$user->storeID);
 $positionsData = $model->toList();
 }
 $companyTypesData = [];
 if(strlen($companyType)>0){
 $model = Model::load('CompanyTypesModel');
 $companyTypesData = $model->toList();
 }
 $staffsData = [];
 if(strlen($staffs)>0){
 $model = Model::load('StaffsModel');
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $model->where('branchID',$user->branchID);
 }
else {
 $model->whereIn('branchID', $user->getBranchsId());
 }
 $model->where("name","sadmin","<>");
 $staffsData = $model->toList();
 }
 $branchsData = [];
 if(strlen($branchs)>0){
 $model = Model::load('BranchsModel');
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $user = $auth->getUser();
 $model->where('id',$user->branchID);
 }
 else {
 $user = $auth->getUser();
 $model->where('storeID',$user->storeID);
 }
 $branchsData = $model->toList();
 }
 $carsData = [];
 if(strlen($cars)>0){
 $model = Model::load('CarsModel');
 $user = $auth->getUser();
 $model->where('storeID',$user->storeID);
 $carsData = $model->toList();
 }
 $codeworksData = [];
 if(strlen($codeWorks)>0){
 $model = Model::load('CodeWorksModel');
 $codeworksData = $model->toList();
 }
 $purposesData = [];
 if(strlen($purposes)>0){
 $model = Model::load('PurposesModel');
 $purposesData = $model->toList();
 }
 $carcompartmentsData = [];
 if(strlen($carcompartments)>0){
 $model = Model::load('CarCompartmentsModel');
 $model->orderBy("group")->orderBy("sort_index");
 $carcompartmentsData = $model->toList();
 }
 return $this->ok([ 'customers' => $customerData, 'citys' => $citysData, 'districts' => $districtsData, 'positions' => $positionsData, 'companyType' => $companyTypesData, 'staffs' => $staffsData, 'branchs' => $branchsData, 'cars' => $carsData, 'codeWorks' => $codeworksData, 'purposes' => $purposesData, 'cvdvs' => $cvdvData, 'carcompartments' => $carcompartmentsData ]);
 }
 }
