<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Redirect;
use Input;
use Validator;

use App\Models\Employee;
use App\Models\PayrollHistory;
use App\Models\EmployeeEducation;
use App\Models\EmployeeDocument;
use App\Models\EducationLevel;
use App\Models\DocumentType;
use App\Models\Grade;
use App\Models\Designation;
use App\Models\EmploymentDetail;
use App\Models\employee_reference;
use App\Models\EmployeeWorkExperience;
use App\Models\PayrollStructure;
use App\Models\GradeStructure;
use App\Models\PayrollStructureDetail;
use App\Models\Role;
use App\User;

class EmployeeController extends Controller
{
    
    public function index()
    {
        $data['title'] = "Employee management";
        $data['all'] = Employee::with('user')->orderBy('name','ASC')->get();
        return view('admin.employee.employee',$data);
    }
    public function create()
    {
        $data['title'] = "Employee management";
        $data['all_document'] = DocumentType::where('status',1)->orderBy('document_name','ASC')->get();
        $data['all_level'] = EducationLevel::where('status',1)->orderBy('level_name','ASC')->get();
        $data['all_grade'] = grade::where('status',1)->orderBy('name','ASC')->get();
        $data['all_designation'] = Designation::where('status',1)->orderBy('name','ASC')->get();
        return view('admin.employee.employee_add',$data);
    }

    public function store(Request $request)
    {
        //dd($request->all());
        $this->validate($request,[
            'name'            => 'required',
            'personal_email'  => 'required|email|unique:employees,personal_email',
            'phone'           => 'required',
            'present_address' => 'required',
            'birth_day' => 'required',
            'joining_date' => 'required',
            'current_designation' => 'required',
            'salary_grade' => 'required'
        ]);

        $user_id = \Auth::user()->id;
        $employee_info = new Employee;
        $employee_info->name = $request->name;
        $employee_info->personal_email = $request->personal_email;
        $employee_info->phone = $request->phone;
        $employee_info->phone2 = $request->phonetwo;
        $employee_info->present_address = $request->present_address;
        $employee_info->per_address = $request->per_address;
        $employee_info->birth_day = $request->birth_day;
        $employee_info->note = $request->note;
        $employee_info->facebook = $request->facebook;
        $employee_info->skype = $request->skype;
        $employee_info->linkedin = $request->linkedin;
        $employee_info->added_by = $user_id;
        $employee_info->status = 1;
            if (!empty($request->file('image'))) {
                $file =$request->file('image');
                $destPath = 'assets/document/employee/';
                $fileName = $file->getClientOriginalName();
                $newFile = "employee_".date('d_m_y_h_m_s')."_".$fileName;
                $file->move($destPath, $newFile);
                $employee_info->image = $newFile;
            }
        $employee_info->save();

        $emp_details = new EmploymentDetail;
        $emp_details->employee_id = $employee_info->id;
        $emp_details->designation_id = $request->current_designation;
        $emp_details->grade_id = $request->salary_grade;
        $emp_details->joining_date = $request->joining_date;
        $emp_details->type = "1";
        $emp_details->added_by = $user_id;
        $emp_details->save();

        $prst = new PayrollStructure;
        $prst->employee_id = $employee_info->id;
        $prst->grade_id = $request->salary_grade;
        $prst->type = "1";
        $prst->date = $request->joining_date;
        $prst->added_by = $user_id;
        $prst->save();

        if (!empty($request->file('file') && !empty($request->document_id))) {
            $files = $request->file('file');
            foreach($files as $key => $file) {
                $destinationPath = 'assets/document/employeedocument/';
                $extension = $file->getClientOriginalExtension();
                $filename = $file->getClientOriginalName();
                $newFileName = "document_".date('d_m_y_h_m_s')."_".$filename;
                $file->move($destinationPath, $newFileName);

                $document = new EmployeeDocument;
                $document->document_id = $request['document_id'][$key];
                $document->employee_id = $employee_info->id;
                $document->file = $newFileName;
                $document->status = 1;
                $document->added_by = $user_id ;
                $document->save();

            }
        }
            
        if (!empty($request->edu_level) && !empty($request->institute) && !empty($request->major) && !empty($request->marks) && !empty($request->passing_year) ) {
            $input = $request->all();
            $condition = $input['edu_level'];
            foreach ($condition as $key => $condition) {
                $student = new EmployeeEducation;
                $student->edu_level_id = $input['edu_level'][$key];
                $student->institute_name = $input['institute'][$key];
                $student->major = $input['major'][$key];
                $student->marks = $input['marks'][$key];
                $student->passing_year = $input['passing_year'][$key];
                $student->duration = $input['duration'][$key];
                $student->employee_id = $employee_info->id ;
                $student->status = 1 ;
                $student->added_by = $user_id ;
                $student->save();
            }
        }
        if (!empty($request->org_name) && !empty($request->org_contact) && !empty($request->designation) && !empty($request->start_date) && !empty($request->end_date) ) {
            $input = $request->all();
            $condition = $input['org_name'];
            foreach ($condition as $key => $condition) {
                $ewe = new EmployeeWorkExperience;
                $ewe->org_name = $input['org_name'][$key];
                $ewe->org_contact = $input['org_contact'][$key];
                $ewe->designation_id = $input['designation'][$key];
                $ewe->start_date = $input['start_date'][$key];
                $ewe->end_date = $input['end_date'][$key];
                $ewe->employee_id = $employee_info->id ;
                $ewe->added_by = $user_id ;
                $ewe->save();
            }
        }
        if ($request->person_name !="" && $request->relation !="" && $request->phone1 !=""  && $request->address !="" ) {
            $input = $request->all();
            $condition = $input['person_name'];
            foreach ($condition as $key => $condition) {
                $employee_ref = new employee_reference;
                $employee_ref->person_name = $input['person_name'][$key];
                $employee_ref->relation = $input['relation'][$key];
                $employee_ref->phone1 = $input['phone1'][$key];
                $employee_ref->phone2 = $input['phone2'][$key];
                $employee_ref->email = $input['email'][$key];
                $employee_ref->address = $input['address'][$key];
                $employee_ref->employee_id = $employee_info->id ;
                $employee_ref->status = 1 ;
                $employee_ref->added_by = $user_id ;
                $employee_ref->save();
            }
        }
       return redirect('admin/employee')->with('msg','Data Insert Successful!');
    }
    
    public function show($id)
    {
        $data['title'] = "Employee Information";
        $data['employee'] = Employee::find($id);
        $data['emp_details'] = EmploymentDetail::with(['designation','grade'])->where('employee_id',$id)->orderBy('id','DESC')->first();
        $data['emp_history'] = EmploymentDetail::with(['designation','grade'])->where('employee_id',$id)->orderBy('id','ASC')->get();
        $data['emp_star'] = EmploymentDetail::where('employee_id',$id)->where('type',2)->select('id')->get();
        $data['employee_ewe'] = EmployeeWorkExperience::with('designation')->where('employee_id',$id)->orderBy('start_date','DESC')->get();
        $data['pay_history'] = PayrollHistory::where('employee_id',$id)->orderBy('id','DESC')->get();
        $data['ref_info'] = employee_reference::where('employee_id',$id)->first();
        $data['employee_document'] = EmployeeDocument::with('document_type')->where('employee_id',$id)->get();
        $data['employee_education'] = EmployeeEducation::with('education_name')->where('employee_id',$id)->get();
        $data['last_education'] = EmployeeEducation::with('education_name')->where('employee_id',$id)->orderBy('passing_year','DESC')->first();
        $data['employee_ref'] = employee_reference::where('employee_id',$id)->get();
        return view('admin.employee.employee_view',$data);
    }
    
    public function editEmployee($id)
    {
        $data['title'] = "Employee Edit";
        $data['all_document'] = DocumentType::where('status',1)->orderBy('document_name','ASC')->get();
        $data['all_level'] = EducationLevel::where('status',1)->orderBy('level_name','ASC')->get();
        $data['employee'] = Employee::find($id);
        $data['employee_document'] = EmployeeDocument::where('employee_id',$id)->get();
        $data['all_grade'] = grade::where('status',1)->orderBy('name','ASC')->get();
        $data['all_designation'] = Designation::where('status',1)->orderBy('name','ASC')->get();
        $data['emp_details'] = EmploymentDetail::where('employee_id',$id)->orderBy('id','ASC')->get();
        $data['employee_ewe'] = EmployeeWorkExperience::where('employee_id',$id)->orderBy('start_date','DESC')->get();
        $data['employee_education'] = EmployeeEducation::where('employee_id',$id)->get();
        $data['employee_ref'] = employee_reference::where('employee_id',$id)->get();
        return view('admin.employee.employee_edit',$data);
    }

   
    public function update(Request $request, $id)
    {
        $user_id = \Auth::user()->id;
        
        $this->validate($request,[
            'name'            => 'required',
            'personal_email'  => 'required|email',
            'phone'           => 'required',
            'present_address' => 'required',
            'birth_day' => 'required'
        ]);
        $user_id = \Auth::user()->id;
        $employee_info = Employee::find($id);
        $employee_info->name = $request->name;
        $employee_info->personal_email = $request->personal_email;
        $employee_info->phone = $request->phone;
        $employee_info->phone2 = $request->phonetwo;
        $employee_info->present_address = $request->present_address;
        $employee_info->per_address = $request->per_address;
        $employee_info->birth_day = $request->birth_day;
        $employee_info->note = $request->note;
        $employee_info->facebook = $request->facebook;
        $employee_info->skype = $request->skype;
        $employee_info->linkedin = $request->linkedin;
        $employee_info->updated_by = $user_id;
            if (!empty($request->file('image'))) {
                $file =$request->file('image');
                $destPath = 'assets/document/employee/';
                $fileName = $file->getClientOriginalName();
                $newFile = "employee_".date('d_m_y_h_m_s')."_".$fileName;
                $file->move($destPath, $newFile);
                $employee_info->image = $newFile;
            }
        $employee_info->save();

        // if not add new Employment History
        if (!empty($request->joining_date) && !empty($request->current_designation) && !empty($request->salary_grade)) {
            $input = $request->all();
            $condition = $input['joining_date'];
            foreach ($condition as $key => $condition) {
                $emp_we_id = $input['emp_we_id'][$key];
                $emp_details =EmploymentDetail::find($emp_we_id);
                $emp_details->designation_id = $input['current_designation'][$key];
                $emp_details->grade_id = $input['salary_grade'][$key];
                $emp_details->joining_date = $input['joining_date'][$key];
                $emp_details->updated_by = $user_id ;
                $emp_details->save();
            }
            //Payroll Structure
            $find = PayrollStructure::where('employee_id',$employee_info->id)->first();
            if ($find==NULL) {
                $prst = new PayrollStructure;
                $prst->employee_id = $employee_info->id;
                $prst->grade_id = $emp_details->grade_id;
                $prst->date =$emp_details->joining_date;
                $prst->added_by = $user_id;
                $prst->type = 1;
                $prst->save();
            }
            else{
                $prstu = PayrollStructure::find($find->id);
                $prstu->grade_id = $emp_details->grade_id;
                $prstu->date =$emp_details->joining_date;
                $prstu->updated_by = $user_id;
                $prstu->type = 1;
                $prstu->update();
            }
        }
        // if add new Employment History
        if (!empty($request->new_emp_we_id)) {
            if (!empty($request->joining_date_new) && !empty($request->current_designation_new) && !empty($request->salary_grade_new)) {
            $input = $request->all();
            $condition = $input['joining_date_new'];
            foreach ($condition as $key => $condition) {
                $emp_details_new = new EmploymentDetail;
                $emp_details_new->employee_id = $id;
                $emp_details_new->designation_id = $input['current_designation_new'][$key];
                $emp_details_new->grade_id = $input['salary_grade_new'][$key];
                $emp_details_new->joining_date = $input['joining_date_new'][$key];
                $emp_details_new->type = 2 ;
                $emp_details_new->added_by = $user_id ;
                $emp_details_new->save();
                }

                //Payroll Structure
                $find = PayrollStructure::where('employee_id',$employee_info->id)->first();
                if ($find==NULL) {
                    $prst = new PayrollStructure;
                    $prst->employee_id = $employee_info->id;
                    $prst->grade_id = $emp_details_new->grade_id;
                    $prst->date =$emp_details_new->joining_date;
                    $prst->type = 2;
                    $prst->added_by = $user_id;
                    $prst->save();
                    if ($prst->save()) {
                        PayrollStructureDetail::where('structure_id',$prst->id)->delete();
                    }
                }
                else{
                    $prstu = PayrollStructure::find($find->id);
                    $prstu->employee_id = $employee_info->id;
                    $prstu->grade_id = $emp_details_new->grade_id;
                    $prstu->date =$emp_details_new->joining_date;
                    $prstu->type = 2;
                    $prstu->updated_by = $user_id;
                    $prstu->update();
                    if ($prstu->update()) {
                        PayrollStructureDetail::where('structure_id',$prstu->id)->delete();
                    }
                }
            }
        }

        // if not add new File Upload
        if (!empty($request->document_id) && !empty($request->file('file'))) {
                $files = $request->file('file');
                foreach($files as $key => $file) { 
                $emp_doc_id= $request['emp_doc_id'][$key];
                $document =EmployeeDocument::find($emp_doc_id);
                if (!empty($request['file'][$key])) {
                    $destinationPath = 'assets/document/employeedocument/';
                     $filename = $file->getClientOriginalName();
                     $newFileName = "document_".date('d_m_y_h_m_s')."_".$filename;
                    $file->move($destinationPath, $newFileName);
                    $document->file = $newFileName;
                }
                $document->document_id = $request['document_id'][$key];
                $document->updated_by = $user_id ;
                $document->save();

                }
            }
        // if add new File Upload
       if (!empty($request->new_doc_id)) {
           if (!empty($request->file('file_new') && !empty($request->document_id_new))) {
            $files = $request->file('file_new');
            foreach($files as $key => $file) {
                $destinationPath = 'assets/document/employeedocument/';
                $filename = $file->getClientOriginalName();
                $newFileName = "document_".date('d_m_y_h_m_s')."_".$filename;
                $file->move($destinationPath, $newFileName);

                $document = new EmployeeDocument;
                $document->document_id = $request['document_id_new'][$key];
                $document->employee_id = $id;
                $document->file = $newFileName;
                $document->status = 1;
                $document->added_by = $user_id ;
                $document->save();
                }
            }
        }
        // if not add new Academic Information
        if (!empty($request->edu_level) && !empty($request->institute) && !empty($request->major) && !empty($request->marks) && !empty($request->passing_year) ) {
            $input = $request->all();
            $condition = $input['edu_level'];
            foreach ($condition as $key => $condition) {
                $emp_edu_id = $input['emp_edu_id'][$key];
                $student =EmployeeEducation::find($emp_edu_id);
                $student->edu_level_id = $input['edu_level'][$key];
                $student->institute_name = $input['institute'][$key];
                $student->major = $input['major'][$key];
                $student->marks = $input['marks'][$key];
                $student->passing_year = $input['passing_year'][$key];
                $student->duration = $input['duration'][$key];
                $student->updated_by = $user_id ;
                $student->save();
            }
        }
        // if add new Academic Information
        if (!empty($request->new_edu_id)) {
            if (!empty($request->edu_level_new) && !empty($request->institute_new) && !empty($request->major_new) && !empty($request->marks_new) && !empty($request->passing_year_new) ) {
                $input = $request->all();
                $condition = $input['edu_level_new'];
                foreach ($condition as $key => $condition) {
                    $student = new EmployeeEducation;
                    $student->edu_level_id = $input['edu_level_new'][$key];
                    $student->institute_name = $input['institute_new'][$key];
                    $student->major = $input['major_new'][$key];
                    $student->marks = $input['marks_new'][$key];
                    $student->passing_year = $input['passing_year_new'][$key];
                    $student->duration = $input['duration_new'][$key];
                    $student->employee_id = $id ;
                    $student->status = 1 ;
                    $student->added_by = $user_id ;
                    $student->save();
                }
            }
        }
        // if not add new Work Experience
        if (!empty($request->org_name) && !empty($request->org_contact) && !empty($request->designation) && !empty($request->start_date) && !empty($request->end_date) ) {
            $input = $request->all();
            $condition = $input['org_name'];
            foreach ($condition as $key => $condition) {
                $emp_exp_id = $input['emp_exp_id'][$key];
                $ewe = EmployeeWorkExperience::find($emp_exp_id);
                $ewe->org_name = $input['org_name'][$key];
                $ewe->org_contact = $input['org_contact'][$key];
                $ewe->designation_id = $input['designation'][$key];
                $ewe->start_date = $input['start_date'][$key];
                $ewe->end_date = $input['end_date'][$key];
                $ewe->updated_by = $user_id ;
                $ewe->save();
            }
        }
        // if add new Work Experience
        if (!empty($request->org_name_new) && !empty($request->org_contact_new) && !empty($request->designation_new) && !empty($request->start_date_new) && !empty($request->end_date_new) ) {
            $input = $request->all();
            $condition = $input['org_name_new'];
            foreach ($condition as $key => $condition) {
                $ewe = new EmployeeWorkExperience;
                $ewe->org_name = $input['org_name_new'][$key];
                $ewe->org_contact = $input['org_contact_new'][$key];
                $ewe->designation_id = $input['designation_new'][$key];
                $ewe->start_date = $input['start_date_new'][$key];
                $ewe->end_date = $input['end_date_new'][$key];
                $ewe->employee_id = $employee_info->id ;
                $ewe->added_by = $user_id ;
                $ewe->save();
            }
        }
        
        // if not add new Reference / Emergence Contact
        if (!empty($request->person_name) && !empty($request->relation) && !empty($request->phone1) && !empty($request->address)) {
            $input = $request->all();
            $condition = $input['person_name'];
            foreach ($condition as $key => $condition) {
                $emp_ref_id = $input['emp_ref_id'][$key];
                $student =employee_reference::find($emp_ref_id);
                $student->person_name = $input['person_name'][$key];
                $student->relation = $input['relation'][$key];
                $student->phone1 = $input['phone1'][$key];
                $student->phone2 = $input['phone2'][$key];
                $student->email = $input['email'][$key];
                $student->address = $input['address'][$key];
                $student->updated_by = $user_id ;
                $student->save();
            }
        }
        // if add new Reference / Emergence Contact
        if (!empty($request->new_ref_id)) {
            if (!empty($request->person_name_new) && !empty($request->relation_new) && !empty($request->phone1_new) && !empty($request->address_new)) {
            $input = $request->all();
            $condition = $input['person_name_new'];
            foreach ($condition as $key => $condition) {
                $employee_ref = new employee_reference;
                $employee_ref->person_name = $input['person_name_new'][$key];
                $employee_ref->relation = $input['relation_new'][$key];
                $employee_ref->phone1 = $input['phone1_new'][$key];
                $employee_ref->phone2 = $input['phone2_new'][$key];
                $employee_ref->email = $input['email_new'][$key];
                $employee_ref->address = $input['address_new'][$key];
                $employee_ref->employee_id = $employee_info->id ;
                $employee_ref->status = 1 ;
                $employee_ref->added_by = $user_id ;
                $employee_ref->save();
                }
            }
        }

       return redirect('admin/employee')->with('msg','Data Updated Successful!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Employee::whereId($id)->delete();
        EmploymentDetail::where('employee_id',$id)->delete();
        EmployeeWorkExperience::where('employee_id',$id)->delete();
        EmployeeEducation::where('employee_id',$id)->delete();
        EmployeeDocument::where('employee_id',$id)->delete();
        PayrollStructure::where('employee_id',$id)->delete();
        return redirect('admin/employee')->with('msg','Successfully Deleted!');
    }
    public function statusUpdate($id)
    {
        $employee = Employee::find($id);
        if($employee->status == 0){
            $employee->status = 1;
            $status = 'published';
        }else{
            $employee->status = 0;
            $status = 'unpublished';
        }
        $user_id = \Auth::user()->id;
        $employee->approved_by = $user_id;
        $employee->update();

    }
    public function addUser($id)
    {
        $data['title'] = "Employee to User";
        $data['employee'] = Employee::find($id);
        $data['roles']=Role::orderBy('name','ASC')->get();
        return view('admin.employee.employee_to_user',$data);
    }
    public function addToUser(Request $request,$id)
    {
        $this->validate($request,[
            'email'            => 'required|email|unique:users,email',
            'password'  => 'required',
            'confirm_password' => 'required|same:password',
            'role' => 'required',
        ]);
        $employee = Employee::find($id);
        $name = $employee->name;
        $email = $request->email;
        $phone = $employee->phone;
        $present_address = $employee->present_address;
        $per_address = $employee->per_address;
        $facebook = $employee->facebook;
        $skype = $employee->skype;
        $linkedin = $employee->linkedin;
        $password = bcrypt($request->password);

        $user = new User;
        $user->name = $name;
        $user->email = $email;
        $user->password = $password;
        $user->mob = $phone;
        $user->address = $present_address;
        $user->per_address = $per_address;
        $user->fb = $facebook;
        $user->skype = $skype;
        $user->linkedin = $linkedin;
        $user->employee_id = $employee->id;
        $user->active = 1;;
        $user->utype = 2;
        $user->save();
        if (!empty($request->input('role'))) {
            $user->attachRole($request->role);
        }
        return redirect('admin/employee')->with('msg','Employee To User Add Successful !');
    }
    public function changePassword(Request $request)
    {
        $this->validate($request,[
            'password'  => 'required',
            'password_confirmation' => 'required|same:password',
        ]);
        $emp_id = $request->emp_id;
         $password = bcrypt($request->password);

        $user = User::find($emp_id);
        $user->password = $password;
        $user->update();
        return redirect('admin/employee')->with('msg','Password Change Successful !');
    }
    public function rejoining(Request $request)
    {
        $user_id = \Auth::user()->id;
        $emp_id = $request->emp_id;
        $emp_data = EmploymentDetail::where('employee_id',$emp_id)->orderBy('id','DESC')->first();
        $findre = PayrollStructure::where('employee_id',$emp_id)->first();
        $emp = Employee::find($emp_id);
        $emp->status = 4;
        $emp->added_by = $user_id;
        $emp->save();

        $rejoining =  new EmploymentDetail;
        $rejoining->employee_id =  $emp_id;
        $rejoining->designation_id =  $emp_data->designation_id;
        $rejoining->grade_id =  $emp_data->grade_id;
        $rejoining->joining_date =  $request->rejoining_date;
        $rejoining->type =  4;
        $rejoining->added_by = $user_id;
        $rejoining->save();

        $prstre = PayrollStructure::find($findre->id);
        $prstre->type = 4;
        $prstre->update();
                
        return redirect()->back()->with('msg','Employee Rejoining Successfully. !');
    }

}
