<?php

namespace App\Http\Controllers\HR;

use App\Fun\Fun;
use App\Model\Hr\HrTravelRequestModel;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Gate;

class HrTravelRequestController extends Controller
{

    function __construct()
    {
       $this->middleware('permission:Travel Request List', ['only' => ['index', 'get_travel_request']]);
       $this->middleware('permission:Travel Request  Create', ['only' => ['create','store']]);
       $this->middleware('permission:Travel Request Show', ['only' => ['view_modal']]);
//       $this->middleware('permission:Travel Request Edit', ['only' => ['edit','update']]);
       $this->middleware('permission:Travel Request Approve', ['only' => ['travel_status']]);
    }

    public function index()
    {
        return view('hr.travel-request.index');
    }

    public function get_travel_request(Request $request)
    {
        $search         = $request->input('search.value');
        $count_total    = HrTravelRequestModel::count();
        $data           = HrTravelRequestModel::select('nso007_hr_travel_request.*', 'users.name')
                        ->join('users', 'users.id', 'nso007_hr_travel_request.emp_id')
                        ->where(function ($query) use ($search){
                            $query->orWhere('users.name', 'LIKE', "%$search%");
                        })
                        ->orderBy('id', 'DESC');
        $count_filter   = $data->count();
        return DataTables::of($data->take(20))
            ->addIndexColumn()
            ->with([
                'recordsTotal' => $count_total,
                'recordsFiltered' => $count_filter
            ])
            ->editColumn('emp_id', function ($data) {
                return optional($data->employee)->name;
            })
            ->editColumn('amount', function ($data) {
                return $data->amount.($data->currency == 'riel'?' ៛':' $');
            })
            ->editColumn('from_date', function ($data){
                return $data->from_date ? date('d-m-Y', strtotime($data->from_date)) : "";
            })
            ->editColumn('to_date', function ($data){
                return $data->to_date ? date('d-m-Y', strtotime($data->to_date)) : "";
            })
            ->editColumn('status', function ($data) {
                $status = '';
                $label = '';
                $check_language = Fun::lang();
                if ($check_language == 'km') {
                    $pending = "រង់ចាំ";
                    $approve = "ទទួលយកសំណើរ";
                    $reject = "បដិសេធសំណើរ";
                } else {
                    $pending = "Pending";
                    $reject = "Rejected";
                    $approve = "Approved";
                }
                if($data->status == 0){
                    $status = $pending;
                    $label = 'warning';
                }
                if($data->status == 1){
                    $status = $approve;
                    $label = 'success';
                }
                if($data->status == 2){
                    $status = $reject;
                    $label = 'danger';
                }
                return ' <a class="viewPopLink label label-'.$label.'" role="button" data-id="' . $data->id . '" data-status="' . $data->status . '"  data-toggle="modal tooltip" data-target="#myModal" data-placement="top" title="'.$status.'">'.$status.'</a>';

            })
            ->addColumn('action', function ($data) {
                $check_language = Fun::lang();
                if ($check_language == 'km') {
                    $edit = "កែសម្រួល";
                    $view = "បង្ហាញ";
                    $delete = "លុបចោល";
                } else {
                    $edit = "Edit";
                    $view = "View";
                    $delete = "Delete";
                }
                $btn_edit = "";
                $btn_view ="";
                $btn_delete="";
                if (Gate::check('Travel Request  Show')) {
                    if($data->status == 0) {
                        $btn_edit .= '<a href="' . route('hr-travel-request.edit', encrypt($data->id)) . '" class="button_warning"><span class="fa fa-pencil-square-o"></span></a>';
                    }
                }
//                if (Gate::check('Travel Request  Edit')) {
                    $btn_view .= ' <a class="button_success viewtravel" role="button" data-id="' . $data->id . '" data-toggle="modal tooltip" data-target="#viewModal" data-placement="top" title="' . $view . '"><span class="fa fa-eye"></span></a>';
//                }
                if (Gate::check('Travel Request  Delete')) {
                    $btn_delete .= '<a class="button_danger btn-delete-travel" role="button" data-id="' . $data->id . '" data-toggle="modal tooltip" data-target="" data-placement="top" title="' . $delete . '"><span class="fa fa-trash"></span></a>';
                }
                return $btn_view.$btn_edit.$btn_delete;
            })
            ->rawColumns(['action' => 'action', 'status' => 'status'])
            ->make(true);
    }

    public function create()
    {
        $emp = User::where('status', 1)->pluck('name', 'id');
        return view('hr.travel-request.create', compact('emp'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'emp_id'            => 'required',
            'travel_by'         => 'required',
            'purpose'           => 'required',
            'from'              => 'required',
            'to'                => 'required',
            'from_date'         => 'required',
            'to_date'           => 'required',
            'currency'          => 'required',
            'amount'            => 'required',

        ]);
        try{
            $travel         = new HrTravelRequestModel();
            $mili           = round(microtime(true) * 1000);
            $mili           = substr_replace($mili,'','0','9');
            $file1          = $request->file1;
            $file2          = $request->file12;
            $file_name1     = '';
            $file_name2     = '';
            if ($file1) {
                $file_name1 = $file1->getClientOriginalName();
                $file_name1 = $request->emp_id.date('d').$mili .'_'. $file_name1;
                $destinationPath = 'assets/attachment_file';
                if ($file1->move($destinationPath, $file_name1)) {
                    $travel->file1 = $file_name1;
                }
            }
            if ($file2) {
                $file_name2 = $file2->getClientOriginalName();
                $file_name2 = $request->emp_id.date('d').$mili .'_'. $file_name2;
                $destinationPath = 'assets/attachment_file';
                if ($file2->move($destinationPath, $file_name2)) {
                    $travel->file2 = $file_name2;
                }
            }
            $travel->emp_id     = $request->emp_id;
            $travel->travel_by  = $request->travel_by;
            $travel->purpose    = $request->purpose;
            $travel->from       = $request->from;
            $travel->to         = $request->to;
            $travel->from_date  = date('Y-m-d',strtotime($request->from_date));
            $travel->to_date    = date('Y-m-d',strtotime($request->to_date));
            $travel->amount     = $request->amount;
            $travel->currency   = $request->currency;
            $travel->note       = $request->note;
            $travel->status     = 0;
            $travel->file1      = $file_name1;
            $travel->file2      = $file_name2;

            $travel->save();

            return redirect()->route('hr-travel-request.index')->with('success', 'Travel request was saved ...');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $emp    = User::where('status', 1)->pluck('name', 'id');
        $travel = HrTravelRequestModel::find(decrypt($id));
        return view('hr.travel-request.edit', compact('emp','travel'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'emp_id'        => 'required',
            'travel_by'     => 'required',
            'purpose'       => 'required',
            'from'          => 'required',
            'to'            => 'required',
            'from_date'     => 'required',
            'to_date'       => 'required',
            'currency'      => 'required',
            'amount'        => 'required',

        ]);
        try{
            $travel         = HrTravelRequestModel::find($id);
            $mili           = round(microtime(true) * 1000);
            $mili           = substr_replace($mili,'','0','9');
            $file1          = $request->file1;
            $file2          = $request->file12;
            $file_name1     = '';
            $file_name2     = '';

            if ($file1) {
                $file_name1 = $file1->getClientOriginalName();
                $file_name1 = $request->emp_id.date('d').$mili .'_'. $file_name1;
                $destinationPath = 'assets/attachment_file';
                if ($file1->move($destinationPath, $file_name1)) {
                    $travel->file1 = $file_name1;
                    if (file_exists(public_path() . '/assets/attachment_file/' . $request->old_file1)) {
                        if ($request->old_file1 != '') {
                            unlink(public_path() . '/assets/attachment_file/' . $request->old_file1);
                        }
                    }
                }
            }else{
                $travel->file1 = $request->old_file1;
            }
            if ($file2) {
                $file_name2 = $file2->getClientOriginalName();
                $file_name2 = $request->emp_id.date('d').$mili .'_'. $file_name2;
                $destinationPath = 'assets/attachment_file';
                if ($file2->move($destinationPath, $file_name2)) {
                    $travel->file2 = $file_name2;
                    if (file_exists(public_path() . '/assets/attachment_file/' . $request->old_file2)) {
                        if ($request->old_file2 != '') {
                            unlink(public_path() . '/assets/attachment_file/' . $request->old_file2);
                        }
                    }
                }
            }else{
                $travel->file2 = $request->old_file2;
            }
            $travel->emp_id         = $request->emp_id;
            $travel->travel_by      = $request->travel_by;
            $travel->purpose        = $request->purpose;
            $travel->from           = $request->from;
            $travel->to             = $request->to;
            $travel->from_date      = date('Y-m-d',strtotime($request->from_date));
            $travel->to_date        = date('Y-m-d',strtotime($request->to_date));
            $travel->amount         = $request->amount;
            $travel->currency       = $request->currency;
            $travel->note           = $request->note;
            $travel->file1          = $file_name1;
            $travel->file2          = $file_name2;

            $travel->update();

            return redirect()->route('hr-travel-request.index')->with('success', 'Travel request was updated ...');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }

    public function destroy($id)
    {
        //
    }
    public function travel_status(Request $request){
        $travel             = HrTravelRequestModel::find($request->id);
        $travel->status     = $request->status;
        $travel->update();
        return redirect()->route('hr-travel-request.index')->with('success','Travel status was change successful...');
    }
    public function view_modal(){
        $travel = HrTravelRequestModel::find($_GET['id']);
        $employee = optional($travel->employee);
        $status = '';
        $check_language = Fun::lang();
        if ($check_language == 'km') {
            $pending = "រង់ចាំ";
            $approve = "ទទួលយកសំណើរ";
            $reject = "បដិសេធសំណើរ";
        } else {
            $pending = "Pending";
            $reject = "Rejected";
            $approve = "Approved";
        }
        if($travel->status == 1){
            $status = '<span class="label label-success">'.$approve.'</span>';
        }
        if($travel->status == 0){
            $status = '<span class="label label-warning">'.$pending.'</span>';
        }
        if($travel->status == 2){
            $status = '<span class="label label-danger">'.$reject.'</span>';
        }
        $amount = $travel->amount.($travel->currency == 'riel'?' ៛':' $');
        $data = [
            'employee'      => $employee->name,
            'travel_by'     => $travel->travel_by,
            'purpose'       => $travel->purpose,
            'from'          => $travel->from,
            'to'            => $travel->to,
            'from_date'     => date('d-m-Y',strtotime($travel->from_date)),
            'to_date'       => date('d-m-Y',strtotime($travel->to_date)),
            'amount'        => $amount,
            'note'          => $travel->note,
            'file1'         => $travel->file1,
            'file2'         => $travel->file2,
            'statuss'       => $status,
        ];
        return response()->json(['datas' => $data]);
    }
    // delete travel request
    public function delete_travel(Request $request)
    {
        $id = $request->delete_id;
        HrTravelRequestModel::where('id', $id)->delete();
        return redirect()->route('hr-travel-request.index')->with('success', 'Deleted Successful!..');
    }
}
