<?php

namespace App\Http\Controllers;

use App\Models\Log;
use App\Models\Indexing;
use App\Models\EBM;
use App\Models\Journal;
use App\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Auth;
use DB;
use File;

class EBMController extends BenthamController
{

    public function index(Request $request)
    {
        $createPermission = false;
        $editPermission   = false;
        $deletePermission = true;

        $param['journal_id']  = trim($request->get('journal_id'));
        $param['role_id']     = trim($request->get('role_id'));
        $param['country']     = trim($request->get('country_id'));
        $param['name']        = trim($request->get('name'));
        $param['email']       = trim($request->get('email'));
        $param['keyword']     = trim($request->get('keyword'));

        if (checkPermission('EditorialBoardMember', 'create')) {
            $createPermission = true;
        }
        if (checkPermission('EditorialBoardMember', 'edit')) {
            $editPermission = true;
        }
        if (checkPermission('EditorialBoardMember', 'delete')) {
            $deletePermission = true;
        }

        if ($request->get('export')) {
            $ebm_report = EBM::GetEBMReport($param);
            //dd($ebm_report);
            $this->generatecsv($ebm_report);
        }

        $journal_search = EBM::GetJournalList();
        $country_search = EBM::GetCountryList();
        $ebm_role_search = EBM::GetAllEBMRole();

        $editors_list = EBM::GetAllEditors($param);

        return view('admin.editorial_board_member.ebm', ['createPermission' => $createPermission, 'editPermission' => $editPermission, 'deletePermission' => $deletePermission, 'editors_list' => $editors_list, 'journal_search' => $journal_search, 'country_search' => $country_search, 'ebm_role_search' => $ebm_role_search, 'param' => $param]);
    }

    public function create(Request $request)
    {
        $country_list = Country::GetCountryList();
        return view('admin.editorial_board_member.ebm_add', ['country_list' => $country_list]);
    }

    public function store(Request $request)
    {
        if (DB::table('tbl_editors')->where('email', '=', $request->get('email'))->exists()) {
            return Redirect::back()->withErrors('Email already exist!');
        }
        if ($request->get('institution_id')) {
            $institute = EBM::GetInstitutebyID($request->get('institution_id'));
            $institute_name = $institute->name;
        } else {
            $institute_name = $request->get('institute');
        }
        if ($request->get('editor_city')) {
            $city = $request->get('editor_city');
        } else {
            $city = $request->get('city');
        }

        try {

            DB::beginTransaction();

            //----------------------Upload Profile Pic-------------------------------
            $image_path = 'ebm_pic/';
            $image_file_path = config('constants.admin.ebm_root_path') . $image_path;

            if ($request->hasfile('profile_pic')) {
                $image_file = $request->file('profile_pic');

                $file_name = $image_file->getClientOriginalName();
                $profile_pic_type = $image_file->getClientOriginalExtension();

                if (!is_dir($image_file_path)) {
                    mkdir($image_file_path, 0755, true);
                }
                $image_file->move($image_file_path, $file_name);
            } else {
                $file_name = "";
                $profile_pic_type = "";
            }

            //-------------------------Update Other Column-----------------------------
            $data = array(
                'fname'                 => $request->get('fname'),
                'mname'                 => $request->get('mname'),
                'lname'                 => $request->get('lname'),
                'degree'                => $request->get('degree'),
                'titles'                 => $request->get('titles'),
                'salutation'            => $request->get('salutation'),
                'suffix'                => $request->get('suffix'),
                'institute'             => $institute_name,
                'university'            => $request->get('university'),
                'pharmaceutical'        => $request->get('pharmaceutical'),
                'company'               => $request->get('company'),
                'department'            => $request->get('department'),
                'laboratory'            => $request->get('laboratory'),
                'library'               => $request->get('library'),
                'expertise'             => $request->get('expertise'),
                'h_index'               => $request->get('h_index'),
                'orcid_id'              => $request->get('orcid_id'),
                'researcher_id'         => $request->get('researcher_id'),
                'research_gate'         => $request->get('research_gate'),
                'google_scholar'        => $request->get('google_scholar'),
                'scopus_id'             => $request->get('scopus_id'),
                'address'               => $request->get('address'),
                'email'                 => $request->get('email'),
                'alt_email'             => $request->get('alt_email'),
                'zip_code'              => $request->get('zip_code'),
                'city'                  => $city,
                'state'                 => $request->get('state'),
                'country'               => $request->get('country'),
                'institution_id'        => $request->get('institution_id'),
                'phone'                 => $request->get('phone'),
                'mobile'                => $request->get('mobile'),
				'we_chat_number'        => $request->get('we_chat_number'),
                'fax'                   => $request->get('fax'),
                'url'                   => $request->get('url'),
                'profile_pic'           => $file_name,
                'profile_pic_type'      => $profile_pic_type,
                'web_format'            => $request->get('web_format'),
                'status'                => 'A',
                'added_by'              => Auth::user()->id,
                'created_on'            => now(),
            );
            $add_editor_id = EBM::AddEditor($data);
            $add_editor_history = EBM::AddEditorHistory($add_editor_id, "A");

            $add_log = array(
                'content_id'      => $add_editor_id,
                'content_type_id' => config('constants.log_content_types.EditorialBoardMember'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($data),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            $data['editor_id'] = $add_editor_id;
            $editor_add_verification = EBM::AddEditorVerification($data);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return  Redirect::back();
        }
        return redirect()->route('editorial_board_member.index')->with('success', 'Editor was added.');
    }

    public function show($id)
    {
    }

    public function edit($id)
    {
        $verification_id = request()->get('verification_id');
        session(['redirect_url' => url()->previous()]);

        $editor_city = "";
        $editor_institute_name = "";
        $editor = EBM::GetEditorbyID($id);
        $editor_institute = EBM::GetEditorInstituteName($id);
        if (!empty($editor_institute)) {
            $editor_city = $editor_institute->city;
            $editor_institute_name = $editor_institute->name;
        }
        $country_list = Country::GetCountryList();

        return view('admin.editorial_board_member.ebm_edit', ['country_list' => $country_list, 'editor' => $editor, 'editor_city' => $editor_city, 'editor_institute_name' => $editor_institute_name, 'verification_id' => $verification_id]);
    }

    public function update(Request $request, $id)
    {
        if (!empty($request->get('verification_id'))) {
            $verification_id = $request->get('verification_id');
            $editor_request_delete = DB::table('tbl_editors_verification')->where('id', $verification_id)->delete();
        }

        $param['editor_id'] = $id;
        $param['verification_status'] = 'pending';
        $editor_data = EBM::GetVerificationEditorsList($param);

        if ($editor_data->count() == 0) {
            if ($request->get('institution_id')) {
                $institute = EBM::GetInstitutebyID($request->get('institution_id'));
                $institute_name = $institute->name;
            } else {
                $institute_name = $request->get('institute');
            }
            if ($request->get('editor_city')) {
                $city = $request->get('editor_city');
                $request->merge(['city' => $city]);
            } else {
                $city = $request->get('city');
            }

            try {

                DB::beginTransaction();

                //----------------------Upload Profile Pic-------------------------------
                $editor = EBM::GetEditorbyID($id);
                $editorArray = (array) $editor;
                $changedAttributes = '';

                $file_name   = $editor->profile_pic;
                $profile_pic_type   = $editor->profile_pic_type;

                $image_path = 'ebm_pic/';
                $image_file_path = config('constants.admin.ebm_root_path') . $image_path;

                if ($request->hasfile('profile_pic')) {
                    $image_file = $request->file('profile_pic');

                    $file_name = $image_file->getClientOriginalName();
                    $profile_pic_type = $image_file->getClientOriginalExtension();

                    if (!is_dir($image_file_path)) {
                        mkdir($image_file_path, 0755, true);
                    }
                    $image_file->move($image_file_path, $file_name);

                    $data['profile_pic'] = $file_name;
                    $data['profile_pic_type'] = $profile_pic_type;
                    $changedAttributes .= 'profile_pic,profile_pic_type,';
                }

                $requestData = $request->except(['_method', '_token', '_wysihtml5_mode', 'editor_city', 'profile_pic', 'verification_id']);

                foreach ($requestData as $attribute => $value) {

                    if (trim($request->input($attribute)) != trim($editorArray[$attribute])) {

                        $data[$attribute] = $request->input($attribute);
                        $changedAttributes .= $attribute . ',';
                    }
                }

                if (strpos($changedAttributes, 'fname') === false) {
                    $data['fname']  = $editor->fname;
                }
                if (strpos($changedAttributes, 'mname') === false) {
                    $data['mname']  = $editor->mname;
                }
                if (strpos($changedAttributes, 'lname') === false) {
                    $data['lname']  = $editor->lname;
                }
                if (strpos($changedAttributes, 'email') === false) {
                    $data['email'] = $editor->email;
                }

                $changedAttributes = rtrim($changedAttributes, ',');

                if (empty($changedAttributes)) {

                    return redirect()->route('editorial_board_member.index');
                } else {

                    // -------------------------Update Other Column-----------------------------
                    $data['editor_id']  = $id;
                    $data['created_on'] = now();
                    $data['added_by'] = Auth::user()->id;
                    $data['verification_comment']  = 'Edit Editor';
                    $data['verification_status']  = 'pending';
                    $data['editor_changes']  = $changedAttributes;

                    $editor_add = EBM::AddEditorVerification($data);
                }

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return  Redirect::back();
            }
            $redirectURL = session('redirect_url');
            return redirect($redirectURL)->with('success', 'Request for changes in editor has been send to verification department.');
        } else {
            $redirectURL = session('redirect_url');
            return redirect($redirectURL)->with('error', 'There is already pending request against this editor.');
        }
    }

    public function destroy(Request $request, $id)
    {
        $param['editor_id'] = $request->id;
        $param['verification_status'] = 'pending';
        $editor_data = EBM::GetVerificationEditorsList($param);

        if ($editor_data->count() == 0) {
            $data = EBM::GetEditorbyID($request->id);
            $data->created_on            = now();
            $data->added_by              = Auth::user()->id;
            $data->verification_comment  = 'Delete Editor';
            $data->verification_status   = 'pending';

            $arrayData = (array) $data;

            $arrayData['editor_delete_comment'] = $request->editor_delete_comment;
            $editor_add = EBM::AddEditorVerification($arrayData);

            return redirect()->route('editorial_board_member.index')->with('success', 'Request to delete editor has been send to verification department.');
        } else {
            return redirect()->route('editorial_board_member.index')->with('error', 'There is already pending request against this editor.');
        }
    }

    function generatecsv($ebm_report)
    {
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=ebm_report.csv");

        $r = 'Journal Title, Role, Conditional EBM, Executive Guest Editor,	Section Region, First Name, Middle Name, Last Name, Acceptance Date, Degree, Honours, Salutation, Suffix, Institute, Expertise, H-Index, Orcid ID, Researcher ID, Research Gate, Google Scholar, Scopus ID, University, Pharmaceutical, Department, Laboratory, Library, Company, Address, Zip code, City, State, Country, Phone, Fax, Mobile, Email, Alt Email, URL, Web Format, EBM Added On, EBM Added By';
        $r .= "\n";

        foreach ($ebm_report as $vals) {
            $r .= str_replace(',', ' ', $vals->title) . ',';
            $r .= $vals->nicename . ',';
            if ($vals->conditional_ebm == "Y") {
                $r .= "Yes" . ',';
            } else {
                $r .= "No" . ',';
            }
            if ($vals->executive_ge == "Y") {
                $r .= $vals->executive_ge . ',';
            } else {
                $r .= "No" . ',';
            }
            $r .= $vals->section_region . ',';
            $r .= $vals->fname . ',';
            $r .= $vals->mname . ',';
            $r .= $vals->lname . ',';
            $r .= $vals->acceptance_date . ',';
            $r .= str_replace(',', ' ', $vals->degree) . ',';
            $r .= str_replace(',', ' ', $vals->titles) . ',';
            $r .= $vals->salutation . ',';
            $r .= $vals->suffix . ',';
            $r .= str_replace(',', ' ', $vals->institute) . ',';
            $r .= preg_replace("/\r\n|\n\r|\n|\r/", " ", str_replace(',', ' ', $vals->expertise)) . ',';
            $r .= $vals->h_index . ',';
            $r .= $vals->orcid_id . ',';
            $r .= $vals->researcher_id . ',';
            $r .= $vals->research_gate . ',';
            $r .= $vals->google_scholar . ',';
            $r .= $vals->scopus_id . ',';
            $r .= str_replace(',', ' ', $vals->university) . ',';
            $r .= str_replace(',', ' ', $vals->pharmaceutical) . ',';
            $r .= str_replace(',', ' ', $vals->department) . ',';
            $r .= str_replace(',', ' ', $vals->laboratory) . ',';
            $r .= str_replace(',', ' ', $vals->library) . ',';
            $r .= str_replace(',', ' ', $vals->company) . ',';
            $r .= preg_replace("/\r\n|\n\r|\n|\r/", " ", str_replace(',', ' ', $vals->address)) . ',';
            $r .= $vals->zip_code . ',';
            $r .= str_replace(',', ' ', $vals->city) . ',';
            $r .= str_replace(',', ' ', $vals->state) . ',';
            $r .= str_replace(',', ' ', $vals->country) . ',';
            $r .= preg_replace("/\r\n|\n\r|\n|\r|\t/", " ", str_replace(',', ' ', $vals->phone)) . ',';
            $r .= $vals->fax . ',';
            $r .= $vals->mobile . ',';
            $r .= $vals->email . ',';
            $r .= str_replace(',', ' ', $vals->alt_email) . ',';
            $r .= str_replace(',', ' ', $vals->url) . ',';
            $r .=  preg_replace("/\r\n|\n\r|\n|\r/", " ", str_replace(',', ' ', strip_tags($vals->web_format))) . ',';
            $r .= $vals->ebm_added_on . ',';
            $r .= $vals->ebm_added_by . ',';
            $r .= "\n";
        }
        echo $r;
        die;
    }

    public function GetCountryCity($country_name, $city_name = '')
    {
        $country_name = str_replace('_', ' ', $country_name);
        $output = '';
        if ($country_name) {

            $city = EBM::GetCityList($country_name);
            $selected = '';
            $output .= '<option value="" >Select City</option>';
            foreach ($city as $row) {
                $country_city = str_replace(' ', '_', $row->city);
                if ($country_city == urldecode($city_name) && !empty($city_name)) {
                    $selected = ' selected ';
                }
                $output .= '<option value="' . urlencode($country_city) . '" ' . $selected . '>' . $row->city . '</option>';
                $selected = '';
            }
            return  response()->json(array('output' => $output));
        }
    }

    public function GetCityInstitute($country_name, $city_name = '', $institution_name = '')
    {
        $country_name = str_replace('_', ' ', $country_name);
        $city_name = urldecode(str_replace('_', ' ', $city_name));
        $selected = '';
        $output = '';
        $output .= '<option value="" >Select Institute</option>';
        if ($city_name && $country_name) {
            $institute = EBM::GetInstituteList($country_name, $city_name);
            foreach ($institute as $row) {
                if ($row->name == $institution_name && !empty($institution_name)) {
                    $selected = ' selected ';
                }
                $output .= '<option value="' . $row->institution_id . '" ' . $selected . '>' . $row->name . '</option>';
                $selected = '';
            }
            return  response()->json(array('output' => $output));
        }
    }
}
