Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 269
ScheduleController
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 10
2970
0.00% covered (danger)
0.00%
0 / 269
 index
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 6
 create
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 10
 store
0.00% covered (danger)
0.00%
0 / 1
420
0.00% covered (danger)
0.00%
0 / 98
 show
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 8
 edit
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 21
 update
0.00% covered (danger)
0.00%
0 / 1
506
0.00% covered (danger)
0.00%
0 / 101
 destroy
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 4
 ChangeStatus
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 ChangeDefaultSchedule
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 10
 searchname
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 9
<?php
namespace App\Http\Controllers\ScheduleManagement;
use App\Http\Controllers\FirebaseController\FirebaseCloudMessaging;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Admin\Team;
use App\Models\Schedule\Schedule;
use App\Models\Admin\UserDetailTeam;
use App\Models\Admin\TeamShiftDetail;
use App\Models\Admin\UserDetail;
use App\Models\Schedule\ScheduleDetail;
use App\Notifications\AppNotifications;
use Illuminate\Support\Facades\DB;
use App\Models\Auth\User;
// use Carbon;
use App\Models\Admin\UserDetailUser;
use GetShiftDetailHelper;
use App\Helpers\AttendanceHelper;
use Carbon\Carbon;
class ScheduleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        /*get teams for select box in manage schedule
            - get teams of this sytyem
        */
        $title = '/Manage Team Schedule';
        $backurl = route('home');
        // For Attendance Marking
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($request);
        $valUser = AttendanceHelper::getAttendanceUser($request);
        return view('ScheduleManagement.showTeams', compact('title', 'backurl', 'val', 'valTeam', 'valUser'))->with('show', Team::all());
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        /* -get team by teamId  */
        $teamId = $request->teamId;
        $team = Team::where('id', $teamId)->first();
        $title = '/Manage Team Schedule';
        $backurl = route('my-schedule.index');
        /*-get team shifts by teamId*/
        $teamShifts = TeamShiftDetail::where('team_id', $teamId)->with('shift')->get();
        /*-get team user_detai_ id  form user_detail_team  for get users of a team*/
        //$teamUserId = UserDetailTeam::where('team_id', $teamId)->pluck('user_detail_id');
        /*-get all non deleted users of a team*/
        $teamUsers = UserDetail::where('primary_team_id', '=', $teamId)->where('deleted_at', NULL)->with('user')->get();
        // For Attendance Marking
        // dd($teamUsers);
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($request);
        $valUser = AttendanceHelper::getAttendanceUser($request);
        return view('ScheduleManagement.AddCustomSchedule', compact('title', 'teamShifts', 'teamUsers', 'team', 'val', 'valTeam', 'valUser'));
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
        ]);
        $is_default = $request->get('is_default');
        $team_id = $request->get('team_id');
        $from_date = null;
        $to_date = null;
        /*Change Date format In UTC*/
        if ($request->from_date) {
            $from_date = Carbon::parse(Carbon::createFromFormat(config('settings.php_date_format'), $request->from_date))->format('Y-m-d');
        }
        if ($request->to_date) {
            $to_date = Carbon::parse(Carbon::createFromFormat(config('settings.php_date_format'), $request->to_date))->format('Y-m-d');
        }
        $range = array($from_date, $to_date);
        //  dd($range);
        /*Check Schedule Already Exist In Schedule table at these date , if exist then it will show error*/
        if (!empty($request->to_date) || isset($request->to_date)) {
            $scheduleExists = Schedule::where('team_id', $team_id)
                ->whereBetween('from_date', $range)
                ->orWhereBetween('to_date', $range)
                ->where('team_id', $team_id)
                ->orWhere(function ($query) use ($from_date, $to_date, $team_id) {
                    $query->where('from_date', '<=', $from_date)
                        ->where('to_date', '>=', $to_date)
                        ->where('team_id', $team_id);
                })
                ->first();
        } else {
            $scheduleExists = null;
        }
        //dd($scheduleExists);                          
        if (isset($scheduleExists)) {
            return redirect()->back()->with('error', 'Schedule already exist for this dates.');
        } else {
            /*Check is_default value is 1 or 0 , if one start_date and end  Date will be empty */
            if ($is_default == 1) {
                $allScheduleQuery = array(
                    'team_id' => $request->team_id
                );
                $allScheduleUpdateData = array(
                    'is_default' => 0
                );
                Schedule::where($allScheduleQuery)->update($allScheduleUpdateData);
                $schedule = new Schedule();
                $schedule->team_id = $request->input('team_id');
                $schedule->name = $request->input('name');
                $schedule->is_default = $request->input('is_default');
                $schedule->status = $request->input('status');
                $schedule->save();
            } else {
                if ($from_date == null) {
                    return redirect()->back()->with('error', 'please select From Date');
                }
                if ($to_date == null) {
                    return redirect()->back()->with('error', 'please select To Date');
                }
                $schedule = Schedule::create([
                    'name' => $request->input('name'),
                    'team_id' => $request->input('team_id'),
                    'from_date' => $from_date,
                    'to_date' => $to_date,
                    'is_default' => 0,
                    'status' => $request->input('status')
                ]);
            }
            /*  Check schedule is created by given Information ,
                if shedule created then  find out team shift and team users,
                if team has users then entry will save for every user schedule_detail table
            */
            if (isset($schedule)) {
                $teamShifts = TeamShiftDetail::where('team_id', $team_id)->with('shift')->get();
                //$teamUserId = UserDetailTeam::where('team_id', $team_id)->pluck('user_detail_id');
                $teamUsers = UserDetail::where('primary_team_id', '=', $team_id)->where('deleted_at', NULL)->with('user')->get();
                if (!empty($teamUsers)) {
                    foreach ($teamUsers as $k => $v) {
                        $member_id = $v['user_id'];
                        foreach ($teamShifts as $ks => $vs) {
                            $teamShid = $vs['shift_id'];
                            $sh_detail = new ScheduleDetail;
                            $sh_detail->shift_id = $teamShid;
                            $sh_detail->user_id = $member_id;
                            $mon = 0;
                            $tue = 0;
                            $wed = 0;
                            $thu = 0;
                            $fri = 0;
                            $sa = 0;
                            $sun = 0;
                            if (isset($request['mon_' . $member_id . '_' . $teamShid])) {
                                $mon = $request['mon_' . $member_id . '_' . $teamShid];
                            }
                            if (isset($request['tue_' . $member_id . '_' . $teamShid])) {
                                $tue = $request['tue_' . $member_id . '_' . $teamShid];
                            }
                            if (isset($request['wed_' . $member_id . '_' . $teamShid])) {
                                $wed = $request['wed_' . $member_id . '_' . $teamShid];
                            }
                            if (isset($request['thu_' . $member_id . '_' . $teamShid])) {
                                $thu = $request['thu_' . $member_id . '_' . $teamShid];
                            }
                            if (isset($request['fri_' . $member_id . '_' . $teamShid])) {
                                $fri = $request['fri_' . $member_id . '_' . $teamShid];
                            }
                            if (isset($request['sa_' . $member_id . '_' . $teamShid])) {
                                $sa = $request['sa_' . $member_id . '_' . $teamShid];
                            }
                            if (isset($request['sun_' . $member_id . '_' . $teamShid])) {
                                $sun = $request['sun_' . $member_id . '_' . $teamShid];
                            }
                            $sh_detail->mon = $mon;
                            $sh_detail->tue = $tue;
                            $sh_detail->wed = $wed;
                            $sh_detail->thu = $thu;
                            $sh_detail->fri = $fri;
                            $sh_detail->sat = $sa;
                            $sh_detail->sun = $sun;
                            $sh_detail->schedule_id = $schedule->id;
                            $sh_detail->team_id = $schedule->team_id;
                            $sh_detail->save();
                        }
                        //notification to team user
                        $title = "New Schedule";
                        $message = "You have new schedule";
                        $actionUrl = "";
                        $arr = null;
                        $arr = [$title, $message, $actionUrl];
                        $notifyuser = User::where('id', '=', $v['user_id'])->first();
                        /*echo $member_id;*/
                        /*print_r($notifyuser);
                        exit;*/
                        $notifyuser->notify(new AppNotifications($arr));
                        $firebaseObject = new FirebaseCloudMessaging();
                        $firebaseObject->sendFirebaseNotification($title,$message,$notifyuser);
                    }
                }
                return redirect()->back()->with('success', 'Schedule Saved Successfully!');
            }
        }
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $id)
    {
        //dd();
        /*show schedule of selected team in manage schedule*/
        $id = base64_decode($id);
        $title = '/Manage Team Schedule';
        $schedules = Schedule::where('team_id', $id)->get();
        $team = Team::find($id);
        // return $schedules;
        // For Attendance Marking
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($request);
        $valUser = AttendanceHelper::getAttendanceUser($request);
        return view('ScheduleManagement.availableschedule', compact('title', 'schedules', 'team', 'val', 'valTeam', 'valUser'));
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        // dd($request);
        /*To Edit Scheule get team_id from request
            -get team by teamId  then get team shifts
            -get team user_detai_ id  form user_detail_team  for get users of a team
            -get all non deleted users of this team
        */
        $teamId = $request->get('team_id');
        //dd($teamId);
        $team = Team::where('id', $teamId)->first();
        $title = '/Manage Team Schedule';
        // $teamShifts = TeamShiftDetail::where('team_id', $teamId)->with('shift')->whereHas('shift')->get();
        // $shiftData = [];
        // foreach ($teamShifts as $teamShift) {
        //     $shiftData[] = $teamShift->shift;
        // }
        //  dd($shiftData);
        $teamShifts = TeamShiftDetail::where('team_id', $teamId)->with('shift')->whereHas('shift')->get();
        $shiftData = [];
        foreach ($teamShifts as $teamShift) {
            $shiftData[] = $teamShift->shift;
        }
        $shiftData = collect($shiftData)
            ->map(function ($item) {
                $item['start_time'] = carbon::parse($item['start_time'])->setTimezone('Asia/Kolkata')->format('H:i:s');
                return $item;
            })
            ->sortBy('start_time')
            ->values()
            ->all();
        //dd($shiftData);
        //$teamUserId = UserDetailTeam::where('team_id', $teamId)->pluck('user_detail_id');
        $teamUsers = UserDetail::where('primary_team_id', '=', $teamId)->where('deleted_at', NULL)->with('user')->whereHas('user')->orderBy('id', 'ASC')->get();
        $schedule = Schedule::where('id', $id)->first();
        $scheduleDetail = ScheduleDetail::where('schedule_id', $schedule->id)->latest('updated_at')->first();
        // For Attendance Marking
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($request);
        $valUser = AttendanceHelper::getAttendanceUser($request);
        return view('ScheduleManagement.editSchedule', compact('title', 'shiftData', 'teamShifts', 'teamUsers', 'team', 'schedule', 'scheduleDetail', 'id', 'val', 'valTeam', 'valUser'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required',
        ]);
        $team_id = $request->get('team_id');
        $from_date = null;
        $to_date = null;
        // Change Date format In UTC
        if ($request->from_date) {
            $from_date = Carbon::parse(Carbon::createFromFormat(config('settings.php_date_format'), $request->from_date))->format('Y-m-d');
        }
        if ($request->to_date) {
            $to_date = Carbon::parse(Carbon::createFromFormat(config('settings.php_date_format'), $request->to_date))->format('Y-m-d');
        }
        $range = array($from_date, $to_date);
        // Check Schedule Already Exist In Schedule table at these date, if exist then it will show an error
        if (!empty($request->to_date) || isset($request->to_date)) {
            $scheduleExists = Schedule::where('id', '!=', $id)
                ->where('team_id', $team_id)
                ->whereBetween('from_date', $range)
                ->orWhereBetween('to_date', $range)
                ->where('team_id', $team_id)
                ->orWhere(function ($query) use ($from_date, $to_date, $team_id) {
                    $query->where('from_date', '<=', $from_date)
                        ->where('to_date', '>=', $to_date)
                        ->where('team_id', $team_id);
                })
                ->first();
        } else {
            $scheduleExists = null;
        }
        if (isset($scheduleExists) && ($scheduleExists->id != $id)) {
            return redirect()->back()->with('error', 'Schedule already exists for this date');
        } else {
            // Fetch the team name based on team_id
            $team = Team::find($team_id);
            $team_name = $team ? $team->team : 'team';
            // Check is_default value is 1 or 0, if one start_date and end Date will be empty or null
            if ($request->is_default == 1) {
                $scheduleQuery = array(
                    'id' => $id
                );
                $scheduleUpdateData = array(
                    'name' => $request->name,
                    'is_default' => 1,
                    'from_date' => null,
                    'to_date' => null
                );
                $schedule = Schedule::where($scheduleQuery)->first();
                Schedule::where($scheduleQuery)->update($scheduleUpdateData);
            } else {
                $allScheduleQuery = array(
                    'id' => $id
                );
                $allScheduleUpdateData = array(
                    'name' => $request->name,
                    'is_default' => 0,
                    'from_date' => $from_date,
                    'to_date' => $to_date
                );
                Schedule::where($allScheduleQuery)->update($allScheduleUpdateData);
            }
            // Update is_active = 0 in schedule_details table for the last record of this team users
            // Insert a new record for every user with is_active 1
            ScheduleDetail::where('schedule_id', $id)->update(['is_active' => 0]);
            $teamShifts = TeamShiftDetail::where('team_id', $team_id)->with('shift')->get();
            $teamUsers = UserDetail::where('primary_team_id', '=', $team_id)->where('deleted_at', NULL)->with('user')->get();
            if (!empty($teamUsers)) {
                foreach ($teamUsers as $k => $v) {
                    $member_id = $v['user_id'];
                    foreach ($teamShifts as $ks => $vs) {
                        $teamShid = $vs['shift_id'];
                        $sh_detail = new ScheduleDetail;
                        $sh_detail->is_active = 1;
                        $sh_detail->shift_id = $teamShid;
                        $sh_detail->user_id = $member_id;
                        $mon = 0;
                        $tue = 0;
                        $wed = 0;
                        $thu = 0;
                        $fri = 0;
                        $sa = 0;
                        $sun = 0;
                        if (isset($request['mon_' . $member_id . '_' . $teamShid])) {
                            $mon = 1;
                        }
                        if (isset($request['tue_' . $member_id . '_' . $teamShid])) {
                            $tue = 1;
                        }
                        if (isset($request['wed_' . $member_id . '_' . $teamShid])) {
                            $wed = 1;
                        }
                        if (isset($request['thu_' . $member_id . '_' . $teamShid])) {
                            $thu = 1;
                        }
                        if (isset($request['fri_' . $member_id . '_' . $teamShid])) {
                            $fri = 1;
                        }
                        if (isset($request['sa_' . $member_id . '_' . $teamShid])) {
                            $sa = 1;
                        }
                        if (isset($request['sun_' . $member_id . '_' . $teamShid])) {
                            $sun = 1;
                        }
                        $sh_detail->mon = $mon;
                        $sh_detail->tue = $tue;
                        $sh_detail->wed = $wed;
                        $sh_detail->thu = $thu;
                        $sh_detail->fri = $fri;
                        $sh_detail->sat = $sa;
                        $sh_detail->sun = $sun;
                        $sh_detail->schedule_id = $id;
                        $sh_detail->team_id = $team_id;
                        $sh_detail->save();
                    }
               // Notification to team user all team members
                $title = "Schedule Update";
                $message = "Your schedule has been updated";
                $actionUrl = "";
                 $notifyuser = User::where('id', '=', $v['user_id'])->first();
                if (!empty($notifyuser)) {
                       $notifyuser->notify(new AppNotifications([$title, $message, $actionUrl]));
                }
                }
            
              
                // Notification to director and HR
                $title1 = "Schedule Update";
                $message1 = "Schedule for Team '" . $team_name . "' has been updated.";
                $actionUrl1 = "";
                //here send the notification to the Director and Hr 
                $recipientRoleNames = ['Director', 'HR'];
                $recipients = UserDetail::whereIn('role_id', function ($query) use ($recipientRoleNames) {
                    $query->select('id')
                        ->from('roles')
                        ->whereIn('name', $recipientRoleNames);
                })->get();
                foreach ($recipients as $recipient) {
                    // dd($recipients);
                    $recipientUser = User::find($recipient->user_id);
                    if (!empty($recipientUser)) {
                        $recipientUser->notify(new AppNotifications([$title1, $message1, $actionUrl1]));
                    }
                }
             return redirect()->back()->with('success', 'Schedule updated successfully');
            }
        }
    }
    public function destroy($id)
    {
        /*Delete schdule with schedule_details*/
        $schedule = Schedule::whereId($id)->delete();
        ScheduleDetail::where('schedule_id', $id)->delete();
        return redirect()->back()
            ->with('success', 'Schedule deleted successfully');
    }
    public function ChangeStatus($id)
    {
        /*Change Draft schedule into  Publish schdule */
        Schedule::where('id', $id)->update(['status' => '0']);
        return redirect()->back()->with('message', 'Status changed!');
    }
    public function ChangeDefaultSchedule(Request $request, $scheduleId)
    {
        /*Change is_default of any schedule */
        if (auth()->user()->can('Edit Schedule Module')) {
            $scheduleQuery = array(
                'id' => $scheduleId
            );
            $scheduleUpdateData = array(
                'is_default' => 1,
                'from_date' => NULL,
                'to_date' => NULL
            );
            $schedule = Schedule::where($scheduleQuery)->first();
            $allScheduleQuery = array(
                'team_id' => $schedule->team_id
            );
            $allScheduleUpdateData = array(
                'is_default' => 0
            );
            Schedule::where($allScheduleQuery)->update($allScheduleUpdateData);
            Schedule::where($scheduleQuery)->update($scheduleUpdateData);
            return redirect()->back()->with('message', 'Default changed!');
        } else {
            //Session::flash('warning', 'You Not have right permission to edit it');
            return redirect()->back()->with('message', 'You Not have right permission to edit it');
        }
    }
    public function searchname(Request $request)
    {
        $name = $request->get('name');
        $names = explode(' ', $name);
        $firstName = $names[0];
        $lastName = count($names) > 1 ? $names[count($names) - 1] : '';
        $users = User::where(function ($query) use ($firstName, $lastName) {
            $query->where('name', 'like', $firstName . '%');
            if ($lastName !== '') {
                $query->where('lastName', 'like', $lastName . '%');
            }
        })->get();
        return $users;
    }
}