<?php

namespace App\Http\Controllers;

use App\Models\Rota;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\UserGroup;
use App\CustomClass\Helper;
use Illuminate\Support\Facades\Session;
use DB;

class RotaController extends Controller
{
    public function index( $userGroupId = null)
    {
        // set current date
        if (Session::has('rota_startDate') && Session::has('rota_weekend')) {
            $startDate = Session::get('rota_startDate');
            $weekend = Session::get('rota_weekend');
        } else {

            $startDate = date('Y-m-d', strtotime(Helper::getFirstWeekDay(date('Y-m-d'), 1)));
            $weekend = date('Y-m-d', strtotime("$startDate +6 days"));
            Session::put('rota_startDate', $startDate);
            Session::put('rota_weekend', $weekend);
        }
        $result = $this->getRotaData($startDate, $weekend, $userGroupId);
        //echo "<pre>";
        //print_r();
        return view('backend.rota.index')
            ->with('users', $result['users'])
            ->with('userGroup', $result['userGroup'])
            ->with('defaultGroup', $result['defaultGroup'])
            ->with('data', $result['data'])
            ->with('weekend', $weekend)
            ->with('startDate', $startDate);
    }

    public function weekShift( Request $request)
    {
        $startDate = $request->startDate;
        $s = date('Y-m-d', strtotime("$startDate -1 day"));
        $weekend = date('Y-m-d', strtotime("$s +1 week"));
        Session::put('rota_startDate', $startDate);
        Session::put('rota_weekend', $weekend);
        return redirect()->back();
    }

    public function getRotaData($startDate, $weekend, $userGroupId = null)
    {
        $userGroup = UserGroup::where('client_id', Auth::user()->client_id)->pluck('title', 'id')->all();
        if ($userGroup) {
            foreach ($userGroup as $key => $value) {
                $defaultGroup = [$key, $value];
                break;
            }
            if (isset($userGroupId)) {
                foreach ($userGroup as $key => $value) {
                    if ($key == $userGroupId) {
                        $defaultGroup = [$key, $value];
                        break;
                    }
                }
            }
            $users = User::where('client_id', Auth::user()->client_id)->where('user_group_id', $defaultGroup[0])->where('status', 1)->get();

            $week = Helper::createDateRangeArray($startDate, $weekend);
            $data = [];
            /*$dummy=[
                'userId'=>[
                    'date1'=>['note1','note2'],
                    'date2'=>['note1','note2']
                ],
                'userId1'=>[
                    'date1'=>['note1','note2'],
                    'date2'=>['note1','note2']
                ]
            ];*/
            $usersArray = Helper::convertNumericArray($users, 'id');
            $getRota = Rota::whereIn('user_id', $usersArray)->whereBetween('date', [$startDate, $weekend])->get();
            foreach ($users as $user) {
                $found = 0;
                foreach ($week as $date) {
                    if (count($getRota) > 0) {
                        foreach ($getRota as $rota) {
                            if ($rota->date == $date && $user->id == $rota->user_id) {
                                $found = 1;
                                $data[$user->id . "|@|" . $user->first_name . " " . $user->last_name]["$date"][] = ['rotaId' => $rota->id, 'from_time' => $rota->from_time, 'to_time' => $rota->to_time, 'note' => $rota->note];

                            }
                        }
                    }
                }

                if ($found == 0) {
                    $data[$user->id . "|@|" . $user->first_name . " " . $user->last_name][$date][] = null;
                }


            }
            return ['users' => $users, 'defaultGroup' => $defaultGroup, 'userGroup' => $userGroup, 'data' => $data];
        }
    }

    public function shiftAssignModal( $userIDandDefaultGroup, $date)
    {
        try {
            $userIDandDefaultGroup = explode('-', $userIDandDefaultGroup);
            $userId = $userIDandDefaultGroup[0];
            $userGroupId = $userIDandDefaultGroup[1];
        } catch (\Exception $e) {
            return "Something wrong . Please try again";
        }

        return view('backend.rota.shiftAssignModal', compact('userId', 'date', 'userGroupId'));
    }

    public function shiftAssignSave( Request $request)
    {
        if (count($request->user_id) > 0) {
            $successRota = 0;
            $msg = '';
            $existsRota = [];
            $fromTime = date('H:i:s', strtotime($request->from_time));
            $toTime = date('H:i:s', strtotime($request->to_time));
            if (strtotime($toTime) <= strtotime($fromTime)) {
                return json_encode(['error' => "Sorry ! Please put correct range"]);
            }
            $canInsert = 1;
            foreach ($request->user_id as $user) {
                $exists = Rota::where('date', $request->date)->where('user_id', $user)->where('client_id', Auth::user()->client_id)->get();
                if (count($exists) > 0) {
                    foreach ($exists as $data) {
                        //echo $fromTime.$toTime."<br>";
                        $result = Helper::testRange($fromTime, $toTime, $data->from_time, $data->to_time); //true if not overlap
                        if (!$result) {
                            $canInsert = 0;
                            break;
                        }
                    }
                } else {
                    $canInsert = 1;
                }
                if ($canInsert == 1) {

                    ++$successRota;
                    $rota = new Rota;
                    $rota->user_id = $user;
                    $rota->user_group_id = $request->user_group_id;
                    $rota->date = $request->date;
                    $rota->from_time = $fromTime;
                    $rota->to_time = $toTime;
                    $rota->note = $request->note;
                    $rota->break = $request->break;
                    $rota->client_id = Auth::user()->client_id;
                    $rota->created_by = Auth::id();
                    $rota->updated_by = Auth::id();
                    $rota->save();
                } else {
                    $existsRota[] = $user;
                }

            }
        }
        if (count($existsRota) > 0) {
            $usersExists = User::whereIn('id', $existsRota)->get();
            $existsMsg = [];
            foreach ($usersExists as $usersExist) {
                $existsMsg[] = $usersExist->first_name . " " . $usersExist->last_name;
            }
            $msg = implode(",", $existsMsg);
            return json_encode(['error' => "Already created for " . $msg]);
        }
        if ($successRota > 0) {
            return json_encode(['success' => "$successRota user's rota created successfully!"]);
        }

    }

    public function shiftAssignModalAll( $userGroupId, $date)
    {
        try {
            $users = User::where('client_id', Auth::user()->client_id)->where('status', 1)->where('user_group_id', $userGroupId)->get();
            if ($users) {
                $userGroup = UserGroup::find($userGroupId);
                return view('backend.rota.shiftAssignModalAll', compact('date', 'userGroup', 'users'));
            }
            return "No user yet. Without user how u can create rota !!";
        } catch (\Exception $e) {
            return "Something wrong . Please try again";
        }

    }

    public function rotaNextWeek( $date, $userGroup)
    {
        if (isset($date)) {
            $startDate = date('Y-m-d', strtotime("$date +1 day"));
            $weekend = date('Y-m-d', strtotime("$startDate +6 days"));
            Session::put('rota_startDate', $startDate);
            Session::put('rota_weekend', $weekend);
        }
        return redirect('rota-setup/' . $userGroup);

    }

    public function rotaPrevWeek( $date, $userGroup)
    {
        if (isset($date)) {
            $startDate = date('Y-m-d', strtotime("$date -7 days"));
            $weekend = date('Y-m-d', strtotime("$date -1 day"));
            Session::put('rota_startDate', $startDate);
            Session::put('rota_weekend', $weekend);
        }
        return redirect('rota-setup/' . $userGroup);

    }

    public function shiftEditModal( $rotaId)
    {
        $rota = Rota::where('id', $rotaId)->where('client_id', Auth::user()->client_id)->first();
        if ($rota) {
            return view('backend.rota.editRota', compact('rota'));
        } else {
            return "Sorry! You are not authorized!";
        }
    }

    public function shiftUpdate( Request $request)
    {
        $rota = Rota::find($request->rotaId);
        if ($rota) {
            $fromTime = date('H:i:s', strtotime($request->from_time));
            $toTime = date('H:i:s', strtotime($request->to_time));
            $rota->from_time = $fromTime;
            $rota->to_time = $toTime;
            $rota->note = $request->note;
            $rota->break = $request->break;
            $rota->save();
            return redirect('rota-setup')->with('success', 'Rota Updated Successfully !');
        }
    }

    public function deleteRota( $rotaId)
    {
        $rota = Rota::where('id', $rotaId)->where('client_id', Auth::user()->client_id)->delete();
        if ($rota) {
            return redirect()->back()->with('success', 'Rota deleted Successfully !');
        }
    }

    public function copyRota( Request $request)
    {
        //return $request->all();
        $startDate = $request->start_date;
        $weekend = $request->weekend;
        $users = User::where('user_group_id', $request->user_group_id)->where('client_id', Auth::user()->client_id)->get();
        $usersId = Helper::convertNumericArray($users, 'id');
        $getRota = Rota::whereBetween('date', [$startDate, $weekend])->whereIn('user_id', $usersId)->get();
        $week = Helper::createDateRangeArray($startDate, $weekend);
        $data = [];
        foreach ($users as $user) {
            foreach ($week as $date) {
                $found = 0;
                if (count($getRota) > 0) {
                    foreach ($getRota as $rota) {
                        if ($rota->date == $date && $user->id == $rota->user_id) {
                            $found = 1;
                            $data[$user->id][$date][] = ['rotaId' => $rota->id, 'from_time' => $rota->from_time, 'to_time' => $rota->to_time, 'note' => $rota->note, 'break' => $rota->break];
                        }
                    }
                }
                if ($found == 0) {
                    $data[$user->id][$date][] = '';
                }
            }
        }/*
            echo "<pre>";
            print_r($data);
            return;*/
        Session::put('weekRota_' . $request->user_group_id, $data);
        return redirect('rota-setup/' . $request->user_group_id)->with('success', 'Rota copied Successfully !');

    }

    public function pasteRota( Request $request)
    {
        if (Session::has('weekRota_' . $request->user_group_id)) {
            if (Session::has('rota_startDate') && Session::has('rota_weekend')) {
                $rota = Session::get('weekRota_' . $request->user_group_id);
                $week = Helper::createDateRangeArray(Session::get('rota_startDate'), Session::get('rota_weekend'));
                $new = [];
                $overlap = 0;
                foreach ($rota as $userId => $value) {
                    $i = 0;
                    foreach ($value as $rotaInfo) {
                        $newDate = $week[$i++];
                        foreach ($rotaInfo as $item) {
                            if (count($item) > 1) {
                                $exists = Rota::where('date', $newDate)->where('user_id', $userId)->where('client_id', Auth::user()->client_id)->get();
                                if (count($exists) > 0) {
                                    foreach ($exists as $data) {
                                        $result = Helper::testRange($item['from_time'], $item['to_time'], $data->from_time, $data->to_time); //true if not overlap
                                        if (!$result) {
                                            $overlap++;
                                            return redirect('rota-setup/' . $request->user_group_id)->with('error', "Rota Overlapped! You can't paste that week.");
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        $new[$userId][$newDate][] = $rotaInfo;
                    }
                }
            }

            //return;
            foreach ($new as $userId => $value) {
                $userGroup = User::where('id', $userId)->where('client_id', Auth::user()->client_id)->first();
                foreach ($value as $date => $rotaArray) {
                    foreach ($rotaArray as $rotaInfo) {
                        foreach ($rotaInfo as $info) {
                            if (count($info) > 1) {
                                $rota = new Rota;
                                $rota->user_id = $userId;
                                $rota->user_group_id = $userGroup->user_group_id;
                                $rota->date = $date;
                                $rota->from_time = $info['from_time'];
                                $rota->to_time = $info['to_time'];
                                $rota->note = $info['note'];
                                $rota->break = $info['break'];
                                $rota->client_id = Auth::user()->client_id;
                                $rota->created_by = Auth::id();
                                $rota->updated_by = Auth::id();
                                $rota->save();
                            }
                        }
                    }
                }
            }
        } else {
            return redirect('rota-setup/' . $request->user_group_id)->with('error', 'No rota copied for this user Group !');
        }
        return redirect('rota-setup/' . $request->user_group_id)->with('success', 'Rota Paste Successfully !');
    }

    public function clearWeekRota( Request $request)
    {
        if (Session::has('rota_startDate') && Session::has('rota_weekend')) {
            $userGroupId = $request->user_group_id;
            $rota = Rota::with('user')->whereBetween('date', [Session::get('rota_startDate'), Session::get('rota_weekend')])->whereHas('user', function ($query) use ($userGroupId) {
                $query->where('user_group_id', $userGroupId);
            })->delete();
        }
        return redirect()->back()->with('success', 'Rota Clear Successfully !');
    }

    public function myRota()
    {
        return view('backend.rota.rotaByUser');
    }

    public function getMyRotaData( $yearMonth)
    {
        $result = Rota::select(DB::raw('CONCAT(TIME_FORMAT(from_time,\'%h:%i %p\')," - ",TIME_FORMAT(to_time,\'%h:%i %p\'))as title'), 'date as start', 'rota.*')->where('user_id', Auth::id())->where('date', 'like', "$yearMonth%")->get()->toJson();
        return $result;
    }

    public function copyIndividualRota( $rotaId)
    {
        $data = Rota::where('id', $rotaId)->where('client_id', Auth::user()->client_id)->first();
        if ($data) {
            Session::put('individualRota', $data);
        }
        return redirect()->back()->with('info', 'Rota Copied!');
    }

    public function pasteIndividualRota( $userId, $userGroupId, $date)
    {
        $canInsert = 1;
        if (Session::has('individualRota')) {
            $pasteData = Session::get('individualRota');
        } else {
            return redirect()->back()->with('error', 'No clipboard data found !');
        }
        $exists = Rota::where('date', $date)->where('user_id', $userId)->where('client_id', Auth::user()->client_id)->get();
        if (count($exists) > 0) {
            foreach ($exists as $data) {
                //echo $fromTime.$toTime."<br>";
                $result = Helper::testRange($pasteData->from_time, $pasteData->to_time, $data->from_time, $data->to_time); //true if not overlap
                if (!$result) {
                    $canInsert = 0;
                    break;
                }
            }
        } else {
            $canInsert = 1;
        }
        if ($canInsert === 1) {
            $checkUser = User::where('id', $userId)->where('client_id', Auth::user()->client_id)->first();
            if ($checkUser) {
                $rota = new Rota;
                $rota->user_id = $userId;
                $rota->user_group_id = $userGroupId;
                $rota->date = $date;
                $rota->from_time = $pasteData->from_time;
                $rota->to_time = $pasteData->to_time;
                $rota->note = $pasteData->note;
                $rota->break = $pasteData->break;
                $rota->client_id = Auth::user()->client_id;
                $rota->created_by = Auth::id();
                $rota->updated_by = Auth::id();
                $rota->save();
                return redirect()->back()->with('userId',$userId);
            } else {
                return redirect()->back()->with('error', 'You are trying in wrong way !');
            }
        } else {
            return redirect()->back()->with('error', 'Time range overlap !');
        }

    }

}
