<?php

namespace App\Http\Controllers\HR;

use App\Fun\Fun;
use App\Model\Hr\HrHolidayModel;
use App\Model\Hr\PreHolidayModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\DataTables;
use Importer;
use Illuminate\Support\Facades\Gate;

class HrHolidayController extends Controller
{


    function __construct()
    {
      $this->middleware('permission:Holiday List', ['only' => ['index','get_holiday']]);
      $this->middleware('permission:Holiday Create', ['only' => ['create','store']]);
      $this->middleware('permission:Holiday Edit', ['only' => ['edit','update']]);
    }

    public function index()
    {
        return view('hr.holiday.index');
    }

    public function get_holiday()
    {
        $count_total    = PreHolidayModel::where('status', 1)->count();
        $hol            = PreHolidayModel::where('status', 1)->orderBy('year', 'DESC');
        $count_filter   = $hol->count();
        return DataTables::of($hol->take(20))
                        ->addIndexColumn()
                        ->with([
                            'recordsTotal' => $count_total,
                            'recordsFiltered' => $count_filter
                        ])
                        ->addColumn('details_url', function ($data) {
                            return route('holiday.detail', $data->year);
                        })
                        ->addColumn('action', function($data){
                            $check_language = Fun::lang();

                            if ($check_language == 'km') {
                                $edit = "កែសម្រួល";
                                $delete= "លុបចោល";
                            } else {
                                $edit = "Edit";
                                $delete = "Delete";
                            }
                            $btn = "";
                            $btn .= '<a class="btn btn-sm button_success btn_add_holiday" title="Add holiday" data-year="'.$data->year.'"><i class="fa fa-plus"></i> </a>';
                            $btn .= '<a href="'.route('print.holiday', $data->year).'" target="_blank" class="btn btn-sm button_primary btn_add_print" title="Print holiday"><i class="fa fa-print"></i> </a>';
//                            if(Gate::check('Holiday Edit')){
//                                $btn .= '<a href="'.route('hr-holiday.edit', encrypt($data->id)).'" class="btn btn-sm button_warning" title="'.$edit.'"><span class="fa fa-pencil-square-o"></span></a>';
//                            }
//                            if(Gate::check('Holiday Delete')) {
//                                $btn .= '<a class="btn btn-sm button_danger btn_del_holiday" data-id="' . $data->id . '" title="' . $delete . '"><span class="fa fa-trash"></span></a>';
//                            }

                            return $btn;
                        })
                        ->rawColumns(['action', 'details_url'])
                        ->make(true);
    }

    public function holiday_detail($year)
    {
        $data = HrHolidayModel::where('year', $year)->orderBy('from_date', 'ASC')->get();
        return DataTables::of($data)
            ->addIndexColumn()
            ->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)) : "";
            })
            ->addColumn('count_day', function ($data){
                $date1 = $data->from_date ? date('d-m-Y', strtotime($data->from_date)) : date('d-m-Y', now());
                $date2 = $data->to_date ? date('d-m-Y', strtotime($data->to_date)) : date('d-m-Y', now());
                $dateDiff = $this->dateDiffInDays($date1, $date2);

                return $dateDiff;
            })
            ->addColumn('action', function ($data){
                $btn = '';
                $btn .= '<a class="btn btn-sm btn-warning btn_edit_one" title="Edit" data-id="'.$data->id.'"><i class="fa fa-edit"></i> </a> ';
                $btn .= '<a class="btn btn-sm btn-danger btn_delete_one" title="Delete" data-id="'.$data->id.'"><i class="fa fa-times"></i> </a>';
                return $btn;
            })
            ->rawColumns(['action', 'count_day'])
            ->make(true);
    }

    function dateDiffInDays($date1, $date2)
    {
        // Calculating the difference in timestamps
        $diff = strtotime($date2) - strtotime($date1);
        // 1 day = 24 hours
        // 24 * 60 * 60 = 86400 seconds
        return abs(round($diff / 86400));
    }

    public function print_holiday($year)
    {
        $hol = HrHolidayModel::where('year', $year)->get();
        return view('hr.holiday.print', compact('hol'));
    }
    public function create()
    {
        return view('hr.holiday.create');
    }

    public function store(Request $request)
    {

        $this->validate($request,[
            'name'              => 'required',
            'year'              => 'required|unique:nso007_hr_pre_holiday,year',
            'effect_date'       => 'required',

            'name_en'           => 'required',
            'name_en.*'         => 'required',
            'name_kh'           => 'required',
            'name_kh.*'         => 'required',
            'from_date'         => 'required',
            'from_date.*'       => 'required',
            'to_date'           => 'required',
            'to_date.*'         => 'required'
        ]);

        try{
            if($request->name){
                PreHolidayModel::create([
                    'name'          => $request->name,
                    'year'          => $request->year,
                    'effect_date'   => $request->effect_date ? date('Y-m-d', strtotime($request->effect_date)) : null,
                    'note'          => $request->note,
                    'branch_id'     => Auth::user()->branch_id
                ]);
            }
            if(isset($request->name_kh) || isset($request->name_en)){
                foreach ($request->name_kh as $key => $row){
                    $hol                = new HrHolidayModel();
                    $hol->name_en       = $request->name_en[$key];
                    $hol->name_kh       = $row;
                    $hol->from_date     = $request->from_date ? date('Y-m-d',strtotime($request->from_date[$key])) : null;
                    $hol->to_date       = $request->to_date ? date('Y-m-d',strtotime($request->to_date[$key])) : null;
                    $hol->year          = $request->year;
                    $hol->save();
                }
            }

            return response()->json(['status' => 200, 'message' => 'Created Holiday Success']);
        }catch(\Exception $ex){
            return response()->json(['status' => 400, 'message' => $ex->getMessage()]);
        }
    }

    public function add_holiday(Request $request)
    {
        $this->validate($request, [
            'name_kh'   => 'required',
            'name_en'   => 'required',
            'from_date' => 'required',
            'to_date'   => 'required',
        ]);

        try{
            HrHolidayModel::create([
                'name_kh'   => $request->name_kh,
                'name_en'   => $request->name_en,
                'from_date' => $request->from_date ? date('Y-m-d', strtotime($request->from_date)) : null,
                'to_date'   => $request->to_date ? date('Y-m-d', strtotime($request->to_date)) : null,
                'year'      => $request->year,
            ]);
            return response()->json(['status' => 200, 'message' => 'Add holiday success.']);
        }catch(\Exception $ex){
            return response()->json(['status' => 400, 'message' => $ex->getMessage()]);
        }
    }
    public function update_holiday(Request $request)
    {

        $this->validate($request, [
            'name_kh'   => 'required',
            'name_en'   => 'required',
            'from_date' => 'required',
            'to_date'   => 'required',
        ]);

        try{
            HrHolidayModel::where('id', $request->id)->update([
                'name_kh'   => $request->name_kh,
                'name_en'   => $request->name_en,
                'from_date' => $request->from_date ? date('Y-m-d', strtotime($request->from_date)) : null,
                'to_date'   => $request->to_date ? date('Y-m-d', strtotime($request->to_date)) : null,
            ]);
            return response()->json(['status' => 200, 'message' => 'Update holiday success.']);
        }catch(\Exception $ex){
            return response()->json(['status' => 400, 'message' => $ex->getMessage()]);
        }
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $hol = HrHolidayModel::find($id);
        return response()->json($hol);
    }

    public function update(Request $request, $id)
    {
        $this->validate($request,[

            'name_en'       => 'required',
            'name_kh'       => 'required',
            'from_date'     => 'required',
            'to_date'       => 'required'

        ]);

        $hol                = HrHolidayModel::find($id);
        $hol->name_en       = $request->name_en;
        $hol->name_kh       = $request->name_kh;
        $hol->from_date     = date('Y-m-d',strtotime($request->from_date));
        $hol->to_date       = date('Y-m-d',strtotime($request->to_date));
        $hol->year          = $request->year;
        $hol->note          = $request->note;

        $hol->update();
        return redirect()->route('hr-holiday.index')->with('success','Holiday was updated successful ...');
    }

    public function destroy($id)
    {
        //
    }
    public function delete_holiday(Request $request)
    {
        try{
            HrHolidayModel::where('id', $request->id)->delete();
            return response()->json(['status' => 200, 'message' => 'Delete Holiday Success']);
        }catch(\Exception $ex){
            return response()->json(['status' => 400, 'message' => $ex->getMessage()]);
        }
    }

    public function importHoliday(Request $request)
    {
        $validator = Validator::make($request->all(),[
           'excel' => 'required|mimes:xlsx,xls,csv'
        ]);

        if($validator->passes())
        {
            $dateTime       = date('Ymd_His');
            $file           = $request->file('excel');
            $file_name      = $dateTime.'-'.$file->getClientOriginalName();
            $path           = public_path('/uploads/');
            $file->move($path,$file_name);
            $excel          = Importer::make('excel');
            $excel->load($path.$file_name);
            $collection     = $excel->getCollection();
            if(sizeof($collection[0]) == 7)
            {
                foreach ($collection as $key => $ex_file)
                {
                    if($key > 0)
                    {
                        try
                        {
                            $holiday = new HrHolidayModel();
                            $holiday->name_en   = !empty($ex_file[1]) ? $ex_file[1] : null;
                            $holiday->name_kh   = !empty($ex_file[0]) ? $ex_file[0] : null;
                            $holiday->from_date = !empty($ex_file[2]) ? date('Y-m-d',strtotime($ex_file[2])) : null;
                            $holiday->to_date   = !empty($ex_file[3]) ? date('Y-m-d',strtotime($ex_file[3])) : null;
                            $holiday->year      = !empty($ex_file[4]) ? $ex_file[4] : null;
                            $holiday->status    = !empty($ex_file[5]) ? $ex_file[5] : null;
                            $holiday->note      = !empty($ex_file[6]) ? $ex_file[6] : null;
                            $holiday->save();

                        }
                        catch (\Exception $e)
                        {
                            return $e->getMessage();
                        }
                    }
                }

                return redirect()->route('hr-holiday.index')->with('success','Holiday was create successful ...');

            }
            else
            {
                return redirect()->back()->with('danger','Please check your file!');
            }
        }
        else
        {
            return redirect()->back()->with(['danger' => $validator->errors()->all()]);
        }
    }

}
