<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Models\ActivityLog;
use App\Models\AssignProject;
use App\Models\Comment;
use App\Models\CompanyActivity;
use App\Models\CompanyModel;
use App\Models\Group;
use App\Models\Notification;
use App\Models\Project;
use App\Models\Task;
use App\User;
use Auth;
use DateTime;
use Illuminate\Http\Request;
use Mail;
class TaskController extends Controller
{
    public function index(){

        $data['title'] = "All Task";
        $data['projectss'] = Project::all();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['users'] = User::where('active',1)->where('utype','<',3)->orderBy('name')->get();

        $data['tasks'] = Task::with('proj_name')->orderBy('created_time')->paginate(25);
        return view('admin.task.task',$data);

        /*
        1=Created;
        2=in process;
        3=Completed;
        4=checking;
        5=bugfixing;
        6=done;
        */
    }
    public function deadlineToday(){
        $data['title'] = "Deadline Today";
        $data['projectss'] = Project::all();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['users'] = User::where('active',1)->where('utype','<',3)->orderBy('name')->get();

        $data['today_tasks'] = Task::with(['user','proj_name'])->where('user_id','!=',0)->where('status','!=',6)->whereDate('dead_line', '=', date('Y-m-d'))->orderBy('created_time')->paginate(25);
        return view('admin.task.today_task',$data);
    }
    public function deadlineMissed(){
        $data['title'] = "Deadline Missed";
        $data['projectss'] = Project::all();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['users'] = User::where('active',1)->where('utype','<',3)->orderBy('name')->get();
        $data['deadline_missed'] = Task::with(['user','proj_name'])->where('user_id','!=',0)->where('status','!=',6)->whereDate('dead_line', '<', date('Y-m-d'))->orderBy('created_time')->paginate(25);
        return view('admin.task.deadline_missed',$data);
    }
    public function completedToday(){
        $data['title'] = "Completed Today";
        $data['projectss'] = Project::all();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['users'] = User::where('active',1)->where('utype','<',3)->orderBy('name')->get();
        $data['completed_today'] = Task::with(['user','proj_name'])->where('user_id','!=',0)->where('status','=',6)->whereDate('closing_time', '=', date('Y-m-d'))->orderBy('created_time')->paginate(25);
        return view('admin.task.completed_today',$data);
    }
    public function completedYesterday(){
        $data['title'] = "Completed Yesterday";
        $data['projectss'] = Project::all();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['users'] = User::where('active',1)->where('utype','<',3)->orderBy('name')->get();
        $data['completed_yesterday'] = Task::with(['user','proj_name'])->where('user_id','!=',0)->where('status',6)->whereDate('closing_time', '=', date('Y-m-d'))->orderBy('created_time')->paginate(25);
        return view('admin.task.completed_yesterday',$data);
    }
    public function pendingTask(){
        $data['title'] = "Pending Task";
        $data['projectss'] = Project::all();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['users'] = User::where('active',1)->where('utype','<',3)->orderBy('name')->get();
        $data['pending_task'] = Task::with(['user','proj_name'])->where('user_id','!=',0)->where('status','!=',6)->orderBy('created_time')->paginate(25);
        return view('admin.task.pending_task',$data);
    }
    public function inProcess(){
        $data['title'] = "In Process";
        $data['projectss'] = Project::all();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['users'] = User::where('active',1)->where('utype','<',3)->orderBy('name')->get();
        $data['in_process'] = Task::with(['user','proj_name'])->where('user_id','!=',0)->whereIn('status',[2,3,4,5])->orderBy('created_time')->paginate(25);
        return view('admin.task.in_process',$data);
    }

    public function add_task(Request $request){
        
        $name = $request->name;
        $proj_id = $request->proj_id;
        $p=Project::find($proj_id);
        
        $office_id=$p->office_id;
        
        $description = $request->description;
        $estimated_time = $request->estimated_time;
        $task_type = $request->task_type;
        $priority = $request->priority;
        $dead_date = $request->dead_line;
        //$dead_hour = $request->dead_hour;
        //$dead_min = $request->dead_min;
        $assigned_user = $request->user_id;
        $dead_line = $dead_date;
        
        date_default_timezone_set("Asia/Dhaka"); 
        $cdate = date('Y-m-d H:i:s');

        $sav = new Task;
        $sav->name = $name;
        $sav->type = $task_type;
        $sav->proj_id = $proj_id;
        $sav->priority = $priority;
        $sav->dead_line = $dead_line;
        $sav->description = $description;
        $sav->created_time = $cdate;
        $sav->created_by = Auth::user()->id;
        $sav->status = 1;
        $sav->user_id=$assigned_user;
        $sav->assign_by = Auth::user()->id;
        $sav->assign_time = $cdate;
        $sav->office_id =  $office_id;
        $sav->save();

        $task_id = $sav->id;

            //send email to add user add with this proj
            $proj_user = AssignProject::where('proj_id',$proj_id)->get();
            $proj_namee = Project::find($proj_id)->name;

            foreach($proj_user as $pu){

                $data = [
                    'task_name' => $name,
                    'proj_name' => $proj_namee,
                    'user_name' => $pu->one_user->name,
                    'details'   => $description,
                ];

                $subj = "A task has been created in ".$proj_namee.".";

                $this->send_email_new_task($pu->one_user->email,$subj,$data);
            }
            
        //activity log
        $msg = "Task: $name created.";
        $this->task_log($msg,$task_id,$proj_id);  //call function

        //notification
        $projj_name = Project::find($proj_id)->name;
        $adminss = User::where('utype',1)->get();
        
        $post_by_name = Auth::user()->name;
        $post_by_id = Auth::user()->id;
        $msg = "Task:$name created in Proj:$projj_name by ".$post_by_name;

        foreach($adminss as $info){
            if($info->id != $post_by_id){
                $this->notification($info->id, $msg);
            }
        }
        
        $ass_usr = AssignProject::where('proj_id',$proj_id)->get();

        if(count($ass_usr) > 0){
            foreach($ass_usr as $info){
                $this->notification($info->user_id, $msg);
            }    
        }

        return redirect()->back()->with('message','Success');
    }

    public function remove_task($id)
    {
        $del = Task::find($id);

            //activity log
            $msg = "Task:".$del->name." removed.";
            $this->project_log($msg,$del->proj_id);  //call function

            //notification
            $projj_name = Project::find($del->proj_id)->name;
            $name = $del->name;
            $adminss = User::where('utype',1)->get();
            
            $post_by_name = Auth::user()->name;
            $post_by_id = Auth::user()->id;
            $msg = "Task:$name removed from Proj:$projj_name by ".$post_by_name;

            foreach($adminss as $info){
                if($info->id != $post_by_id){
                    $this->notification($info->id, $msg);
                }
            }
            
            $ass_usr = AssignProject::where('proj_id',$del->proj_id)->get();

            if(count($ass_usr) > 0){
                foreach($ass_usr as $info){
                    $this->notification($info->user_id, $msg);
                }    
            }
            //end notification

        $del->delete();

        return redirect()->back()->with('data','Delete successfully !!');
    }

    public function change_tast_by_proj(Request $req)
    {
        $proj_id = $req->proj_id;
        $all = Task::where('proj_id',$proj_id)->get();
        $str = "";

        $str .="<select>";
            $str .="<option value='all'>All Tast</option>";
        foreach($all as $info){
            $str .="<option value=".$info->id.">".$info->name."</option>";
        }
        $str .="</select>";

        return $str;
    }

    public function user_list_for_task_assign(Request $req){

        $proj_id = $req->proj_id;
        $task_id = $req->task_id;

        $all = AssignProject::with('one_user')->where('proj_id',$proj_id)->get();

        $str = "";
        $str .="<select>";
        foreach($all as $info){
            $str .="<option value={$info->user_id}>".$info->one_user->name."</option>";
        }
        $str .="</select>";

        //getting status of this task
            $task_sta = Task::find($task_id);
            $task_status = $task_sta->status;
            $deadline =$task_sta->dead_line;
            if(!empty($task_sta->description))
            {
                $details = $task_sta->description;
            }
            else{
                $details = "No details...";
            }

        //tast already assigned user
            $str1 = $this->fetch_task_assign_user($task_id);  //call function

        //activity log fetch
            $logss = ActivityLog::with('one_user')->where('task_id',$task_id)->orderBy('id','DESC')->get();
            $str_log = "";

            foreach($logss as $log){
                $str_log .="* $log->msg -".$log->one_user->name."<br>";
            }

        //comments fetch
            $str_comment = $this->fetch_comments($task_id);

        $data[0] = $str;
        $data[1] = $str1;
        $data[2] = $str_log;
        $data[3] = $str_comment;
        $data[4] = $task_status;
        $data[5] = $details;
        $data[6] = $deadline;
        
        return $data;

    }

    public function task_assign_to_user(Request $req){

        $task_id = $req->id_task_id;
        $estimated_time = $req->id_estimated_time;
        $user_id = $req->id_user_id;
        date_default_timezone_set("Asia/Dhaka"); 
        $cdate = date('Y-m-d H:i:s');
        $assign_by = Auth::user()->id;
        //dd($estimated_time);
        $sav = Task::find($task_id);
        $sav->user_id = $user_id;

            //fetch for activity log
            $proj_id = $sav->proj_id;
            $task_name = $sav->name;
            //send email to add user add with this proj
            $data = [
                'task_name' => $sav->name,
                'proj_name' => $sav->proj_name->name,
                'user_name' => User::find($user_id)->name,
                'estimated_time' => $estimated_time,
                'assign_by' => User::find($assign_by)->name,
            ];

            $this->send_email_assign_task($sav->user->email,'Task assign to you',$data);

        $sav->assign_by = $assign_by;
        $sav->assign_time = $cdate;
        $sav->estimated_time = $estimated_time;
        $sav->save();

        //activity log
        $nam = User::find($user_id);
        $msg = "User: $nam->name added";
        $this->task_log($msg,$task_id,$proj_id);  //call function

        //notification
        $projj_name = Project::find($proj_id)->name;
        $adminss = User::where('utype',1)->get();
        
        $post_by_name = Auth::user()->name;
        $post_by_id = Auth::user()->id;

        $msg = "$nam->name assigned in Task:$task_name of Proj:$projj_name by ".$post_by_name;

        foreach($adminss as $info){
            if($info->id != $post_by_id){
                $this->notification($info->id, $msg);   
            }
        }
        
        $msg = "You assigned in Task:$task_name of Proj:$projj_name by ".$post_by_name;
        $this->notification($user_id, $msg);
        //---end notification

        $str = $this->fetch_task_assign_user($task_id);

        return $str;
    }

    public function remove_assign_task_user(Request $req){

        $id = $req->id;            //here id and task id same
        $task_id = $req->task_id;

        $del = Task::find($id);
            //fetch proj_id for activity log
            $proj_id = $del->proj_id;
            //activity log
            $nam = User::find($del->user_id);
            $msg = "User: $nam->name removed";
            $this->task_log($msg,$task_id,$proj_id);  //call function
        $del->user_id = 0;
        $del->save();

        $str = $this->fetch_task_assign_user($task_id); //call function
        return $str;

    }

    public function add_task_comment(Request $req){

        $comment = $req->comment;
        $task_id = $req->task_id;

        date_default_timezone_set("Asia/Dhaka"); 
        $assign_time = date('Y-m-d H:i:s');

        if(!empty($comment) && $task_id > 0){
            $sav = new Comment;
            $sav->comment = $comment;
            $sav->task_id = $task_id;
            $sav->date_time = $assign_time;
            $sav->post_by = Auth::user()->id;
            $sav->save();
        }

            //activity log
            $task_info = Task::find($task_id);
            $task_name = $task_info->name;
            $proj_id  = $task_info->proj_id;
            $user_id = $task_info->user_id;
            $msg = "$comment -added to $task_name.";
            $this->task_log($msg,$task_id,$proj_id);  //call function

            //notification
            $fetch_proj = Project::find($proj_id);
            $projj_name = $fetch_proj->name;
            $client_id = $fetch_proj->client_id;
            $adminss = User::where('utype',1)->get();

            $notification_post_by = Auth::user()->name;
            $noti_post_by_id = Auth::user()->id;
            $msg = "A comment added in Task:$task_name of Proj:$projj_name by ".$notification_post_by;
            
            foreach($adminss as $info){
                if($info->id != $noti_post_by_id){
                    $this->notification($info->id, $msg);
                }
            }
            
            $this->notification($user_id, $msg);
            $this->notification($client_id, $msg);
            //--------end notification

        $str = $this->fetch_comments($task_id);

        return $str;
    }

    public function project_log($msg,$proj_id)
    {
        date_default_timezone_set("Asia/Dhaka"); 
        $assign_time = date('Y-m-d H:i:s');

        $sav = new ActivityLog;
        $sav->msg = $msg;
        $sav->proj_id = $proj_id;
        $sav->logged_user_id = Auth::user()->id;
        $sav->created_at = $assign_time;
        $sav->save();
    }

    public function fetch_task_assign_user($task_id)
    {
        $fetch = Task::with('user')->find($task_id);
        //echo $fetch->user_id;
        $str = "";
        if($fetch->user_id > 0){
            $test=date("F jS, Y h:i:s", strtotime($fetch->estimated_time));
            $str .="<input type='hidden' value=".$fetch->id.">";
            $str .= $fetch->user->name."<br/>Estimated time: ".$test." <span style='color:#FD4B39;cursor:pointer;' class='remove-task-assign-user'><i class='fa fa-times pull-right' aria-hidden='true'></i></span><br>";
        }
        else{
            $str .= "No user assigned";
        }

        return $str;
    }

    public function task_log($msg,$task_id,$proj_id)
    {
        date_default_timezone_set("Asia/Dhaka"); 
        $assign_time = date('Y-m-d H:i:s');

        $sav = new ActivityLog;
        $sav->msg = $msg;
        $sav->proj_id = $proj_id;
        $sav->task_id = $task_id;
        $sav->logged_user_id = Auth::user()->id;
        $sav->created_at = $assign_time;
        $sav->save();
    }

    public function fetch_comments($task_id){

        $fetch = Comment::with('user')->where('task_id',$task_id)->orderBy('id','DESC')->get();
        $str = "";

        if(count($fetch) > 0){
            
            foreach($fetch as $fet)
            {
                $immmgg = "assets/document/task/$fet->url";
                $str .="<input type='hidden' value=".$fet->id.">";

                $str .= $fet->comment ."-by ".$fet->user->name."<br/>";
                
                if(!empty($fet->url)){
                $str .="<br/><a target='_blank' href=".url("assets/document/task/$fet->url").">
                <img height='150' width='120' src='".asset($immmgg)."'></a>";
                }
                
                $str .="<span style='color:#FD4B39;cursor:pointer;margin-left:10px' data-id='".$fet->id."' class='edit_comment pull-right'><i class='fa fa-pencil-square-o' aria-hidden='true'></i></span>
                <span style='color:#FD4B39;cursor:pointer;' data-id='".$fet->id."' class='remove_comment'><i class='fa fa-times pull-right' aria-hidden='true'></i></span><br/>";
            }
        }

        return $str;
    }

    public function change_to_process(Request $req)
    {
        $task_id = $req->task_id;
        $status = $req->status;

        date_default_timezone_set("Asia/Dhaka"); 
        $t_time = date('Y-m-d H:i:s');

        $sav = Task::find($task_id);
            $task_name = $sav->name;

        $sav->status = $status;
        if($status == 2){
            $sav->start_time = $t_time;   
        }
        elseif($status == 6){
            $sav->closing_time = $t_time;
        }
            //fetch proj_id for activity log
            $proj_id = $sav->proj_id;
        
        if($sav->save())
        {
            $text = "";
            if($status == 2){ $text = "in-process"; }
            elseif($status == 3){ $text = "completed"; }
            elseif($status == 4){ $text = "checking"; }
            elseif($status == 5){ $text = "bug-fixing"; }
            elseif($status == 6){ $text = "done"; }

            $msg = "$task_name -Change status to: $text";
            $this->task_log($msg,$task_id,$proj_id);  //call function
            
            return "Yes";
        }
        else{
            return "No";
        }
    }

    public function send_email_new_task($uemail,$subj,$data){

        Mail::send('emails.new_task', $data, function ($message) use ($uemail,$subj)
        {
        $message->from('m.revinr@gmail.com', 'Revinr Task Management');
        $message->to($uemail)->subject($subj);
        });
    }

    public function send_email_assign_task($uemail,$subj,$data){

        Mail::send('emails.task_assign', $data, function ($message) use ($uemail,$subj)
        {
        $message->from('m.revinr@gmail.com', 'Revinr Task Management');
        $message->to($uemail)->subject($subj);
        });
    }

    public function notification($user_id,$msg){

        $sav = new Notification;
        $sav->user_id = $user_id;
        $sav->msg = $msg;
        $sav->status = 1;
        $sav->save();
    }

    public function company_task(Request $request, $typ){
        //dd($request->all());
        date_default_timezone_set("Asia/Dhaka");
        $company_id = $request->company_id;
        if($typ == 'manager_task'){
            $task_type = 1;
            $act_val = 'New Task created';
        }elseif($typ == 'manager_appointment'){
            $task_type = 2;
            $act_val = 'New Appointment created';
        }elseif($typ == 'manager_phone'){
            $task_type = 3;
            $act_val = 'New Call date created';
        }else{
            $task_type = 4;
            $act_val = 'An email Sent';
        }
        if($task_type != 4){
            $name = $request->name;
            $desc = $request->description;
            $priority = $request->priority;
            $date = $request->date;
            $cur_date = date('Y-m-d H:i:s');

            $company = CompanyModel::find($company_id);
            $manager_id = $company->account_manager;

            $manager = User::find($manager_id);

            if($manager_id != null){
                $sav = new Task;
                $sav->name = $name;
                $sav->type = 0;
                $sav->proj_id = 0;
                $sav->priority = $priority;
                $sav->dead_line = $date;
                $sav->description = $desc;
                $sav->created_time = $cur_date;
                $sav->created_by = Auth::user()->id;
                $sav->status = 1;
                $sav->user_id = $manager_id;
                $sav->assign_by = Auth::user()->id;
                $sav->assign_time = $cur_date;
                $sav->office_id =  1;
                $sav->task_type =  $task_type;
                $sav->client_id =  $company_id;
                $sav->save();
                
                $act = new CompanyActivity;
                $act->activity = $act_val;
                $act->company_id = $company_id;
                $act->date = $cur_date;
                $act->save();


                $data = [
                    'task_name' => $name,
                    'company_name' => $company->name,
                    'prio' => $priority,
                    'type' => $task_type,
                    'details'   => $desc,
                    'date'   => $date,
                    'manager_name' => $manager->name
                ];

                $subj = "New Task Added";
                $uemail = $manager->email;

                Mail::send('emails.company_task', $data, function ($message) use ($uemail,$subj)
                {
                $message->from('m.revinr@gmail.com', 'Revinr Task Management');
                $message->to($uemail)->subject($subj)->cc('helaldu@gmail.com');
                });
            }
        }else{
            $client = User::find($request->mail_to);
            $client_name = $client->name;
            $client_email = $client->email;
            $to = $client_email;
            $subject = $request->subject;
            $message = $request->message;

            $data = ['msg' => $message];

            Mail::send('emails.email_to_client', $data, function ($message) use ($to,$subject)
            {
            $message->from('m.revinr@gmail.com', 'Revinr Task Management');
            $message->to($to)->subject($subject)->cc('helaldu@gmail.com');
            });

            $act = new CompanyActivity;
            $act->activity = $act_val;
            $act->company_id = $company_id;
            $act->date = date('Y-m-d H:i:s');
            $act->save();
        }

        return redirect()->back()->with('message','Success');
    }
}
