<?php
 namespace VnChocola\Module\Home\Index;
 use TCMS\Controller;
 use Model;
 class IndexController extends Controller {
 public function __construct() {
 }
 public function index() {
 $this->notificationInsert();
 view()->hot_negotiation = $this->getNotificationNegotiation('ext-hot-negotiation-list');
 view()->notificationCount = $this->getNotificationNegotiation('all');
 return view();
 }
 private function notificationInsert(){
 $today = $date = date('Y-m-d');
 $date = date('Y-m-d',strtotime($date . "+1 days"));
 $results = $this->workContent($date);
 if(count($results)>0){
 $auth = load_auth();
 $user = $auth->getUser();
 $model = Model::load('NotificationModel');
 $model->where('staffID',$user->staffId);
 $model->where('key','ext-hot-negotiation-list');
 $model->where("created_at", $today . ' 00:00:00', '>=');
 $model->where("created_at", $today . ' 23:59:59', '<=');
 if(count($model->toList()) <= 0){
 $model->staffID = $user->staffId;
 $model->key = "ext-hot-negotiation-list";
 $model->content = count($results)."";
 $model->status = false;
 $model->save();
 }
 else{
 $model->content = count($results)."";
 $model->update();
 }
 }
 }
 private function workContent($date){
 $WcModel = Model::load('WorkContentsModel');
 $WcModel->where("nextContactDate", $date . ' 00:00:00', '>=');
 $WcModel->where("nextContactDate", $date . ' 23:59:59', '<=');
 return $this->searchHotCustomersWithWorkContent($WcModel->toList());
 }
 private function searchHotCustomersWithWorkContent($wContent){
 $hotCustomersData = [];
 $auth = load_auth();
 $model = Model::load('HotCustomersModel');
 if($auth->hasRole(\RoleGlobal::$role->viewHotCustomer)){
 $user = $auth->getUser();
 foreach($wContent as $item){
 if(!$auth->hasRole(\RoleGlobal::$role->viewHotCustomerAll)){
 $model->where('staffID',$user->staffId);
 }
 if(!$auth->hasRole(\RoleGlobal::$role->viewAllBranch)){
 $model->where('branchID',$user->branchID);
 }
 else {
 $model->whereIn('branchID', $user->getBranchsId());
 }
 $hotCustomerData = $model->find($item->HotCustomerID);
 if($hotCustomerData != ""){
 if(!in_array($hotCustomerData,$hotCustomersData)) array_push($hotCustomersData,$hotCustomerData);
 }
 }
 }
 return $hotCustomersData;
 }
 private function getNotificationNegotiation($key){
 $model = Model::load('NotificationModel');
 $auth = load_auth();
 $user = $auth->getUser();
 if($key == 'all'){
 $model->where('staffID',$user->staffId)->where('status',0);
 }
 else{
 $model->where('staffID',$user->staffId)->where('key',$key)->where('status',0);
 }
 return $model->count();
 }
 }
