<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\Helpers\PageSL;
use App\User;
use App\Models\MarketCountry;
use App\Models\University;
use App\Models\Department;
use App\Models\ReferUser;
use App\Models\ResearchInterest;
use App\Models\Requirement;
use App\StudentProposal;
use Session;
use Mail;
use Auth;
use Hash;


class AjaxController extends Controller
{
    public function get($name, Request $req)
	{
		if($name=='available_ref_no_search') {

		}elseif(empty($name)){
            return response([
            'msg'=>'Invalid request please insert correct value!.'
            ], 403);
        }
	}

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

		if($name =='teacher_change_password') {

			$validator=\Validator::make($req->all(), [
                'old_password'=>'required',
                'new_password_confirmation'=>'required',
                'new_password'=>[
                    'required',
                    'confirmed',
                    'min:8',
                    //'regex:/[a-z]/',
                    //'regex:/[A-Z]/',
                    //'regex:/[0-9]/',
                    //'regex:/[@$!%*#?&]/',
                ]
            ]);
			//  [
            //     'regex' => 'The :attribute must contain at least one lowercase, uppercase, digit and special character.'
            // ]);

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

            $user=auth_user('teacher');

            if(\Illuminate\Support\Facades\Hash::check($req->old_password, $user->password)) {

                $user->password=bcrypt($req->new_password);
                $user->update();

                return ['msg'=>'Your login password updated successfully!. Please use your new password for next time login.'];

            }else{

                return response(
                    ['msg'=>'Sorry!, old password does not match with login credential.'],
                    403
                );

            }

		}elseif($name=="teacher_user_status_change"){
            $user=auth_user('teacher');
            $teacher =User::find($req->id);
            $teacher->status =$req->status;
            $teacher->update();

            $data['name'] = $teacher->first_name.' '.$teacher->last_name;
            $user_mail = $teacher->email;
            $from = 'test@mail.com';
            if($teacher->status==1){
                Mail::send('email.approve_teacher_email',$data, function ($message) use ($user_mail,$from) {
                    $message->from($from);
                    $message->to($user_mail)->subject('New Email Send to you');
                });
            }
            return response(
                ['msg'=>'Your login permission successfully updated.']
            );

        }elseif($name=="set_country"){
            $user =Auth::guard('admin')->user();
            if($req->checked == 'true'){
                $mc = new MarketCountry;
                $mc->country_id = $req->id;
                $mc->status = 1;
                $mc->added_by = $user->id;
                $mc->save();
                return response(
                    ['msg'=>'Added Successfully.']
                );
            }else{
                MarketCountry::where('country_id', $req->id)->delete();

                return response(
                    ['msg'=>'Removed Successfully.']
                );
            }
        }elseif($name=="add_country_wise_uni"){
            $user =Auth::guard('admin')->user();
            $validator=\Validator::make($req->all(), [
                'country_id'=>'required',
                'university_name'=>'required',
                'university_website'=>'required',
            ]);

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

            $data =new University;
            $data->country_id =$req->country_id;
            $data->name =$req->university_name;
            $data->web_address =$req->university_website;
            $data->save();

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


        }elseif($name=="add_department"){
            $user =Auth::guard('admin')->user();

            $validator=\Validator::make($req->all(), [
                'dapartment'=>'required',
            ]);

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

            $data =new Department;
            $data->name =$req->dapartment;
            $data->status =1;
            $data->save();

            return response(
                ['msg'=>'Department saved successfully.']
            );

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

            $validator=\Validator::make($req->all(), [
                'first_name'=>'required',
                'last_name'=>'required',
                'university_name'=>'required',
                'department'=>'required',
            ]);

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

            $data = User::find($req->id);
            $data->first_name =$req->first_name;
            $data->last_name =$req->last_name;
            $data->university_name =$req->university_name;
            $data->department =$req->department;
            $data->update();

            return response(
                ['msg'=>'Saved successfully.']
            );
        }elseif($name=="add_refer_user"){
            $user =Auth::user();
            $validator=\Validator::make($req->all(), [
                'name'=>'required',
                'email'=>'required|email|max:255|unique:refer_users'
            ]);

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

            $std_proposal =StudentProposal::where('student_id',$user->id)->first();

            if(empty($std_proposal)){
                return response(
                    ['msg'=>'Sorry! you have to submit a proposal first.'],403
                );
            }

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

            if($refer->save()){
                $data['name'] = $refer->name;
                $data['teacher_id'] = $refer->teacher_id;
                $data['std_email'] = $refer->email;
                $data['applicant_name'] = $user->first_name.' '.$user->last_name;
                $user_mail = $refer->email;
                $from = 'test@mail.com';

                Mail::send('email.refer_email',$data, function ($message) use ($user_mail,$from) {
                    $message->from($from);
                    $message->to($user_mail)->subject('New Email Send to you');
                });
            }

            return response(
                ['msg'=>'Refer saved successfully.']
            );
        }elseif($name=="research_interest"){

            $validator=\Validator::make($req->all(), [
                'research'=>'required',
            ]);

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

            $data = new ResearchInterest;
            $data->teacher_id =$req->id;
            $data->research =$req->research;
            $data->save();

            return response(
                ['msg'=>'Saved successfully.']
            );
        }elseif($name=="edit_university_save"){
            $user=Auth::guard('admin')->user();
            $validator=\Validator::make($req->all(), [
                'country_id'=>'required',
                'university_name'=>'required',
                'university_website'=>'required',
            ]);

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

			$data =University::find($req->edit_id);
            $data->country_id =$req->country_id;
            $data->name =$req->university_name;
            $data->web_address =$req->university_website;
            $data->update();

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

        }elseif($name=="delete_university_info"){
            $user=Auth::guard('admin')->user();
            $data =University::find($req->delete_id);
            $data->delete();
            return response([
                'msg'=>'Successfully Deleted'
            ]);

        }elseif($name=="delete_department_info"){
            $user=Auth::guard('admin')->user();
            $data =Department::find($req->delete_id);
            $data->delete();
            return response([
                'msg'=>'Successfully Deleted'
            ]);
        }elseif($name=="edit_department_save"){
            $user=Auth::guard('admin')->user();
            $validator=\Validator::make($req->all(), [
                'department'=>'required',
            ]);

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

            $data =Department::find($req->edit_id);
            $data->name =$req->department;
            $data->update();
            return response([
                'msg'=>'Successfully updated.'
            ]);
        }elseif($name=="concept_status_update"){

            $data =StudentProposal::find($req->id);
            $data->concept =$req->value;
            $data->update();

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

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

            $data =StudentProposal::find($req->id);
            $data->proposal_status =$req->value;
            $data->proposal_status_date =now();
            $data->feedback_msg =NULL;

            $data->update();

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

        }elseif($name=="proposal_feedback_update"){
            $validator=\Validator::make($req->all(), [
                'message'=>'required',
            ]);

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

            $data =StudentProposal::find($req->id);
            $data->proposal_status =$req->proposal_status;
            $data->feedback_msg =$req->message;
            $data->proposal_status_date =now();
            $data->update();

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

        }elseif($name=="accept_status_update"){
            $data =StudentProposal::find($req->id);
            $data->accepted_status =1;
            $data->accepted_date =now();
            $data->update();

            return response([
                'msg'=>'Updated successfully.'
            ]);
        }elseif($name=="proposal_quality_rate_star_update"){
            $data =StudentProposal::find($req->id);
            $data->proposal_quality =$req->value;
            $data->update();

            return response([
                'msg'=>'Updated successfully.'
            ]);
        }elseif($name=="teacher_is_available"){
            $user =Auth::guard('teacher')->user();

            $data =User::find($user->id);
            if($req->checked =="true"){
                $data->is_available =1;
            }else{
                $data->is_available =0;
            }

            $data->update();
            return response(
                ['msg'=>"Updated Successfully."]
            );
        }elseif($name=="student_q_form"){

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

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

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

            // if($refer->save()){
            //     $data['name'] = $refer->name;
            //     $data['teacher_id'] = $refer->teacher_id;
            //     $data['std_email'] = $refer->email;
            //     $data['applicant_name'] = $user->first_name.' '.$user->last_name;
            //     $user_mail = $refer->email;
            //     $from = 'test@mail.com';

            //     Mail::send('email.refer_email',$data, function ($message) use ($user_mail,$from) {
            //         $message->from($from);
            //         $message->to($user_mail)->subject('New Email Send to you');
            //     });
            // }

            return response(
                ['msg'=>'Saved successfully.']
            );
        }elseif($name=="add_wishlist_registration"){
            
            $validator=\Validator::make($req->all(), [
                'first_name'=>'required',
                'last_name'=>'required',
                'dob'=>'required',
                'gender'=>'required',
                'nationality'=>'required',
                'email'=>'required',
                'password_confirmation'=>'required',
                'password'=>[
                    'required',
                    'confirmed',
                    'min:8',
                ]
            ]);

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

            $user_data = User::find($req->id);

            if($user_data){

                $user_exists = ReferUser::where('email',$req->email)->where('signup',1)->exists();

                if($user_exists){
                    return response(['msg'=>'You are already registered!.Please login.'], 403);
                }

                $refer_user_signup = ReferUser::where('email',$req->email)->where('signup',0)->first();

                if($refer_user_signup){
                    $refer_user_signup->signup =1;
                    $refer_user_signup->update();
                }

                $user_data->first_name =$req->first_name;
                $user_data->last_name =$req->last_name;
                $user_data->first_name =$req->first_name;
                $user_data->nationality =$req->nationality;
                $user_data->dob =\Carbon\Carbon::parse($req->dob)->format('Y-m-d');
                $user_data->gender =$req->gender;
                $user_data->password =Hash::make($req->password);
                $user_data->status =1;
                $user_data->update();

                return response(
                    ['msg'=>'Registration successfully saved.You can login now']
                );
            }

        }elseif($name=="invited_registration"){
            $validator=\Validator::make($req->all(), [
                'first_name'=>'required',
                'last_name'=>'required',
                'email'=>'required',
                'university'=>'required',
                'department'=>'required',
                'designation'=>'required',
                'password_confirmation'=>'required',
                'password'=>[
                    'required',
                    'confirmed',
                    'min:8',
                ]
            ]);

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

            $user_data = User::find($req->id);

            if($user_data){

                $user_exists = ReferUser::where('email',$req->email)->where('signup',1)->exists();

                if($user_exists){
                    return response(['msg'=>'You are already registered!.Please login.'], 403);
                }

                $refer_user_signup = ReferUser::where('email',$req->email)->where('signup',0)->first();

                if($refer_user_signup){
                    $refer_user_signup->signup =1;
                    $refer_user_signup->update();
                }

                $user_data->first_name =$req->first_name;
                $user_data->last_name =$req->last_name;
                $user_data->first_name =$req->first_name;
                $user_data->university_name =$req->university;
                $user_data->ref_no = name_initials($req->first_name,$req->last_name).''.teacherRefNoGenerate();
                $user_data->department =$req->department;
                $user_data->others_department =$req->others_department;
                $user_data->designation =$req->designation;
                $user_data->uni_website =$req->website;
                $user_data->password =Hash::make($req->password);
                $user_data->status =1;
                $user_data->invited_registered_at = now();
                $user_data->update();

                return response(
                    ['msg'=>'Registration successfully saved.You can login now.']
                );
            }

        }elseif($name=="delete_doc_required"){
            $requirements=Requirement::find($req->delete_id);
            $requirements->delete();
            return response([
                'msg'=>'Deleted Successfully.'
            ]);
        }elseif($name=="document_required_upload_save"){

            $rules=[
                'id'=>'required',
                'document_file' => 'required',
            ];
            
            $validator=\Validator::make($req->all(), $rules);

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

            $data=Requirement::find($req->id);
            $std_ref = StudentProposal::find($data->std_proposal_id);
            
            if($req->document_file){
                $destinationPath =   public_path('/uploads/required_doc');
                $file = $req->document_file;
                $ext = $file->getClientOriginalExtension();
                $fileName = 'document_file_'.$std_ref->student_apply_ref.'.'.$ext;
                if(file_exists($destinationPath.'/'.$fileName)){
                    @unlink($destinationPath.'/'.$fileName);
                }
                $file->move($destinationPath, $fileName);
    
                $data->document_file = $fileName; 

            }

            $data->update();

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

        }
	}
}
