<?php

namespace App\Http\Controllers\HR;

use App\Helpers\dev1776_;
use App\Helpers\IDate;
use App\Models\EmpLeave;
use App\Models\EmpLeaveDetail;
use App\Models\Employee;
use App\Models\EmployeeLeaveTotal;
use App\Models\LeaveType;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\DataTables;
use App\Http\Requests\TakeLeaveRequest ;


class TakeLeaveController extends Controller
{
    public function index(Request $r)
    {

        return view('hr.take-leave.index');
    }

    public function create()
    {
        $job = Employee::pluck('user_firstname', 'id');
        return view('hr.take-leave.create', compact('job'));


    }

    public function store(TakeLeaveRequest $r)
    {
        $em_id = $r->select2_ajax_emp_id;
        $from_date = $r->from_date;
        $to_date = $r->to_date;
        $leave_id = $r->leave_type;
        if ( dev1776_::canTakeLeave($em_id, $leave_id, $from_date, $to_date)) {
            EmpLeave::saveDetail(null, $r);
            return redirect('take-leave')->with('success', 'Employee leave success full');
        }
        return redirect('take-leave')->withErrors('Employee leave not success');
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {

        $d = EmpLeave::find($id);
        return view('hr.take-leave.create', compact('d'));
    }

    public function update(TakeLeaveRequest $r, $id)
    {
        $em_id = $r->select2_ajax_emp_id;
        $from_date = $r->from_date;
        $to_date = $r->to_date;
        $leave_id = $r->leave_type;
        if ( dev1776_::canTakeLeave($em_id, $leave_id, $from_date, $to_date)) {
            EmpLeave::saveDetail($id, $r);
            return redirect('take-leave')->with('success', 'Employee leave success full');
        }
        return redirect('take-leave')->withErrors('Employee leave not success');
    }

    public function destroy($id)
    {
        //
        $d = EmpLeave::findOrFail($id);
        $d->empLeave_detail()->delete();
        $d->delete();

        return redirect('take-leave')->with('success', 'Employee leave is successfully deleted');
    }
    function delete($id){
        EmpLeave::find($id)->empLeave_detail()->delete();;
        EmpLeave::find($id)->delete();
        return response()->json([
            'success' => true,
            'message' => 'Employee leave is successfully deleted'
        ]);
    }




}
