<?php

namespace App\Http\Controllers\HR;

use App\Classes\ZKLibrary;
use App\Fun\Fun;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Imports\TimeAttendanceImport;
use App\TimeAttendanceModel;
use App\User;
use Yajra\DataTables\DataTables;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Gate;

class AttendanceFingerPrintController extends Controller
{


    function __construct()
    {
      $this->middleware('permission:Attendance Finger List', ['only' => ['index']]);
      $this->middleware('permission:Attendance Finger Create', ['only' => ['create','store']]);
      $this->middleware('permission:Attendance Finger Edit', ['only' => ['edit','update']]);
    }
    public function index(Request $request)
    {
        if($request->ajax())
        {
            $count_total = TimeAttendanceModel::count();
            $count_filter = TimeAttendanceModel::count();

            $data = TimeAttendanceModel::orderBy('id', 'DESC')->take(20);
            return DataTables::of($data)
                    ->addIndexColumn()
                    ->with([
                        "recordsTotal" => $count_total,
                        "recordsFiltered" => $count_filter,
                    ])
                    ->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('Attendance Finger Edit')){
                            $btn_edit = '<a href="'.route('hr-attendance-fingerprint.edit', encrypt($data->id)).'" class="button_warning">'.$edit.'</a>';
                        }
                        if(Gate::check('Attendance Finger Delete')){
                            $btn_delete = '<a href="#" class="button_danger btn_delete" data-id="'.$data->id.'">'.$delete​.'</a>';
                        }
                        if($data->attend_type == "system")
                        {
                            return $btn_edit.$btn_delete;
                        }
                        else if($data->attend_type == "fingerprint")
                        {
                            return $btn_delete;
                        }
                        else{
                            $btn_edit = '';
                            $btn_delete = '';
                        }
                        return $btn_edit.$btn_delete;
                    })

                    ->rawColumns(['action' => 'action'])
                    ->make(true);
        }
        return view('hr.attendance-finger-print.index');
    }


    public function create()
    {
        $employee = User::where('status',1)->pluck('name','id');
        return view('hr.attendance-finger-print.create', compact('employee'));
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'emp_id'            =>'required',
            'check_hour'        =>'required',
            'check_minute'      =>'required',
            'check_shift'       =>'required',
            'date'              =>'required',
        ]);

        try{
            $check_in_out           = $request->check_hour.':'.$request->check_minute.':'.$request->check_shift;
            $date                   = date('Y-m-d', strtotime($request->date)).' '.$check_in_out;


            $att                    = new TimeAttendanceModel();
            $att->emp_id            = $request->emp_id;
            $att->check_in_out      = $date;
            $att->attend_type       = "system";
            $att->note              = $request->note;
            $att->save();

            return redirect()->route('hr-attendance-fingerprint.index')->with('success','Attendance was save successful...');
        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }

    public function show($id)
    {
        //
    }


    public function edit($id)
    {
        $att                = TimeAttendanceModel::find(decrypt($id));
        $employee           = User::where('status',1)->pluck('name','id');
        $date_time[]        = explode(' ',$att->check_in_out);

        $date               = $date_time[0][0];
        $time               = $date_time[0][1];
        $time_in_out[]      = explode(':', $time);


        return view('hr.attendance-finger-print.edit', compact('att','employee','time_in_out'));
    }


    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'emp_id'            => 'required',
            'check_hour'        =>'required',
            'check_minute'      =>'required',
            'check_shift'       =>'required',
            'date'              =>'required',
        ]);

        try{
            $check_in_out           = $request->check_hour.':'.$request->check_minute.':'.$request->check_shift;
            $date                   = date('Y-m-d', strtotime($request->date)).' '.$check_in_out;

            $att                    = TimeAttendanceModel::findOrFail($id);
            $att->emp_id            = $request->emp_id;
            $att->check_in_out      = $date;
            $att->attend_type       = "system";
            $att->note              = $request->note;
            $att->update();
            return redirect()->route('hr-attendance-fingerprint.index')->with('success','Attendance was updated successful...');

        }catch(\Exception $ex){
            return back()->withErrors($ex->getMessage())->withInput();
        }
    }


    public function destroy($id)
    {
        //
    }

    //get data from finger print
    public function get_data_finger_print()
    {

    }

    //delete data
    public function delete_attendance_finger_print(Request $request)
    {
        $id = $request->delete_id;
        TimeAttendanceModel::where('id', $id)->delete();
        return redirect()->route('hr-attendance-fingerprint.index')->with('success','Data was Deleted successful ...');

    }
    //import attendace fingerprint
    public function import_attendance_fingerprint()
    {
        try{
            if(request()->hasFile('file'))
            {
                $file = request()->file('file');
                Excel::import(new TimeAttendanceImport(), $file);
            }else{
                return redirect()->route('hr-attendance-fingerprint.index')->with('danger','Do not have file!');
            }
        }catch(\InvalidArgumentException $ex){
            return back()->withErrors('Wrong date format in some column');
        }catch(\Exception $ex){
            return back()->withErrors('Something went wrong, Check your file');
        }catch(\Error $ex){
            return back()->withErrors($ex->getMessage());
        }

        return redirect()->route('hr-attendance-fingerprint.index')->with('success','Attendance was imported successful !');
    }
}
