<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Project;
use App\Models\Group;
use App\Models\Task;
use App\Models\AssignProject;
use App\Models\ActivityLog;
use App\Models\Notification;
use App\Models\ProjAttachment;
use App\User;
use Auth;
use Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

use App\Models\CompanyModel;

class projectController extends Controller
{
    public function index(){

        $data['title'] = "Projects";
        $data['login_user_id'] = Auth::user()->id;
        $data['userss'] = User::where('utype',3)->get();
        $data['client_list']=CompanyModel::where('status',2)->orderBy('name')->get();
        $data['projj'] = Project::with('client','tasks')->where('is_active',1)->orderBy('name')->get();

        return view('admin.projects',$data);
        /*
        1=Created;
        No status will change for assign
        2=in process;
        3=Completed;
        4=checking;
        5=bugfixing;
        5=done;
        */
    }

    public function add_file(Request $req){

        $file = $req->file('file');
        $proj_id = $req->proj_id;

        date_default_timezone_set("Asia/Dhaka");
        
        if ($req->hasFile('file')) {
            $extension = $file->getClientOriginalExtension();
            $os = array("jpg", "jpeg", "png", "pdf", "doc", "docx", "txt", "psd");
            if (in_array($extension, $os)){
                $name = $file->getClientOriginalName();
                $newFileName = $newFileName = "proj_".date('d_m_y_h_m_s').".".$extension;;
                $fileee = $file->move('assets/document/project/', $newFileName);

                //echo $newFileName;
                $cat = new ProjAttachment; 
                $cat->url = $newFileName;
                $cat->uploader_id = Auth::user()->id;
                $cat->proj_id = $proj_id;
                $cat->name = $name;
                $cat->save();

                $msg = "Add document: $name";
                $this->project_log($msg,$proj_id);  //call functiont

                //notification
                $projj_name = Project::find($proj_id)->name;
                $adminss = User::where('utype',1)->get();
                
                foreach($adminss as $info){
                    $msg = "File:$name added in Proj:$projj_name by ".Auth::user()->name;
                    $this->notification($info->id, $msg);
                }
                
                $ass_usr = AssignProject::where('proj_id',$proj_id)->get();

                if(count($ass_usr) > 0){
                    foreach($ass_usr as $info){
                        $msg = "File:$name added in Proj:$projj_name by ".Auth::user()->name;
                        $this->notification($info->user_id, $msg);
                    }    
                }
               
            }
        }
    }

    public function add_project(Request $request){
        
        $proj_name = $request->proj_name;
        $client_id = $request->client_id;
        $description = $request->description;
        date_default_timezone_set("Asia/Dhaka"); 
        $cdate = date('Y-m-d H:i:s');

        if(empty($proj_name) || $client_id <= 0){
            return redirect()->back()->with('message','Fill up all fields');
        }

        $sav = new Project;
        $sav->name = $proj_name;
        $sav->client_id = $client_id;
        $sav->description = $description;
        $sav->created_time = $cdate;
        $sav->created_by = Auth::user()->id;
        $sav->save();

        $lastInsertedId = $sav->id;
        $msg = "Project:$proj_name created.";
        $this->project_log($msg,$lastInsertedId);  //call function

        $noti = User::where('utype',1)->get();

        foreach($noti as $info){

            $msg = "Proj: $proj_name created by ".Auth::user()->name;
            $this->notification($info->id, $msg);
        }

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

    public function remove_proj($id)
    {
        $del = Project::find($id); 
            //proj_name for notification
            $proj_name = $del->name; 
            $del->tasks()->delete();
            $del->documents()->delete();
            $del->proj_assign()->delete();
        $del->delete();

            //notification
            $noti = User::where('utype',1)->get();
            foreach($noti as $info)
            {
            $msg = "Proj: $proj_name removed by ".Auth::user()->name;
            $this->notification($info->id, $msg);
            }

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

    public function remove_proj_document($id)
    {
        $del = ProjAttachment::find($id);
            //for notification
            $proj_id = $del->proj_id;
            $name = $del->name;

            if (File::exists('assets/document/project/'.$del->url) && !empty($del->url))
            {
                File::delete('assets/document/project/'.$del->url);
                $msg = "Document: $del->name removed.";
                $this->project_log($msg,$del->proj_id);  //call function
                $del->delete();

                //notification
                $projj_name = Project::find($proj_id)->name;
                $adminss = User::where('utype',1)->get();
                
                foreach($adminss as $info){
                    $msg = "File:$name removed from Proj:$projj_name by ".Auth::user()->name;
                    $this->notification($info->id, $msg);
                }
                
                $ass_usr = AssignProject::where('proj_id',$proj_id)->get();

                if(count($ass_usr) > 0){
                    foreach($ass_usr as $info){
                        $msg = "File:$name removed from Proj:$projj_name by ".Auth::user()->name;
                        $this->notification($info->user_id, $msg);
                    }    
                }
            }

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

    public function project_details($id){
        
        $data['title'] = "Project details";
        $data['users'] = User::where('active',1)->get();
        $data['groups'] = Group::where('user_id',0)->get();
        $data['project_id'] = $id;
        $data['self'] = Project::find($id);
        $data['proj_assign_user'] = AssignProject::with('one_user')->where('active',1)->where('proj_id',$id)->get();
        $data['documents'] = ProjAttachment::where('proj_id',$id)->orderBy('id','desc')->get();

        $data['tasks'] = Task::where('status',1)->where('proj_id',$id)->get();
        $data['in_process'] = Task::where('status',2)->where('proj_id',$id)->get();
        $data['complete'] = Task::where('status',3)->where('proj_id',$id)->get();
        $data['check'] = Task::where('status',4)->where('proj_id',$id)->get();
        $data['bug'] = Task::where('status',5)->where('proj_id',$id)->get();
        $data['done'] = Task::where('status',6)->where('proj_id',$id)->get();

        $data['logss'] = ActivityLog::with('one_user')->where('proj_id',$id)->orderBy('created_at','DESC')->take(20)->get();

        return view('admin.project_details',$data);
    }

    public function assign_project(Request $req)
    {
        $proj_id = $req->proj_id;
        $type = $req->types;
        $group_id = $req->group_id;
        $user_id = $req->user_id;
        date_default_timezone_set("Asia/Dhaka"); 
        $assign_time = date('Y-m-d H:i:s');

        $fet = Project::find($proj_id);
        $proj_name = $fet->name;
        $subj = "You are added to ".$proj_name."." ;

        $fet_assign_by = User::find(Auth::user()->id);
        
        if($type == 1){
            $all = Group::where('depend_on',$group_id)->where('active','>',0)->get();

            foreach($all as $info)
            {
                $sav = new AssignProject;
                $sav->proj_id = $proj_id;
                $sav->user_id = $info->user_id;
                $sav->assign_time = $assign_time;
                $sav->assign_by = Auth::user()->id;
                $sav->active = 1;
                $sav->save();

                    $fet_user_info = User::find($info->user_id);
                    //send email after assign project
                    $uemail = $fet_user_info->email;
                    $data = [
                        'proj_name' => $proj_name,
                        'user_name' => $fet_user_info->name,
                        'assign_by' => $fet_assign_by->name,
                    ];
                    $this->send_email($uemail,$subj,$data); //call function

                $u_name = $this->get_user_name($info->user_id); //call function
                
                //activity log
                $msg = $u_name." assigned.";
                $this->project_log($msg,$proj_id);  //call function

                //notification
                $adminss = User::where('utype',1)->get();
                $user_name = User::find($info->user_id)->name;
                
                foreach($adminss as $vals){
                    $msg = "$user_name assigned in Proj:$proj_name by ".Auth::user()->name;
                    $this->notification($vals->id, $msg);
                }

                $msg = "You assigned in Proj:$proj_name by ".Auth::user()->name;
                $this->notification($info->user_id, $msg);
            }
        }
        elseif($type == 2){
            $sav = new AssignProject;
            $sav->proj_id = $proj_id;
            $sav->user_id = $user_id;
            $sav->assign_time = $assign_time;
            $sav->assign_by = Auth::user()->id;
            $sav->active = 1;
            $sav->save();

                $fet_user_info = User::find($user_id);
                //send email after assign project
                $uemail = $fet_user_info->email;
                $data = [
                    'proj_name' => $proj_name,
                    'user_name' => $fet_user_info->name,
                    'assign_by' => $fet_assign_by->name,
                ];
                $this->send_email($uemail,$subj,$data); //call function

            $u_name = $this->get_user_name($user_id); //call function
                
            $msg = $u_name." assigned.";
            $this->project_log($msg,$proj_id);  //call function

            //notification
            $adminss = User::where('utype',1)->get();
            $user_name = User::find($user_id)->name;
            
            foreach($adminss as $vals){
                $msg = "$user_name assigned in Proj:$proj_name by ".Auth::user()->name;
                $this->notification($vals->id, $msg);
            }

            $msg = "You assigned in Proj:$proj_name by ".Auth::user()->name;
            $this->notification($user_id, $msg);
        }
        else{
            return redirect()->back()->with('msg','Select type first..');
        }

        return redirect()->back()->with('msg','Add successfully!');
    }

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

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

    public function remove_proj_user($id)
    {   
        $del = AssignProject::find($id);
            $u_name = $this->get_user_name($del->user_id); //call function
            $msg = "$u_name removed.";
            $this->project_log($msg,$del->proj_id);  //call function

            //notification
            $adminss = User::where('utype',1)->get();
            $proj_name = Project::find($del->proj_id)->name;
            
            foreach($adminss as $vals){
                $msg = "$u_name removed from Proj:$proj_name by ".Auth::user()->name;
                $this->notification($vals->id, $msg);
            }

            $msg = "You removed from Proj:$proj_name by ".Auth::user()->name;
            $this->notification($del->user_id, $msg);

        $del->delete();
        
        return redirect()->back();
    }

    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 get_user_name($id){
        $fetch = User::find($id);
        return $fetch->name;
    }

    public function make_pm(Request $req)
    {
        $id = $req->id;
        $status = $req->pm_status;

        $upd = AssignProject::find($id);
        $upd->pm_status = $status;
        $upd->save();

        //notification
        $projj_name = Project::find($upd->proj_id)->name;
        $adminss = User::where('utype',1)->get();
        $user_name = User::find($upd->user_id)->name;
        
        if($status == 1)
        {
        $msg = "$user_name assigned as a PM in Proj:$projj_name by ".Auth::user()->name;
        }
        else
        {
        $msg = "$user_name lost PM position from Proj:$projj_name by ".Auth::user()->name;
        }
        

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

        return "PM status changed successfully!";
    }

    public function notification($user_id,$msg){

        $sav = new Notification;
        $sav->user_id = $user_id;
        $sav->msg = $msg;
        $sav->status = 1;
        $sav->save();
    }
    public function updateDrag($id,$leveltransfer=''){
        $new_value;
        $msg;
        $start_time;
        $end_time;
        $prv_value=DB::table('task')->where('id','=',$id)->first();
        if($prv_value->status==1 && $leveltransfer=='no'){
            $new_value= 2;
            $msg="In Progress !";
            date_default_timezone_set("Asia/Dhaka"); 
            $start_time = date('Y-m-d H:i:s');
        } else if($prv_value->status==2 && $leveltransfer=='no'){
            $new_value= 1;
            $msg="Created !";
        } else if($prv_value->status==3 && $leveltransfer=='no'){
            $new_value= 6;
            $msg="Done !";
            $end_time = date('Y-m-d H:i:s');
        } else if($prv_value->status==6 && $leveltransfer=='no'){
            $new_value= 3;
            $msg="Completed !";
            $end_time="0000-00-00 00:00:00";
            
        } else if($prv_value->status==2 && $leveltransfer=='yes'){
            $new_value= 3;
            $msg="Completed !";
        }
        if($new_value==2){
            DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value,'start_time'=>$start_time));
        } else if($new_value ==6){
           DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value,'closing_time'=>$end_time)); 
        } else {
            DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value));   
        }
        return $prv_value->name." STATUS UPDATED TO ".$msg;
    }
    public function change_task_status($id)
    {
        $new_value;
        $msg;
        $start_time;
        $end_time;
        $prv_value=DB::table('task')->where('id','=',$id)->first();
        if($prv_value->status==1)
        {
            $new_value= 2;
            date_default_timezone_set("Asia/Dhaka"); 
            $start_time = date('Y-m-d H:i:s');
        }
        else if($prv_value->status > 1 && $prv_value->status < 6)
        {
            $new_value= 6;
            $end_time = date('Y-m-d H:i:s');
        } 
        if($new_value==2){
            DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value,'start_time'=>$start_time));
        } else if($new_value ==6){
           DB::table('task')->where('id','=',$id)->update(array('status'=>$new_value,'closing_time'=>$end_time)); 
        }
        return redirect()->back();
    }
}
