<?php
 namespace VnChocola\Module\Master\MasterStaffs;
 use TCMS\Controller;
 use Model;
 use VnChocola\Model\StaffsModel;
 class IndexController extends Controller {
 public function index() {
 $auth = load_auth();
 view()->hasCreateRole = $auth->hasRole(\RoleGlobal::$role->createStaff);
 view()->hasUpdateRole = $auth->hasRole(\RoleGlobal::$role->updateStaff);
 view()->hasDeleteRole = $auth->hasRole(\RoleGlobal::$role->deleteStaff);
 return view();
 }
 public function create() {
 return view();
 }
 public function postCreate(StaffsModel $model) {
 if($model->isValid()) {
 if($model->save()) return route_redirect('create', lang('master.add_success'));
 view()->addErrorMessage('error', lang('master.add_fail'));
 }
 return view($model);
 }
 public function update($id) {
 $model = Model::load('StaffsModel');
 $data = $model->find($id);
 if(!$data) return route_redirect('index', lang('master.id_not_found'), 'error');
 return view($data);
 }
 private function setBranchAndStoreIdForUser($userModel, $staff) {
 $branchModel = Model::load('BranchsModel');
 $branch = $branchModel->select('id', 'storeID')->find($staff->branchID);
 if(!$branch) return false;
 $userModel->storeID = $branch->storeID;
 $userModel->branchID = $staff->branchID;
 $userModel->avatar = $staff->image;
 return true;
 }
 private function updateBranchAndStoreIdForUser($staff) {
 $userModel = Model::load('UserModel');
 $users = $userModel->select('id', 'branchID', 'storeID')->where('staffId', $staff->id)->toList();
 foreach($users as $user) {
 if($user->branchID != $staff->branchID) {
 if(!$this->setBranchAndStoreIdForUser($user, $staff)) return false;
 if(!$userModel->update($user)) return false;
 }
 else if(isset($user->avatar) && $user->avatar != $staff->image) {
 $user->avatar = $staff->image;
 if(!$userModel->update($user)) return false;
 }
 }
 return true;
 }
 public function postUpdate(StaffsModel $model) {
 if($model->isValid()) {
 if(!$this->updateBranchAndStoreIdForUser($model)) {
 view()->addErrorMessage('error', lang('master.update_fail'));
 return view($model);
 }
 if($model->save()) return route_redirect('index', lang('master.update_success'));
 view()->addErrorMessage('error', lang('master.update_fail'));
 }
 return view($model);
 }
 public function postDelete() {
 $id = \Request::get('data');
 $model = Model::load('StaffsModel');
 $isSuccess = $model->delete($id);
 if(\Request::isAjax()) return json(['success' => $isSuccess, 'message' => $isSuccess ? lang('master.detele_success') : lang('master.detele_fail')]);
 return route_redirect('index', $isSuccess ? lang('master.detele_success') : lang('master.detele_fail'));
 }
 }
