<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Proposal;
use App\User;
use App\StudentProposal;
use App\Country;
use App\Models\ReferUser;
use App\Models\Admin;
use App\Models\Requirement;
use App\Models\University;
use App\Models\Publication;
use App\Models\FeedbackReason;
use App\Workexperience;
use App\Institution;
use App\Score;
use Hash;
use DB;
use Session;
use Auth;
use Mail;
Use Carbon\Carbon;

class ModalController extends Controller{

    public function get(Request $req, $name){
        $user = Auth::user();
        $carbon=new \Carbon\Carbon;

        $data=[
            'name'=>$name,
            'carbon'=>$carbon
        ];

        if($name=="apply_student_proposal"){
            $student =Auth::user();
            $data['teacher'] = User::find($req->t_id);
            $data['student'] = User::find($student->id);
            $data['proposal']= Proposal::where('student_id',$user->id)->get();
        }elseif($name=="update_student_proposal"){
            $data['std_proposal'] =StudentProposal::find($req->id);
            $data['teacher'] = User::find($req->teacher_id);
            $data['student'] = User::find($req->student_id);
            $data['proposal']= Proposal::where('student_id',$req->student_id)->get();
            $data['years']=range((int)date('Y'), date('Y')+1);

        }elseif($name=="view_apply_proposal"){
            $data['std_proposal'] =StudentProposal::find($req->id);

        }elseif($name=="view_student_proposal"){
            $data['proposal']= Proposal::where(
                    'student_id',$user->id
                )->where(
                    'id',$req->id
                )->first();

        }elseif($name=="add_destination"){

        }elseif($name=="add_wishlist"){
            $user =Auth::guard('teacher')->user();
            $data['refer'] = new ReferUser;

        }elseif($name=="teacher_invited"){
            $data['admin'] =Admin::find($req->id);

        }elseif($name=="add_doc_required"){
            $data['std_proposal']=StudentProposal::find($req->id);
        }elseif($name=="edit_doc_required"){
            $data['requirements']=Requirement::find($req->id);
        }elseif($name=="landing_register_form"){
            $data['countries'] =Country::where('status',1)->orderBy('name','ASC')->get();
            //$data['universities'] =University::orderBy('name','ASC')->get();
        }elseif($name=="send_email_document_information"){
            $data['teacher']=Auth::guard('teacher')->user();
            $data['std_proposal']=StudentProposal::find($req->id);
            $data['doc_requirement_list']=Requirement::where('std_proposal_id',$req->id)->get();
        }elseif($name=="proposal_status_rejected_form"){
            $data['teacher']=Auth::guard('teacher')->user();
            $data['std_proposal']=StudentProposal::find($req->id);
            $data['feedback_reasons'] =FeedbackReason::where('status',1)->orderBy('id','DESC')->get();
        }else $name='default';


        return view("modal_pages.{$name}", $data);
    }

    public function post(Request $req, $name){

        $user=Auth::user();
        $carbon=new \Carbon\Carbon;

        if($name=='apply_student_proposal'){
            //dd($req->student_id);
            $new_rules=[
                'proposal_id'=>'required',
            ];

            $validator=\Validator::make($req->all(),$new_rules,[
                'proposal_id.required'=>'Please complete your profile to submit your proposal.',
                'startdate'=>'required',
                'startmonth'=>'required',
            ]);

            if($validator->fails()){

                $errors=$validator->errors()->all();
                return response(['msg'=>$errors[0]], 422);
            }

            $student_data =User::where('id',$req->student_id)->where(function($q){
                $q->where(
                    'is_publication',0
                )->orWhere(
                    'is_work_experience',0
                )->orWhere(
                    'is_education',0
                )->orWhere(
                    'is_test_score',0
                );
            })->exists();
             

            if($student_data){
                return response(['msg'=>'you didn\'t complete your profile.'],403);
            }

            $awaiting = StudentProposal::where(
                'student_id',$req->student_id
            )->where(
                'teacher_id',$req->teacher_id
            )->where(
                'proposal_id',$req->proposal_id
            )->where(
                'proposal_submit_status',1
            )->whereIn(
                'proposal_status',[1,2,3,4] // 1 =New; 2 =In Review; 3=Push; 4=Hold;
            )->exists();

            if($awaiting){
                return response(['msg'=>'Application you have submitted that are currently awaiting decisions'],403);
            }

            $approved_proposal = StudentProposal::where(
                'student_id',$req->student_id
            )->where(
                'teacher_id',$req->teacher_id
            )->where(
                'proposal_id',$req->proposal_id
            )->where(
                'proposal_submit_status',1
            )->where(
                'proposal_status',5 // 5=interest;
            )->exists();

            if($approved_proposal){
                return response(['msg'=>'Application you have submitted that are approved'],403);
            }

            $currentYear = date('Y');
            $currentMonth = date('m');
            $selectedMonth =$req->startmonth;

            if($currentYear ==$req->startdate && $currentMonth >= $selectedMonth){ 
                return response(['msg'=>'Current or previous month is not supported'],403);
            } 

            $student_proposal =new StudentProposal;
            $student_proposal->student_id =$req->student_id;
            $student_proposal->teacher_id =$req->teacher_id;
            $student_proposal->proposal_id =$req->proposal_id;
            $student_proposal->start_year =$req->startdate;
            $student_proposal->start_month =$req->startmonth;
            $student_proposal->preferred_start_date =$req->startdate.'-'.$req->startmonth.'-'.'01'; 
            $student_proposal->student_apply_ref =studentRefNoGenerate();
            $student_proposal->proposal_submit_status = 1;
            $student_proposal->submitted_date = now();
            $student_proposal->created_by =$req->student_id;
            $student_proposal->save();

            $student_data =User::find($student_proposal->student_id);
            $student_data->freez_profile =1;
            $student_data->update();

            $teacher =User::find($student_proposal->teacher_id);
            if($teacher->university_name){
                $university =$teacher->university_name;
            }else{
                $university = cn($teacher,'university.name','');
            }

			if($student_data){
				$data['name'] = $student_data->first_name.' '.$student_data->last_name;
				$data['teacher'] = $teacher->first_name.' '.$teacher->last_name;
                $data['university'] = $university;
                $data['submission_date'] = $student_data->created_at;
                $data['receive_email']=$student_data->email;
				//$data['arn'] = $teacher->ref_no;
				$user_mail =$student_data->email;
				$from = 'asraful@revinr.com';
				Mail::send('email.student_proposal_email',$data, function ($message) use ($user_mail,$from,$student_proposal) {
					$message->from($from);
					$message->to($user_mail)->subject('Apply Ref:' .$student_proposal->student_apply_ref. '- Proposal has been submitted successfully ');
				});
			}

             $proposal =Proposal::where(
                    'student_id',$student_proposal->student_id
                )->where(
                    'id',$student_proposal->proposal_id
                )->first();

             if($teacher){
                $data['name'] = $teacher->first_name.' '.$teacher->last_name;
                $data['std_name'] = $user->first_name.' '.$user->last_name;
                $data['proposal_title'] =$proposal->title;
                $data['date_time']=$student_proposal->submitted_date;
                $data['receive_email']=$teacher->email;
				$user_mail =$teacher->email;
				$from = 'asraful@revinr.com';
				Mail::send('email.teacher_proposal_email',$data, function ($message) use ($user_mail,$from) {
					$message->from($from);
					$message->to($user_mail)->subject('New Proposal Received - Action Required');
				});
             }


            return response(['msg'=>'Proposal send successfully.']);

        }elseif($name=="update_student_proposal"){  

            $new_rules=[
                'proposal_id'=>'required',
            ];

            $validator=\Validator::make($req->all(),$new_rules,[
                'proposal_id.required'=>'Please complete your profile to submit your proposal.',
                'startdate'=>'required',
                'startmonth'=>'required',
            ]);

            if($validator->fails()){

                $errors=$validator->errors()->all();
                return response(['msg'=>$errors[0]], 422);
            }  

            $approved_proposal = StudentProposal::where(
                'student_id',$req->student_id
            )->where(
                'teacher_id',$req->teacher_id
            )->where(
                'proposal_id',$req->proposal_id
            )->where(
                'proposal_submit_status',1
            )->where(
                'proposal_status',5 // 5=interest;
            )->exists();

            if($approved_proposal){
                return response(['msg'=>'Already Selected proposal has been submitted'],403);
            }

            $awaiting = StudentProposal::where(
                'student_id',$req->student_id
            )->where(
                'teacher_id',$req->teacher_id
            )->where(
                'proposal_id',$req->proposal_id
            )->where(
                'proposal_submit_status',1
            )->whereIn(
                'proposal_status',[1,2,3,4] // 1 =New; 2 =In Review; 3=Push; 4=Hold;
            )->exists();

            if($awaiting){
                return response(['msg'=>'Application you have submitted that are currently awaiting decisions'],403);
            }

            $currentYear = date('Y');
            $currentMonth = date('m');
            $selectedMonth =$req->startmonth;

            if($currentYear ==$req->startdate && $currentMonth >= $selectedMonth){ 
                return response(['msg'=>'Current or previous month is not supported'],403);
            } 


            $student_proposal =StudentProposal::find($req->id);
            $student_proposal->proposal_id =$req->proposal_id;
            $student_proposal->start_year =$req->startdate;
            $student_proposal->start_month =$req->startmonth;
            $student_proposal->preferred_start_date =$req->startdate.'-'.$req->startmonth.'-'.'01'; 
            $student_proposal->student_apply_ref =studentRefNoGenerate();
            $student_proposal->proposal_submit_status = 1;
            $student_proposal->submitted_date = now();
            $student_proposal->created_by =$req->student_id;
            $student_proposal->draft_status =0; // Q-Form
            $student_proposal->update();

            $student_data =User::find($student_proposal->student_id);
            $student_data->freez_profile =1;
            $student_data->update();

            $teacher =User::find($student_proposal->teacher_id);

            if($teacher->university_name){
                $university =$teacher->university_name;
            }else{
                $university = cn($teacher,'university.name','');
            }

			if($student_data){
				$data['name'] = $student_data->first_name.' '.$student_data->last_name;
				$data['teacher'] = $teacher->first_name.' '.$teacher->last_name;
                $data['university'] = $university;
                $data['submission_date'] = $student_data->created_at;
                $data['receive_email']=$student_data->email;
				//$data['arn'] = $proposal_user->ref_no;
				$user_mail =$student_data->email;
				$from = 'asraful@revinr.com';
				Mail::send('email.student_proposal_email',$data, function ($message) use ($user_mail,$from,$student_proposal) {
					$message->from($from);
					$message->to($user_mail)->subject('Apply Ref:' .$student_proposal->student_apply_ref. '- Proposal has been submitted successfully ');
				});
			}

             $proposal =Proposal::where(
                    'student_id',$student_proposal->student_id
                )->where(
                    'id',$student_proposal->proposal_id
                )->first();

             if($teacher){
                $data['name'] = $teacher->first_name.' '.$teacher->last_name;
                $data['std_name'] = $student_data->first_name.' '.$student_data->last_name;
                $data['proposal_title'] =$proposal->title;
                $data['date_time']=$student_proposal->submitted_date;
                $data['receive_email']=$teacher->email;
				$user_mail =$teacher->email;
				$from = 'asraful@revinr.com';
				Mail::send('email.teacher_proposal_email',$data, function ($message) use ($user_mail,$from) {
					$message->from($from);
					$message->to($user_mail)->subject('New Proposal Received - Action Required');
				});
             }


            return response(['msg'=>'Successfully updated.']);

        }elseif($name=="add_wishlist"){
            $teacher =Auth::guard('teacher')->user();
            $validator=\Validator::make($req->all(), [
                'name'=>'required',
                'email'=>'required|email|max:255'
            ]);

            if($validator->fails()){
                $errors=$validator->errors()->all();
                return response(['msg'=>$errors[0]], 422);
            }


            $is_user_exists=User::where('email',$req->email)->where('user_type',1)->exists();

            if($is_user_exists){ 

                $user_notify =User::where('email',$req->email)->where('user_type',1)->first();
 
                $is_student_proposal_exists =StudentProposal::where(
                    'teacher_id',$teacher->id
                )->where(
                    'student_id',$user_notify->id
                )->whereIn(
                    'proposal_status',[1,2,3,4] // 1 =New; 2 =In Review; 3=Push; 4=Hold;
                )->exists();

                if($is_student_proposal_exists){
                    return response(
                        ['msg'=>'Already there is an account associated this email ID. Please login to your account.'],403
                    );
                }else{
                    $refer =new ReferUser;
                    $refer->name =$req->name;
                    $refer->email =$req->email;
                    $refer->refer_by =$teacher->id;
                    $refer->teacher_id =$teacher->id;
                    $refer->save();
                }

            }else{
                $user_data =new User;
                $user_data->first_name =$req->name;
                $user_data->email =$req->email;
                $user_data->user_type =1;
                $user_data->status =0;
                $user_data->register_type =4; // 1=invitation ; 2= landing/wishlish; 3 =q_form ; 4=student-wishlist
                $user_data->invitation_date =now();
                $user_data->wishlist_teacher_id =$teacher->id;
                $user_data->save();

                $refer =new ReferUser;
                $refer->name =$req->name;
                $refer->email =$req->email;
                $refer->refer_by =$teacher->id;
                $refer->teacher_id =$teacher->id;
                $refer->save();

                $teacher =User::where('email',$req->email)->where('user_type',1)->first();

                if($teacher->others_department){
                    $department =$teacher->others_department;
                }else{
                    $department = cn($teacher,'department_name.name','');
                }

                if($teacher->university_name){
                    $university =$teacher->university_name;
                }else{
                    $university = cn($teacher,'university.name','');
                }

                $data['name'] = $refer->name;
                $data['teacher_id'] = $refer->teacher_id;
                $data['student_id'] = $user_notify->id;
                $data['std_email'] = $refer->email;
                $data['teacher'] = $teacher->first_name.' '.$teacher->last_name;
                $data['arn'] = $teacher->ref_no;
                $data['designation'] = $teacher->designation;
                $data['department'] = $department;
                $data['university'] =  $university;
                $data['receive_email']=$refer->email;
                $user_mail = $refer->email;
                $from = 'asraful@revinr.com';

                Mail::send('email.wishlist_email',$data, function ($message) use ($user_mail,$from) {
                    $message->from($from);
                    $message->to($user_mail)->subject('Research Admission Platform Sign-Up');
                });
            }
            return response(
                ['msg'=>'Wishlist saved successfully.']
            );

        }elseif($name=="teacher_invited"){
            $admin =Admin::find($req->id);
            $validator=\Validator::make($req->all(), [
                'name'=>'required',
                'email'=>'required|email|max:255'
            ]);

            if($validator->fails()){
                $errors=$validator->errors()->all();
                return response(['msg'=>$errors[0]], 422);
            }

            $isUserExists = User::where(
                'email',$req->email
            )->where(
                'user_type',2
            )->where(function($q){
                $q->where('sign_up',1)->orWhere('sign_up',0);
            })->exists();

            if($isUserExists){
                return response([
                    'msg'=>'Already there is an account associated this email ID.'
                ],403);

            }else{
                $user_data =new User;
                $user_data->first_name =$req->name;
                $user_data->email =$req->email;
                $user_data->admin_invite_id =$admin->id;
                $user_data->user_type =2;
                $user_data->register_type =1; // 1=invitation ; 2=wishlist/landing
                $user_data->invitation_date =now();
                $user_data->save();

                $teacher_user =User::where('email',$req->email)->where('user_type',2)->first();

                $refer =new ReferUser;
                $refer->name =$req->name;
                $refer->email =$req->email;
                $refer->refer_by =$admin->id;
                $refer->teacher_id =$teacher_user->id;
                $refer->save();

                $data['name'] = $refer->name;
                $data['teacher_id'] = $teacher_user->id;
                $data['applicant_name'] = $admin->first_name.' '.$admin->last_name;
                $data['email']=$refer->email;
                $data['receive_email']=$refer->email;
                $user_mail = $refer->email;
                $from = 'asraful@revinr.com';

                if($req->is_currently_open==1){
                    Mail::send('email.invitation_to_supervisor_email_with_checked',$data, function ($message) use ($user_mail,$from) {
                        $message->from($from);
                        $message->to($user_mail)->subject('Accepting doctoral applications! Expedite the process with pre-screening proposals');
                    });
                }else{
                    Mail::send('email.invitation_to_supervisor_email',$data, function ($message) use ($user_mail,$from) {
                        $message->from($from);
                        $message->to($user_mail)->subject('Optimize Your Workflow: Join our Innovative Doctoral Applicant Management Solution');
                    });
                }
            }

            $already_invited =ReferUser::where('email',$refer->email)->count();

            if($already_invited > 1) {
                return response(
                    ['msg'=>"Successfully saved. Already invitation send {$already_invited} times."]
                );
            }else{
                return response(
                    ['msg'=>'Invitation saved successfully.']
                );

            }

        }elseif($name=="add_doc_required"){
            $user=auth_user();

            $new_rules=[
                'others'=>'required|array',
                'others.*.requirement_title'=>'required',
            ];
            $validator=\Validator::make($req->all(),$new_rules,[
                'others.*.requirement_title.required'=>'Please!, fill-up all requirement field.'
            ]);

            if($validator->fails()){
                $errors=$validator->errors()->all();
                return response(['msg'=>$errors[0]], 422);
            }

            $std_proposal=StudentProposal::find($req->id);

            foreach($req->others as $row){
                   Requirement::create([
                    'std_proposal_id'=>$std_proposal->id,
                    'requirement_title'=>$row['requirement_title'],
                    'need_upload'=>$row['need_upload'],
                    'created_by'=>$user->id
                ]);
            }

            return response([
                'msg'=>'Successfully Saved.'
            ]);

        }elseif($name=="edit_doc_required"){
            $requirements=Requirement::find($req->id);
            $requirements->requirement_title =$req->requirement_title;
            $requirements->need_upload =$req->need_upload;
            $requirements->update();

            return response([
                'msg'=>'Successfully updated.'
            ]);
        }elseif($name=="landing_register_form"){

            $validator=\Validator::make($req->all(), [
                'name'=>'required',
                'email'=>'required|email|max:255'
            ]);

            if($validator->fails()){
                $errors=$validator->errors()->all();
                return response(['msg'=>$errors[0]], 422);
            }

            $isUserExists = User::where(
                'email',$req->email
            )->where(
                'user_type',2
            )->where(function($q){
                $q->where('sign_up',1)->orWhere('sign_up',0);
            })->exists();

            if($isUserExists){
                return response([
                    'msg'=>'Already there is an account associated this email ID. Please login to your account.'
                ],403);

            }else{
                $user_data =new User;
                $user_data->first_name =$req->name;
                $user_data->email =$req->email;
                $user_data->nationality =$req->country_id;
                $user_data->university_name =$req->university;
                $user_data->uni_website =$req->uni_website;
                $user_data->user_type =2;
                $user_data->register_type =2; // 1=invitation ; 2= landing/wishlish
                // $user_data->invitation_date =now();
                $user_data->save();

                $user =User::where('email',$req->email)->where('user_type',2)->first();

                $refer =new ReferUser;
                $refer->name =$req->name;
                $refer->email =$req->email;
                $refer->teacher_id =$user->id;
                $refer->save();
            }

            return response(
                ['msg'=>'Successfully saved.']
            );
        }elseif($name=="send_email_document_information"){

            $data['teacher']=User::find($req->teacher_id);
            $data['student']=User::find($req->student_id);
            $data['std_proposal']=StudentProposal::find($req->id);
            $data['doc_requirement_list']=Requirement::where('std_proposal_id',$req->id)->get();
            $student =$data['student'];
            $user_mail = $student->email;
            $data['receive_email']=$student->email;
            $from = 'asraful@revinr.com'; 
           
            Mail::send('email.send_email_document_information',$data, function ($message) use ($user_mail,$from) {
                $message->from($from);
                $message->to($user_mail)->subject('Further Information Required');
            });

            return response(
                ['msg'=>'Send email successfully.']
            );
        
        }elseif($name=="proposal_status_rejected_form"){
            $data['teacher']=Auth::guard('teacher')->user();
            $validator=\Validator::make($req->all(), [
                'feedback'=>'required', 
            ]);

            if($validator->fails()){
                $errors=$validator->errors()->all();
                return response(['msg'=>$errors[0]], 422);
            }

            $proposal =StudentProposal::find($req->id);
            $proposal->proposal_status = 6; // rejected

            if($req->feedback=="others"){ 
                $proposal->feedback_msg =$req->feedback_msg;
                $proposal->feedback_reason =NULL;
            }else{
                $proposal->feedback_reason =$req->feedback;
                $proposal->feedback_msg =NULL;
            }

            $proposal->proposal_status_date =now();
            $proposal->update();  
             
            $student = User::find($proposal->student_id);
            $student->freez_profile =0;
            $student->update(); 

            $teacher =User::find($proposal->teacher_id); 

            if($proposal->feedback_msg){
                $reason  = $proposal->feedback_msg;
            }else{
                $reason  = $proposal->feedback_reason;
            }
            
            $data['teacher'] = $teacher->first_name.' '.$teacher->last_name;
            $data['student'] = $student->first_name.' '.$student->last_name; 
            $data['reason'] =$reason;
            $data['receive_email']=$student->email;
            $from = 'asraful@revinr.com';
            $user_mail = $student->email; 
                  
            Mail::send('email.rejected_status_email',$data, function ($message) use ($user_mail,$from) {
                $message->from($from);
                $message->to($user_mail)->subject('Rejection of Research Application');
            });
            

            return response(
                ['msg'=>'Saved successfully.']
            );
             
        }

        return response(['msg'=>'No name argument found.'], 403);

    }

}