<?php
 namespace VnChocola\Module\Notauth\Visited;
 use Cookie;
 use Exception;
 use TCMS\APIController;
 use Model;
 use Request;
 class IndexController extends APIController {
 public function postSearchNumber() {
 $plate = \Request::get('plate', "");
 $image = \Request::get('image', "");
 $branchID = \Request::get('branchID', "");
 $branchName = \Request::get('branchName', "");
 $camera = \Request::get('camera', "");
 $transactionId = \Request::get('transactionId', "");
 $search_plate = $this->formatPlateNumber($plate);
 $name_tts = "";
 $plate_tts = $this->convertPlateToTTS($search_plate);
 if (!$branchID) {
 return $this->ok(['success' => false, 'message' => 'branchID param not exist']);
 }
 $modelVisitCustomer = Model::load('VisitCustomersModel');
 $modelCars = Model::load('CarsInfoModel');
 $message = "";
 if (strlen($plate) > 0) {
 $modelVisitCustomer->where('search_plate', $search_plate);
 $date = date('Y-m-d');
 $modelVisitCustomer->where("branchID", $branchID);
 $modelVisitCustomer->where("created_at", $date . ' 00:00:00', '>=');
 $modelVisitCustomer->where("created_at", $date . ' 23:59:59', '<=');
 if ($modelVisitCustomer->count()) {
 $modelVistit = Model::load('VisitCustomersModel');
 $modelVistit->where('search_plate', $search_plate);
 $modelVistit->where("branchID", $branchID);
 $modelVistit->where("created_at", $date . ' 00:00:00', '>=');
 $modelVistit->where("created_at", $date . ' 23:59:59', '<=');
 $modelVistit->outDateTime = date('Y-m-d H:i:s');
 $modelVistit->update();
 return $this->ok(['success' => false, 'message' => 'existed']);
 }
 try {
 $tmssCData = $this->getDataFromTMSS($plate);
 if ($tmssCData) {
 $message = $this->updateCustomer($plate, $branchID, $tmssCData);
 }
 }
 catch (Exception $ex) {
 $message = $ex;
 }
 $modelVisitCustomer->plate = $plate;
 $modelVisitCustomer->search_plate = $search_plate;
 $modelVisitCustomer->image = $image;
 $modelVisitCustomer->camera = $camera;
 $modelVisitCustomer->customerName = 'Không tên';
 $modelVisitCustomer->branchID = $branchID;
 $modelVisitCustomer->branch = $branchName;
 $modelCars->where('search_plate', $search_plate);
 $cars = $modelCars->toList();
 if (count($cars) > 0) {
 $car = $cars[0];
 $modelCustomers = Model::load('CustomersModel');
 $modelCustomers->where('id', $car->customerID);
 $customers = $modelCustomers->toList();
 if (count($customers) > 0) {
 $customer = $customers[0];
 $modelVisitCustomer->customerID = $customer->id;
 $modelVisitCustomer->customerName = isset($customer->name) ? $customer->name : '';
 $name_tts = $modelVisitCustomer->customerName;
 $modelVisitCustomer->staffID = isset($customer->staffID) ? $customer->staffID : '';
 $modelStaffs = Model::load('StaffsModel');
 if (!empty($customer->staffID)) {
 $modelStaffs->where('id', $customer->staffID);
 $staffs = $modelStaffs->toList();
 if (count($staffs) > 0) {
 $modelVisitCustomer->staff = isset($staffs[0]->name) ? $staffs[0]->name : '';
 }
 }
 $modelVisitCustomer->email = isset($customer->email) ? $customer->email : '';
;
 $modelVisitCustomer->phone = isset($customer->phone) ? $customer->phone : '';
 $modelVisitCustomer->sex = isset($customer->sex) ? $customer->sex : 1;
 $modelVisitCustomer->birthday = isset($customer->birthday) ? $customer->birthday : '';
 $modelVisitCustomer->cityID = isset($customer->cityID) ? $customer->cityID : '';
 $modelVisitCustomer->districtID = isset($customer->districtID) ? $customer->districtID : '';
 $modelVisitCustomer->address = isset($customer->address) ? $customer->address : '';
 $modelVisitCustomer->notify = isset($customer->notify) ? $customer->notify : 1;
 $modelVisitCustomer->loanCarId = isset($customer->loanCarId) ? $customer->loanCarId : '';
 $modelVisitCustomer->insurranceId = isset($customer->insurranceId) ? $customer->insurranceId : '';
 }
 $modelVisitCustomer->carType = isset($car->type) ? $car->type : '';
 $modelVisitCustomer->carColor = isset($car->color) ? $car->color : '';
 $modelVisitCustomer->old_km = isset($car->km) ? $car->km : "0";
 $modelVisitCustomer->km = isset($car->km) ? $car->km : "0";
 }
 $modelReserves = Model::load('ReservesModel');
 $modelReserves->where('search_plate', $search_plate);
 $modelReserves->where('fromDate', date('Y-m-d') . ' 00:00:00');
 $reserves = $modelReserves->toList();
 if (count($reserves) > 0) {
 $reserve = $reserves[0];
 $dateNow = strtotime("now");
 $reserveDate = strtotime(explode(" ", $reserve->fromDate)[0] . ' ' . $reserve->fromTime . ':00');
 if ($dateNow < ($reserveDate + 15 * 60 * 1000)) {
 $modelVisitCustomer->isVisited = 1;
 }
 else if ($dateNow > ($reserveDate + 15 * 60 * 1000)) {
 $modelVisitCustomer->isVisited = 3;
 }
 else {
 $modelVisitCustomer->isVisited = 2;
 }
 $modelVisitCustomer->reserves = 1;
 $modelVisitCustomer->customerName = isset($reserve->nameCustomer) ? $reserve->nameCustomer : '';
 $name_tts = $modelVisitCustomer->customerName;
 $modelVisitCustomer->staffID = isset($reserve->staffID) ? $reserve->staffID : '';
 if ($modelVisitCustomer->staffID) {
 $modelStaffs = Model::load('StaffsModel');
 $modelStaffs->select('name')->where('id', $reserve->staffID);
 $staffs = $modelStaffs->first();
 if ($staffs) {
 $modelVisitCustomer->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) {
 $modelVisitCustomer->sa = isset($staffs->name) ? $staffs->name : '';
 $modelVisitCustomer->saId = $reserve->CVDV;
 }
 }
 if (isset($reserve->purposeID)) {
 $modelPurposes = Model::load('PurposesModel');
 $modelPurposes->where('id', $reserve->purposeID);
 $purposes = $modelPurposes->toList();
 if (count($purposes) > 0) {
 $modelVisitCustomer->purpose = isset($purposes[0]->title) ? $purposes[0]->title : '';
 }
 }
 }
 }
 else {
 return $this->ok(['success' => false, 'tmss' => $message, 'message' => 'plate fail']);
 }
 if($image) {
 $nimage = $this->saveImageToLocal($image);
 if($nimage) $modelVisitCustomer->image = $nimage;
 }
 $modelVisitCustomer->updated_at = date('Y-m-d H:i:s');
 $modelVisitCustomer->dateTime = $modelVisitCustomer->updated_at;
 if (!$modelVisitCustomer->purpose) $modelVisitCustomer->purpose = '';
 if (!$modelVisitCustomer->staff) $modelVisitCustomer->staff = '';
 if (!$modelVisitCustomer->carType) $modelVisitCustomer->carType = '';
 if (!$modelVisitCustomer->cityID) $modelVisitCustomer->cityID = '';
 if (!$modelVisitCustomer->districtID) $modelVisitCustomer->districtID = '';
 if (!$modelVisitCustomer->address) $modelVisitCustomer->address = '';
 $modelVisitCustomer->transactionId = $transactionId;
 $modelVisitCustomer->compartmentStatus = 0;
 $saveRes = $modelVisitCustomer->save();
 if ($saveRes) {
 $text_tts = $this->getTextSendToTTS($name_tts, $plate_tts, $modelVisitCustomer->purpose, \Request::get('lang_tts', 'vi'));
 $name_messen = '';
 if ($name_tts) {
 $name_messen = $name_tts . ", ";
 }
 else {
 $name_messen = "Khách lạ, ";
 }
 $purpose_messen = "";
 if ($modelVisitCustomer->purpose) {
 $purpose_messen = ", " . $modelVisitCustomer->purpose;
 }
 $this->sendMessageOnesignal($branchID, $modelVisitCustomer->staffID, $name_messen . $plate . $purpose_messen);
 return $this->ok(['success' => true, 'tmss' => $message, 'message' => $saveRes, 'branchID' => $branchID, 'text_tts' => $text_tts, '$text_sst' => $name_tts]);
 }
 return $this->ok(['success' => false, 'tmss' => $message, 'message' => 'fail']);
 }
 private function updateCustomer($plate, $branchID, $data) {
 $model = Model::load('CustomersModel');
 $code = (string)$data->cusId;
 $model->where("code", $code);
 if ($model->count() > 0) {
 $customerModel = Model::load('CustomersModel');
 $customerModel->where("code", $code);
 $customerModel->code = $data->cusId;
 $customerModel->name = $data->carownerName;
 $customerModel->phone = $data->carownerMobil;
 $customerModel->tel = $data->carownerTel;
 $cityID = $this->getCityID($data->provinceName);
 if ($cityID) {
 $customerModel->cityID = $cityID;
 $districtID = $this->getDistrictID($data->districtName);
 if ($districtID) $customerModel->districtID = $districtID;
 }
 $customerModel->address = $data->carownerAdd;
 $customerModel->update();
 return $this->updateCar($plate, $customerModel->id, $data);
 }
 else {
 $customerModel = Model::load('CustomersModel');
 $customerModel->code = $code;
 $customerModel->name = $data->carownerName;
 $customerModel->phone = $data->carownerMobil;
 $customerModel->tel = $data->carownerTel;
 $customerModel->notify = 1;
 $customerModel->cityID = $this->getCityID($data->provinceName);
 $customerModel->districtID = $this->getDistrictID($data->districtName);
 $customerModel->address = $data->carownerAdd;
 $customerModel->staffID = "5ec5e2ed1b370000fb005d40";
 $customerModel->branchID = $branchID;
 $custID = $customerModel->save();
 if ($custID) {
 return $this->updateCar($plate, $custID, $data);
 }
 return "insert customer fail";
 }
 }
 private function updateCar($plate, $custID, $data) {
 $model = Model::load('CarsInfoModel');
 $searchPlate = $this->formatPlateNumber($plate);
 $model->where("code", $data->id);
 if ($model->count() > 0) {
 $CarsModel = Model::load('CarsInfoModel');
 $CarsModel->where("search_plate", $searchPlate);
 $CarsModel->code = $data->id;
 $CarsModel->name = $data->cmName;
 $CarsModel->model = $data->cmCode;
 $CarsModel->color = $data->vcname;
 $CarsModel->color_code = $data->vccode;
 $CarsModel->type = $data->cfCode;
 $CarsModel->km = $data->km;
 $CarsModel->plate = $plate;
 $CarsModel->search_plate = $searchPlate;
 $CarsModel->vin = $data->vinNo;
 $CarsModel->frames = $data->frameNo;
 $CarsModel->engineNo = $data->engineNo;
 $CarsModel->cmCode = $data->cmCode;
 $CarsModel->cfCode = $data->cfCode;
 $CarsModel->cfName = $data->cfName;
 $CarsModel->update();
 return "update info";
 }
 else {
 $CarsModel = Model::load('CarsInfoModel');
 $CarsModel->code = $data->id;
 $CarsModel->name = $data->cmName;
 $CarsModel->model = $data->cmCode;
 $CarsModel->color = $data->vcname;
 $CarsModel->color_code = $data->vccode;
 $CarsModel->type = $data->cfCode;
 $CarsModel->km = $data->km;
 $CarsModel->plate = $plate;
 $CarsModel->search_plate = $searchPlate;
 $CarsModel->vin = $data->vinNo;
 $CarsModel->frames = $data->frameNo;
 $CarsModel->engineNo = $data->engineNo;
 $CarsModel->cmCode = $data->cmCode;
 $CarsModel->cfCode = $data->cfCode;
 $CarsModel->cfName = $data->cfName;
 $CarsModel->customerID = $custID;
 $CarsModel->save();
 return "insert info";
 }
 }
 private function getDataFromTMSS($plate) {
 $plate = $this->formatPlateTMSS($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 [];
 }
 private function getTextSendToTTS($name, $plate_tts, $purpose_tts, $lang) {
 if ($lang == 'vi') {
 if ($purpose_tts) return "Khách hàng, " . $name . ", số xe, " . $plate_tts . ", vừa tới show room, mục đích đến " . $purpose_tts;
 return "Khách hàng, " . $name . ", số xe, " . $plate_tts . ", vừa tới show room";
 }
 if ($lang == 'ja') {
 if ($purpose_tts) return "Khách hàng, " . $name . ", số xe, " . $plate_tts . ", vừa tới show room, mục đích đến " . $purpose_tts;
 return "Khách hàng, " . $name . ", số xe, " . $plate_tts . ", vừa tới show room";
 }
 if ($purpose_tts) return "Khách hàng, " . $name . ", số xe, " . $plate_tts . ", vừa tới show room, mục đích đến " . $purpose_tts;
 return "Khách hàng, " . $name . ", số xe, " . $plate_tts . ", vừa tới show room";
 }
 private function sendTextToTTS($name, $plate_tts) {
 $name = "Khách hàng, " . $name . ", số xe, " . $plate_tts . ", vừa tới show room";
 $env_urls = env('TTS_Server', '');
 if ($env_urls) {
 $urls = json_decode($env_urls);
 foreach ($urls as $url) {
 if ($url) $this->requestToTTS($url, $name);
 }
 }
 return $name;
 }
 private function requestToTTS($obj_url, $name) {
 $ip = $obj_url->ip;
 $http = "http://" . $ip . ":" . $obj_url->port;
 $token = $this->getcookieTokenTTS($ip);
 if (!$token) {
 $token = $this->getTokenTTS($http, $ip);
 }
 $url = $http . "/api/speak?text=" . urlencode($name) . "&lang=vi&token=" . $token;
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_TIMEOUT, 2);
 $output = curl_exec($ch);
 $output = json_decode($output);
 if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 401) {
 $token = $this->getTokenTTS($http, $ip);
 $this->requestToTTS($obj_url, $name);
 }
 curl_close($ch);
 }
 private function setcookieTokenTTS($ip, $token) {
 $ip = str_replace('.', '', $ip);
 Cookie::set($ip, $token);
 }
 private function getcookieTokenTTS($ip) {
 $ip = str_replace('.', '', $ip);
 $token = Cookie::get($ip);
 return $token;
 }
 private function getTokenTTS($url, $ip) {
 $auth = env('TTS_auth', '');
 if ($auth) {
 $authInfo = json_decode($auth);
 $url = $url . "/api/getToken?username=" . $authInfo->username . "&password=" . $authInfo->password;
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_TIMEOUT, 2);
 $output = curl_exec($ch);
 $output = json_decode($output);
 if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
 return "";
 }
 curl_close($ch);
 $this->setcookieTokenTTS($ip, $output->token);
 return $output->token;
 }
 return "";
 }
 public function postTodayVisit() {
 $branchID = Request::get('BranchID');
 $model = Model::load('VisitCustomersModel');
 $model->where("created_at", date('Y-m-d') . ' 00:00:00', '>=');
 $model->where("created_at", date('Y-m-d') . ' 23:59:59', '<=');
 $model->where("notify", 1);
 $model->where("branchID", $branchID);
 $model->orderByDesc("_id");
 return $this->ok($model->toList());
 }
 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 '';
 }
 private function formatPlateTMSS($plate) {
 if ($plate) {
 $plate = trim(strtoupper($plate));
 $plate = str_replace('-', "", $plate);
 $plate = str_replace('.', "", $plate);
 $plate = str_replace(' ', "", $plate);
 return $plate;
 }
 return '';
 }
 private function getCityID($cityName) {
 $model = Model::load('CitysModel');
 $model->where('text', $cityName);
 $citys = $model->toList();
 if (count($citys) > 0) return $citys[0]->id;
 return "";
 }
 private function getDistrictID($districtName) {
 $model = Model::load('DistrictsModel');
 $model->where('text', $districtName);
 $districts = $model->toList();
 if (count($districts) > 0) return $districts[0]->id;
 else {
 $model = Model::load('DistrictsModel');
 $model->like('text', '%' . $districtName);
 $districts = $model->toList();
 if (count($districts) > 0) return $districts[0]->id;
 }
 return "";
 }
 private function convertPlateToTTS($plate) {
 $pl = "";
 for ($i = 0;
 $i < strlen($plate);
 $i++) {
 $char = $plate[$i];
 $pl = $pl . " " . $char;
 }
 return $pl;
 }
 public function test() {
 $var = $_POST["var"];
 $target_dir = "mobile";
 if (!file_exists($target_dir)) {
 mkdir($target_dir, 0777, true);
 }
 $target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
 if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
 return $this->ok(["Message" => "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.", "Status" => "OK", "Url" => $target_dir, "userId" => $_REQUEST["var"]]);
 }
 else {
 return $this->ok(["Message" => "Sorry, there was an error uploading your file.", "Status" => "Error", "Url" => "Error", "userId" => $_REQUEST["var"]]);
 }
 }
 public function test1() {
 echo $this->convertPlateToTTS("54bd187451");
 }
 public function postVideoRecord() {
 $videoUrl = \Request::get('videoUrl', "");
 $branchID = \Request::get('branchID', "");
 $inDirection = \Request::get('inDirection', false);
 $transactionId = \Request::get('transactionId', "");
 if (!$transactionId || !$videoUrl) {
 return $this->ok(['success' => false, 'message' => 'transactionId or videoUrl param not exist']);
 }
 $modelVisitCustomer = Model::load('VisitCustomersModel');
 $data = $modelVisitCustomer->where('transactionId', $transactionId)->first();
 if (!$data) {
 return $this->ok(['success' => false, 'message' => 'transactionId not found']);
 }
 if ($inDirection) $modelVisitCustomer->update([ 'id' => $data->id, 'inVideo' => $videoUrl ]);
 else $modelVisitCustomer->update([ 'id' => $data->id, 'outVideo' => $videoUrl ]);
 return $this->ok(['success' => true, 'message' => $data->id]);
 }
 public function setServerList() {
 return $this->ok(array( "serverName" => env("serverName", ""), "serverUrl" => env("serverUrl", "") ));
 }
 private function sendMessageOnesignal($BranchID, $UserID, $message) {
 $content = array( "en" => $message );
 $headings = array( "en" => 'Khách hàng tới show room' );
 $fields = array( 'app_id' => env("onesignal_appid", ""), 'filters' => array( array("field" => "tag", "key" => "keySendAll", "relation" => "=", "value" => "true"), array("operator" => "OR"), array("field" => "tag", "key" => "keySendBranch", "relation" => "=", "value" => $BranchID), array("operator" => "OR"), array("field" => "tag", "key" => "keySendIDUser", "relation" => "=", "value" => $UserID) ), 'data' => array("foo" => "bar"), 'contents' => $content, 'headings' => $headings );
 $fields = json_encode($fields);
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
 curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json; charset=utf-8', 'Authorization: Basic ' . env("REST_API_KEY_onesignal", "") ));
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
 curl_setopt($ch, CURLOPT_HEADER, FALSE);
 curl_setopt($ch, CURLOPT_POST, TRUE);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 $response = curl_exec($ch);
 curl_close($ch);
 return $response;
 }
 private function saveImageToLocal($url) {
 $ch = curl_init($url);
 $dir = public_path() . 'images';
 if(!file_exists($dir)) {
 mkdir($dir);
 }
 $dir .= '/' . date('d_m_Y');
 if(!file_exists($dir)) {
 mkdir($dir);
 }
 $dir .= '/';
 $file_name = basename($url);
 $save_file_loc = $dir . $file_name;
 $fp = fopen($save_file_loc, 'wb');
 curl_setopt($ch, CURLOPT_FILE, $fp);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 curl_exec($ch);
 curl_close($ch);
 fclose($fp);
 return '/images/' . date('d_m_Y') . '/' . $file_name;
 }
 }
 