<?php

namespace App\Http\Controllers\HR;

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

class HrEmployeeLoanController extends Controller
{

    function __construct()
    {
       $this->middleware('permission:Loan List', ['only' => ['index', 'get_emp_loan']]);
       $this->middleware('permission:Loan Create', ['only' => ['create','store']]);
       $this->middleware('permission:Loan Edit', ['only' => ['edit','update']]);
    }
    public function index()
    {
        return view('hr.employee-loan.index');
    }

    /**get loan */
    public function get_emp_loan(Request $request)
    {
        $search         = $request->input('search.value');
        $count_total    = HrEmployeeLoanModel::count();
        $count_filter   = HrEmployeeLoanModel::count();
        $data           = HrEmployeeLoanModel::select('nso007_hr_emp_loans.*', 'users.name')
                                            ->join('users', 'users.id', 'nso007_hr_emp_loans.emp_id')
                                            ->where(function($query) use ($search){
                                                $query->orWhere('users.name', 'LIKE', "%$search%");
                                                $query->orWhere('nso007_hr_emp_loans.type_loan', 'LIKE', "%$search%");
                                            })
                                            ->orderBy('id', 'DESC');
        return DataTables::of($data->take(20))
                        ->addIndexColumn()
                        ->with([
                            'recordsTotal' => $count_total,
                            'recordsFiltered' => $count_filter
                        ])
                        ->addColumn('employee_name', function($data){
                            return optional($data->get_employee)->name;
                        })
                        ->editColumn('date', function($data){
                            return $data->date ? date('d-m-Y', strtotime($data->date)) : "";
                        })
                        ->editColumn('start_date', function($data){
                            return $data->start_date ? date('d-m-Y', strtotime($data->start_date)) : "";
                        })
                        ->editColumn('end_date', function($data){
                            return $data->end_date ? date('d-m-Y', strtotime($data->end_date)) : "";
                        })
                        ->editColumn('disbursement', function($data){
                            return $data->disbursement ? date('d-m-Y', strtotime($data->disbursement)) : "";
                        })
                        ->addColumn('action', function ($data) {
                            $check_language = Fun::lang();
                            if ($check_language == 'km') {
                                $edit = "កែសម្រួល";
                                $delete = "លុបចោល";
                            } else {
                                $edit = "Edit";
                                $delete = "Delete";
                            }
                            $btn_edit ="";
                            $btn_delete="";
                            if(Gate::check('Loan Edit')) {
                                $btn_edit .= '<a href="' . route('hr-emp-loan.edit', $data->id) . '" class="button_warning"><span class="fa fa-pencil-square-o"></span></a>';
                            }
                            if(Gate::check('Loan Delete')) {
                                $btn_delete .= '<a class="button_danger btn-delete-loan" data-id="' . $data->id . '"><span class="fa fa-trash-o"></span></a>';
                            }
                            return $btn_edit.$btn_delete;
                        })
                        ->rawColumns(['action' => 'action'])
                        ->make(true);
    }

    public function create()
    {
        $emp = User::where('status', 1)->pluck('name', 'id');
        return view('hr.employee-loan.create',[
            'emp' => $emp
        ]);
    }


    public function store(Request $request)
    {

        $this->validate($request, [
            'emp_id'            => 'required',
            'loan_type'         => 'required',
            'month'             => 'required',
            'amount'            => 'required',
            'date'              => 'required',
            'interest'          => 'required',
            'duration'          => 'required',
            'disbursement'      => 'required'
        ]);

        try{
            $month   = $request->month;
            $month   = explode('-', $month);
            $f_month = isset($month[0]) ? $month[0] : date('m');
            $f_year  = isset($month[1]) ? $month[1] : date('y');

            $emp_loan = new HrEmployeeLoanModel();
            $emp_loan->emp_id           = $request->emp_id;
            $emp_loan->type_loan        = $request->loan_type;
            $emp_loan->f_month          = $f_month;
            $emp_loan->f_year           = $f_year;
            $emp_loan->amount           = $request->amount;
            $emp_loan->date             = date('Y-m-d', strtotime($request->date));
            $emp_loan->interest         = $request->interest;
            $emp_loan->duration         = $request->duration;
            $emp_loan->start_date       = date('Y-m-d', strtotime($request->start_date));
            $emp_loan->end_date         = date('Y-m-d', strtotime($request->end_date));
            $emp_loan->disbursement     = date('Y-m-d', strtotime($request->disbursement));
            $emp_loan->remark           = $request->remark;
            $emp_loan->save();


            return redirect()->route('hr-emp-loan.index')->with('success','Added Successful!');
        }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');
        $emp_loan = HrEmployeeLoanModel::find($id);

        $m_y = $emp_loan->f_year.'-'.$emp_loan->f_month;
        $month_year = date('m-Y', strtotime($m_y));

        return view('hr.employee-loan.edit', compact('emp','emp_loan', 'month_year'));
    }


    public function update(Request $request, $id)
    {
        //dd($request->all());
        $this->validate($request, [
            'emp_id'            => 'required',
            'loan_type'         => 'required',
            'month'             => 'required',
            'amount'            => 'required',
            'date'              => 'required',
            'interest'          => 'required',
            'duration'          => 'required',
            'disbursement'      => 'required'
        ]);

        $month   = $request->month;
        $month   = explode('-', $month);
        $f_month = isset($month[0]) ? $month[0] : date('m');
        $f_year  = isset($month[1]) ? $month[1] : date('y');

        $date             = date('Y-m-d', strtotime($request->date));
        $start_date       = date('Y-m-d', strtotime($request->start_date));
        $end_date         = date('Y-m-d', strtotime($request->end_date));
        $disbursement     = date('Y-m-d', strtotime($request->disbursement));

        $emp_loan = HrEmployeeLoanModel::find($id);
        $emp_loan->emp_id           = $request->emp_id;
        $emp_loan->type_loan        = $request->loan_type;
        $emp_loan->f_month          = $f_month;
        $emp_loan->f_year           = $f_year;
        $emp_loan->amount           = $request->amount;
        $emp_loan->date             = $date;
        $emp_loan->interest         = $request->interest;
        $emp_loan->duration         = $request->duration;
        $emp_loan->start_date       = $start_date;
        $emp_loan->end_date         = $end_date;
        $emp_loan->disbursement     = $disbursement;
        $emp_loan->remark           = $request->remark;
        $emp_loan->update();


        return redirect()->route('hr-emp-loan.index')->with('success','Updated Successful!');
    }


    public function destroy($id)
    {
        //
    }

    /**delete loan */
    public function delete_loan(Request $request)
    {
        $id = $request->delete_id;
        HrEmployeeLoanModel::where('id', $id)->delete();

        return redirect()->route('hr-emp-loan.index')->with('success', 'Deleted Successful..');
    }
}
