<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Exports\SignInOurReportExport;
use App\Models\Task;
use App\Models\TaskFeedbackSeen;
use App\Models\EmployeeTask;
use App\Models\Employee;
use App\Models\Department;
use App\Models\Designation;
use App\Models\LeaveApplication;
use App\Models\StickyNote;
use App\Models\NoticeBoard;
use App\Models\Project;
use App\Models\SignInOut;
use Carbon\Carbon;
use Auth;
use App\User;
use DB;
use PDF;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     * @author Sabber Hossain
     * @return void
     */
    public function __construct()
    {         
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     * @author Sabber Hossain
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        $data['title'] = 'Dashboard';
        $data['menu'] = 'dashboard';
        $data['request'] = $request;
        $data['users'] = User::all();
        $data['projects'] = Project::where('status', 1)->get();
        $data['department'] = Department::where('status', 1)->count();
        $data['employee'] = Employee::where('status', 1)->count();
        $data['employees'] = Employee::where('status', 1)->get();
        $data['task_count'] = Task::where('status', 1)->count();
        $data['designation'] = Designation::where('status', 1)->count();
        $leave_application = LeaveApplication::orderBy('id', 'desc');
        $data['sticky_note'] = StickyNote::where('user_id', Auth::user()->id)->first();
        $data['notices'] = NoticeBoard::orderBy('created_at', 'asc')->where('status', 1)->get();

        if(Auth::user()->role == 3){
            if(Auth::user()->employee){
                $emp_ids = (Auth::user()->employee->departments)? Auth::user()->employee->departments->pluck('id') : '';
                if($emp_ids){
                    $leave_application = $leave_application->whereIn('emp_id', $emp_ids)->where('dp_status', 1);    
                }
            }
        }
        
        $data['leave_application'] = $leave_application->count();
        // $data['tasks'] = Task::with('employee_task','project','task_feedback')->orderBy('id', 'desc');
        $tasks = Task::with('employee_task','project','task_feedback','task_docs')->orderBy('id', 'desc')->where('status','!=',4);
        
        if(Auth::user()->role != 1){
            $emp_task = EmployeeTask::where('employee_id', Auth::user()->employee->id)->get()->toArray();
            $ids = array_column($emp_task, 'task_id');

            $assign_tasks = Task::where('created_by', Auth::user()->id)->get()->toArray();
            
            if(count($assign_tasks) > 0){
                foreach($assign_tasks as $value){
                    array_push($ids, $value['id']); 
                }
            }
            $tasks = $tasks->whereIn('id', array_unique($ids));
        }
        if($request->daterange){
            $daterange = explode(' - ', $request->daterange);
            $start_date = ($daterange[0])?: ''; 
            $end_date = ($daterange[1])?: ''; 
            if($start_date && $end_date){
                $tasks = $tasks->whereBetween('start_date', [$start_date, $end_date]);
            }
        }
        if($request->project){
            $tasks = $tasks->where('project_id', $request->project);
        }
        if($request->employee){
            $emp_task = EmployeeTask::where('employee_id', $request->employee)->get()->toArray();
            $ids = array_column($emp_task, 'task_id');
            $tasks = $tasks->whereIn('id', array_unique($ids));
        }
        if($request->asign_by){
            $tasks = $tasks->where('created_by', $request->asign_by);
        }
        if($request->status){
            if($request->status == 4){
                $tasks = $tasks->where('end_date', '<', date('Y-m-d'))->where('status', '!=', 4);
            }else{
                $tasks = $tasks->where('status', $request->status);
            }
        }
        if($request->read_status){
            if($request->read_status == 2){
                $task_id = TaskFeedbackSeen::where('is_seen', 0)->where('user_id', Auth::user()->employee->id)->pluck('task_id');
                $tasks = $tasks->whereIn('id', $task_id);
            }else{
                $task_id = TaskFeedbackSeen::where('is_seen', 0)->pluck('task_id');
                foreach ($task_id as $value) {
                   $tasks = $tasks->where('id', '!=', $value);
                }
            }
        }

        $data['tasks'] = $tasks->paginate(10);
        return view('home', $data);
    }

    /**
     * Show the application Profile.
     * @author Sabber Hossain
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function profile()
    {
        $data['title'] = 'Dashboard';
        $data['menu'] = 'dashboard';
        $data['user'] = Auth::user();
        $data['employee'] = Auth::user()->employee;
        $data['departments'] = Department::where('status', 1)->get();
        $data['designastion'] = Designation::where('status', 1)->get();
        return view('profile', $data);
    }

    /**
     * user Profile update.
     * @author Sabber Hossain
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function general_info_update(Request $request)
    {
        $user = Auth::user();
        $user->username = $request->username;
        $user->name = $request->name;
        $user->email = $request->email;

        $image = $request->file('image');
        if(isset($image)){
            if (Storage::disk('public')->exists('uploads/'.$user->photo)) {
                Storage::disk('public')->delete('uploads/'.$user->photo);
            }
            $image_name = uniqid().'.'.$image->getClientOriginalExtension();
            Storage::disk('public')->putFileAs('uploads', $image, $image_name);
            $user->photo = $image_name;
        }

        try {
            $user->save();
        } catch (Exception $e) {
            toastr()->error($e->message());
            return redirect()->back();
        }

        toastr()->success('Profile General Info Update');
        return redirect()->back();
    }

    /**
     * user password Changw.
     * @author Sabber Hossain
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function change_password(Request $request){
        $user = Auth::user();
        if (!\Hash::check($request->old_pass, $user->password)) {
            toastr()->error('Old Password Not Match');
            return redirect()->back();
        }

        $user->password = bcrypt($request->password);
        $user->temp_password = $request->password;

        try {
            $user->save();
        } catch (Exception $e) {
            toastr()->error($e->message());
            return redirect()->back();
        }

        toastr()->success('Password Chnage Successfully');
        return redirect()->back();
    }
    
    /**
     * Employee Info Update.
     * @author Sabber Hossain
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function employee_info_update(Request $request){
        $employee = Auth::user()->employee;
        DB::beginTransaction();
        $employee->type = $request->type;
        $employee->name = $request->name;
        $employee->phone = $request->contact_number;

        $employee->office_phone = $request->office_contact_number;
        $employee->per_email = $request->email;
        $employee->office_email = $request->office_email;
        $employee->pre_address = $request->pre_address;
        $employee->per_address = $request->per_address;
        $employee->maritial_status = $request->marital_status;
        $employee->gender = $request->gender;
        $employee->religion_status = $request->religion;
        $employee->f_name = $request->f_name;
        $employee->f_nid = $request->f_nid;
        $employee->m_name = $request->m_name;
        $employee->m_nid = $request->m_nid;
        $employee->spouse_name = $request->spouse_name;
        $employee->spouse_nid = $request->spouse_nid;
        $employee->dob = $request->dob;
        $employee->department_id = $request->department;
        $employee->designastion = $request->designation;
        $employee->date_of_joining = $request->doj;
        $employee->education = $request->education;
        try {
            $employee->save();
        } catch (Exception $e) {
            DB::rollBack();
            toastr()->error($e->message());
            return redirect()->back();
        }

        $emp_emg = $employee->emg_contact;
        $emp_emg->name = $request->emg_con_name;
        $emp_emg->relation = $request->emg_relation;
        $emp_emg->nid = $request->emg_con_nid;
        $emp_emg->number = $request->emg_con_phone;
        $emp_emg->email = $request->emg_con_email;
        try {
            $emp_emg->save();
        } catch (Exception $e) {
            DB::rollBack();
            toastr()->error($e->message());
            return redirect()->back();
        }

        DB::commit();
        toastr()->success('Successfully Employee added');
        return redirect()->back();
    }


    public function sign_in_out(Request $request, $id = null){
        
        if(empty($id)){
            $data = new SignInOut();
            $data->user_id = Auth::user()->id;
            $data->date = date('Y-m-d');
            $data->sign_in = Carbon::now();

            try {
                $data->save();
            } catch (Exception $e) {
                toastr()->error('',$e->message());
                return redirect()->back();
            }

            toastr()->success('Successfully Signing In');
            return redirect()->back();
        }else{
            $time = $request->hour.':'.$request->minute.':00';
            $time = date('h:i:s', strtotime($time));
            $data = SignInOut::findOrFail($id);
            $data->sign_out = Carbon::now();
            $data->break_time = $time;
            try {
                $data->save();
            } catch (Exception $e) {
                toastr()->error('',$e->message());
                return redirect()->back();
            }

            toastr()->success('Successfully Signing Out');
            return redirect()->back();
        }
    }

    //sign_in_out_report
    public function sign_in_out_report(Request $request){

        // dd($request);
        $data['title'] = "Sign In Sign Out Report";
        $data['request'] = $request;
        $data['menu'] = "hris";
        $data['sub_menu'] = "sign_in_out";
        $data['users'] = User::where('id','!=',1)->get();
        
        $sign_in_out_reports = SignInOut::orderBy('created_at','asc');
        if($request->daterange){
            $daterange = explode(' - ', $request->daterange);
            $start_date = ($daterange[0])? date('Y-m-d', strtotime($daterange[0])) : ''; 
            $end_date = ($daterange[1])? date('Y-m-d', strtotime($daterange[1])) : ''; 
            if($start_date && $end_date){
                $sign_in_out_reports = $sign_in_out_reports->whereBetween('date', [$start_date, $end_date]);
            }
            $data['date_show'] = ($start_date == $end_date)? date('M d y', strtotime($start_date)) : date('M d y', strtotime($start_date)) .' - '. date('M d y', strtotime($end_date));
        }
        if($request->user_id){
            $sign_in_out_reports = $sign_in_out_reports->where('user_id', $request->user_id);
        }
        if($request->sub_type == 'export'){
            if(empty($request->user_id)){
                toastr()->error('','Please Select User');
                return redirect()->back();
            }
            $data['user'] = User::findOrFail($request->user_id);
            set_time_limit(300);
            $data['sign_in_out_reports'] = $sign_in_out_reports->get();
            $sn_dta = $data['sign_in_out_reports'][1];
            $pdf = PDF::loadView('pages.report.print.sign_in_out_report_print', $data);
            return $pdf->stream('sign_in_out_report.pdf');
        }else{
            $data['sign_in_out_reports'] = $sign_in_out_reports->orderBy('id','desc')->paginate(20);
            return view('pages.report.sign_in_out_report', $data);
        }
        
    }



    public function sticky_note_update(Request $request){
        $data = StickyNote::where('user_id', Auth::user()->id)->first();
        if(empty($data)){
            $data = new StickyNote();
            $data->user_id = Auth::user()->id;
        }
        $data->note = $request->sticky_note;
        try {
            $data->save();
        } catch (Exception $e) {
            toastr()->error($e->message());
            return redirect()->back();
        }

        toastr()->success('Successfully Sticky Note Updated');
        return redirect()->back();
    }
}
