<?php
 namespace VnChocola\Module\Master\MasterLoanCar;
 use TCMS\Controller;
 use Model;
 use VnChocola\Model\LoanCarModel;
 class IndexController extends Controller {
 public function index() {
 return view();
 }
 public function create() {
 return view();
 }
 public function postCreate(LoanCarModel $model) {
 if($model->isValid()) {
 if($model->save()) return route_redirect('create', lang('master.add_success'));
 view()->addFlashMessage(lang('master.add_fail'), 'error');
 }
 return view($model);
 }
 public function update($id) {
 $model = Model::load('LoanCarModel');
 $data = $model->find($id);
 if(!$data) return route_redirect('index', 'Id không tồn tại', 'error');
 return view($data);
 }
 public function postUpdate(LoanCarModel $model) {
 if($model->isValid()) {
 if($model->save()) return route_redirect('index', lang('master.update_success'));
 view()->addFlashMessage(lang('master.update_fail'), 'error');
 }
 return view($model);
 }
 public function postDelete() {
 $id = \Request::get('data');
 $model = Model::load('LoanCarModel');
 $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'));
 }
 public function status($id, $status) {
 $status = (int)$status;
 if($status < 1 || $status > 3) return route_redirect('index', 'Dữ liệu không hợp lệ', 'error');
 $model = Model::load('LoanCarModel');
 if($status == 1) {
 $model->update([ 'id' => $id, 'status' => $status, 'borrower' => '' ]);
 }
 else {
 $model->update([ 'id' => $id, 'status' => $status ]);
 }
 return route_redirect('index', lang('master.update_success'));
 }
 }
