<?php

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\Author;
use App\Models\Journal;
use App\Models\Subject;
use App\Models\Manuscript;
use App\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use DB;

class CallForPaperController extends BenthamController
{
    public function __construct()
    {
    }

    public function index(Request $request)
    {
		
    }

	public function GetCallForPapers(Request $request,$journal=null)
    {
		if($request->filter == true)
		{
			return $this->FilterJournals($request);
		}
		elseif(!empty($journal))
		{
			$request->search_journals = [strtoupper($journal)];
			return $this->GetIssueList($request);
		}
		else
		{
			return $this->GetIssueList($request);
		}
    }
	
	private function FilterJournals($request)
	{
		$data['filter']['journalwisecodes'] = [];
		$q = journal::where('journal_status',1);
		
		if(isset($request->action) && $request->action == 'search')
		{
			$where = '';
			if(isset($request->search_journals) && count($request->search_journals))
			{
				$where  = ' jms_jcode in ("'.implode('","',$request->search_journals).'") ';
				$data['filter']['journalwisecodes'] = $request->search_journals;				
			}
			
			if(isset($request->journal_filter) && !empty($request->journal_filter))
			{
				if(isset($request->search_journals) && count($request->search_journals) > 0)
				{
					$where .= ' OR (title like "%'.$request->journal_filter.'%" OR subtitle like "%'.$request->journal_filter.'%" OR jms_jcode like "%'.$request->journal_filter.'%")';
				}
				else
				{
					$where .= ' (title like "%'.$request->journal_filter.'%" OR subtitle like "%'.$request->journal_filter.'%" OR jms_jcode like "%'.$request->journal_filter.'%")';
				}
			}
			
			if($where != '')
			{
				$q = $q->whereRaw($where);	
			}
		}
		
		$jms_jcode =  array_filter($q->pluck('jms_jcode')->toArray());
		
		
		
		$data['journals'] = $this->GetJMSJournals($jms_jcode);
		//return view('callforpapers.section.journal_filter')->with($data);	
		
		return View::make("callforpapers.section.journal_filter")->with($data);	
	}
	
	private function GetIssueList($request)
	{
		$filter['journalwisecodes'] = [];
		$filter['subjectwisecodes'] = [];
		$filter['sdgswisecodes'] = [];
		
		$param['journal_group'] = true;
		$param['paginate'] = "all";
		$filter['sort'] = $param['sort'] = $request->sort?$request->sort:'mostRecent';	
		$page_name = "journal-listing";

		$jms_jcode = array_filter(journal::where('journal_status',1)->pluck('jms_jcode')->toArray());
		$journals = Self::SortByChecked($request,$this->GetJMSJournals($jms_jcode));

		if(isset($request->search_journals))
		{
			$filter['journalwisecodes'] = $param['journalwisecodes'] = $request->search_journals;
		}	

		if(isset($request->search_subjects))
		{
			$param['subjectwisecodes'] = DB::table('subject_journal as s')
			->join('journal as j','s.journal_id','j.journal_id')
			->whereIn('s.subject_id',$request->search_subjects)->pluck('jms_jcode');
			
			$filter['subjectwisecodes'] = $request->search_subjects;
		}	
		if(isset($request->search_sdgss))
		{
			$filter['sdgswisecodes'] = $param['sdgswisecodes'] = $request->search_sdgss;
		}	
		
		$param['paginate'] = 12;
		$param['journal_group'] = true;
		$param['sub_query'] = "(SELECT COUNT(ms.manuscript_id) FROM tbl_manuscript AS ms WHERE m.ht_code = ms.ht_code AND manuscript_type = 'm' AND STATUS = 'A'AND publish = 2) AS articles";

		$issue_list = Manuscript::SearchJMSJournalList($param);

		
		$j_code = [];
		foreach($issue_list as $issue)
		{
			if(!in_array($issue->subtitle,$j_code))
			{
				$j_code[] = $issue->subtitle;
			}
		}
		
		$scopus = DB::table('journal')->whereIn('jms_jcode',$j_code)->pluck('ScopusCiteScore','jms_jcode');
		$impactfactor = DB::table('journal')->whereIn('jms_jcode',$j_code)->pluck('org_impact_factor','jms_jcode');
		
		$subjects 	= $this->Getsubjects($jms_jcode,$filter,$param);
		$sdgs 		= $this->Getsdgs($jms_jcode,$filter,$param);

		$paging = '';
		if(count($issue_list) > 0)
		{
			$paging = (array) json_decode($issue_list->toJson());
		}
		
		if($request->ajax == true)
		{
			return view('callforpapers.specialissue-list',compact('page_name','filter','issue_list','journals','subjects','sdgs','paging','scopus','impactfactor'));
		}
		else
		{
			return view('callforpapers',compact('page_name','filter','issue_list','journals','subjects','sdgs','paging','scopus','impactfactor'));	
		}
	}


    public function GetCallForPapersDetail(Request $request)
    {
        $journal_search = "";
        $param['journal_group'] = false;
        $searchFormRoute = 'callforpapers';
        $param['journal_group'] = true;
        $param['paginate'] = "all";
        $data['jms_all_journal'] = $jms_all_journal = Manuscript::SearchJMSJournalList($param);
		
		if (isset($request->param)) 
		{
			if ($request->param == "journal") 
			{
				$param['subtitle'] = $subject = $request->id;
				if (isset($request->by_journal)) 
				{
					$param['subtitle'] = $subject = $request->by_journal;
				}

				$data['page_name'] = $page_name = "specialissue-list";
				$data['journal'] = $journal = Journal::where('subtitle', $subject)->first();
			}

			if ($request->param == "specialissue") 
			{
				$param['htcode'] = $request->id;
				$data['page_name'] = $page_name = "specialissue-detail";
				$data['searchFormRoute'] = $searchFormRoute = 'callforpapers-detail';
				$param['paginate'] = false;
				
				//=============Published Article=================
				$data['article_list'] = $this->GetPublishedArticles(Manuscript::SearchHTArticleList($param));
				
				//=============Inprocess Article=================
				$data['jms_inp_article'] = $this->GetInProcessArticles(Manuscript::InpHTArticleList($param));
			}
		}
	
		if ($request->param == "specialissue") 
		{
			$journal_title = Manuscript::GetJournalByHtCode($request->id);
			$data['journal'] = $journal = Journal::GetJournalByJMSCode($journal_title->journal_code);
			//echo 1; return ;
			$param['paginate'] = false;
			$param['journal_group'] = false;

			$data['jms_journal'] = $jms_journal = Manuscript::SearchJMSJournalList($param);
			$data['sub_topics'] = $sub_topics = Manuscript::GetSubTopicsbyManuscriptId($jms_journal->manuscript_id);

		} 
		else 
		{
			$param['journal_group'] = false;
			$param['paginate'] = 12;
			$data['jms_journal'] = $jms_journal = Manuscript::SearchJMSJournalList($param);
		}

		foreach(Article::GettAllContinuePublicationJournal() as $val)
		{
			$data['continues_publication_journal'][] = $val->subtitle;
		}
	
		//$data['subject'] = $this->GetSubjcets();
		
        return view($searchFormRoute,with($data));
    }
	
	private function GetPublishedArticles($jms_article)
	{
		$article_list = [];
		
		if (!empty($jms_article)) 
		{
			foreach ($jms_article as $manuscript_list) 
			{
				if (!empty($manuscript_list->reference_number)) 
				{
					$reference_number_list[] = $manuscript_list->reference_number;
				}
			}
			
			if (!empty($reference_number_list)) 
			{

				$article_list = Manuscript::GetArticlebyJMSRefNumber($reference_number_list, 20);

				if ($article_list->count() > 0) {
					// $article_list = $this->CheckUserAccessonArticle($article_list);
					$b = 0;

					if (count($article_list) > 0) {
						foreach ($article_list as $key => $value) {
							$AuthorNames     = '';
							$article_authors = Author::GetAuthorsByContentId($value->article_id, 'article_id');
							if (!empty($article_authors)) {
								foreach ($article_authors as $author) {
									if ($author->is_principle == 1) {
										$AuthorNames .= $author->authors . '*' . ',  ';
									} else {
										$AuthorNames .= $author->authors . ',  ';
									}
								}
								$AuthorNames = rtrim($AuthorNames, ', ');
							}
							$pos = strrpos($AuthorNames, ",");
							if ($pos) {
								$str         = substr($AuthorNames, 0, $pos);
								$str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
								$AuthorNames = $str . " and " . $str2;
							}
							$article_list[$b]->authors = $AuthorNames;
							$b++;
						}
					}
				}
			}
		}
		
		return $article_list;
	}
	
	private function GetInProcessArticles($jms_inp_article)
	{
		if (!empty($jms_inp_article)) 
		{
			$b = 0;

			if (count($jms_inp_article) > 0) {
				foreach ($jms_inp_article as $key => $value) {
					$AuthorNames     = '';
					$article_authors = Manuscript::GetJMSAuthorsByContentId($value->manuscript_id, 'manuscript_id');
					if (!empty($article_authors)) {
						foreach ($article_authors as $author) {
							if ($author->is_principal == 1) {
								$AuthorNames .= $author->authors . '*' . ',  ';
							} else {
								$AuthorNames .= $author->authors . ',  ';
							}
						}
						$AuthorNames = rtrim($AuthorNames, ', ');
					}
					$pos = strrpos($AuthorNames, ",");
					if ($pos) {
						$str         = substr($AuthorNames, 0, $pos);
						$str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
						$AuthorNames = $str . " and " . $str2;
					}
					$jms_inp_article[$b]->authors = $AuthorNames;
					$b++;
				}
			}
			// dd($jms_inp_article);
		}
		
		return $jms_inp_article;
	}
	
	// private function GetSubjcets()
	// {
	// 	$temp = rtrim(Subject::display_parent(), '_');
	// 	$option = explode('_', $temp);
	// 	$subject = array();
	// 	if ($temp != '') 
	// 	{
	// 		//disease=1_diabetes=2_
	// 		foreach ($option as $pair) 
	// 		{
	// 			list($name, $id) = explode('=', $pair);
	// 			if ($id != '') 
	// 			{
	// 				$subject[0] = 'Please Select';
	// 				$subject[$id] = $name;
	// 			}
	// 		}
	// 	}
	// 	else 
	// 	{
    //         $subject[0] = 'Please Select';
    //     }		
		
	// 	return $subject;
	// }

	private function Getsubjects($jms_jcode,$filter,$param)
	{
		$subjects = DB::table('subject as s')->select('s.subject_id','s.title','j.subtitle');
		$subjects = $subjects->join('subject_journal as sj','s.subject_id','sj.subject_id');
		$subjects = $subjects->join('journal as j','sj.journal_id','j.journal_id');
		
		if(!empty($filter['journalwisecodes']))
		{
			$subjects = $subjects->whereIn('j.subtitle',$filter['journalwisecodes']);
		}
		elseif(!empty($filter['subjectwisecodes']))
		{
			$subjects = $subjects->whereIn('j.subtitle',$param['subjectwisecodes']);
		}
		elseif(!empty($filter['sdgswisecodes']))
		{
			$subjects = $subjects->whereIn('j.subtitle',$param['sdgswisecodes']);
		}
		else
		{
			$subjects = $subjects->whereIn('j.subtitle',$jms_jcode);	
		}
		
		return $subjects->where('parent_id','<>',0)->groupBy('s.subject_id')->orderBy('s.title')->get();
	}

	private function Getsdgs($jms_jcode,$filter,$param)
	{
		$sdgs = DB::table('sdgs as s')->select('s.sdgs_id','s.title','j.subtitle');
		$sdgs = $sdgs->join('sdgs_journal as sj','sj.sdgs_id','s.sdgs_id');
		$sdgs = $sdgs->join('journal as j','sj.journal_id','j.journal_id');
		
		if(!empty($filter['journalwisecodes']))
		{
			$sdgs = $sdgs->whereIn('j.subtitle',$filter['journalwisecodes']);
		}
		elseif(!empty($filter['subjectwisecodes']))
		{
			$sdgs = $sdgs->whereIn('j.subtitle',$param['subjectwisecodes']);
		}
		elseif(!empty($filter['sdgswisecodes']))
		{
			$sdgs = $sdgs->whereIn('j.subtitle',$param['sdgswisecodes']);
		}
		else
		{
			$sdgs = $sdgs->whereIn('j.subtitle',$jms_jcode);	
		}
		
		return $sdgs->groupBy('s.sdgs_id')->orderBy('s.sequence_no')->get();
	}

	private function GetJMSJournals($jms_jcode)
	{
		return DB::connection('jms')->table('tbl_manuscript as m')
		->select('j.journal_code as subtitle','j.journal_title as title')
		->join('tbl_eic_initial_scopic_log as l', 'l.manuscript_id', '=', 'm.manuscript_id')
		->join('tbl_journals as j', 'j.journal_id', '=', 'm.journal_id')
		->where(['j.status'=>'A','m.manuscript_type'=>'P'])
		->whereRaw(' (j.journal_type = "S" OR j.journal_code in ("CIS","CSS","CMIM","CMP","TOOPHTJ","TODENTJ","TOCIEJ","TOBEJ","CDR","ENG","TOTJ","EMIDDT","CTM","TOMICROJ")) ')
		->whereIn('journal_code',$jms_jcode)
		->where('journal_code','<>','TJL')
		->groupBy('j.journal_id')->orderBy('j.journal_title', 'ASC')->get();
		
	}

	public function OrderInquiry(Request $request, $id)
	{
		$q = DB::connection('jms')->table('tbl_manuscript as m')->select('*');
		$q = $q->selectRaw(' CASE WHEN (m.proposal_closing_date <> 0 AND TO_DAYS(FROM_UNIXTIME(m.proposal_closing_date)) <= TO_DAYS(NOW())) THEN "closed" END AS status ');
		$q = $q->selectRaw(' CASE WHEN (m.proposal_closing_date <> 0 AND TO_DAYS(FROM_UNIXTIME(m.proposal_closing_date)) >= TO_DAYS(NOW())) THEN "open" END AS status ');
		$q = $q->join('tbl_journals as j','j.journal_id','m.journal_id');
		$q = $q->where('m.manuscript_id',$id);
		$issue = $q->first();
		
		$success = null;
		if(isset($request->submit))
		{
			
			$this->validate(
				  $request,[
                    "first_name"  => "required",
                    'last_name'             => "required",
                    'email'                 => "required|email",
					'user_category'          => "required",
					'country'                 => "required",
					'city'                 => "required",
					'address'                 => "required",
					'comments'                 => "required",
                    'captcha'               => 'required|captcha'
                ], ['captcha.captcha' => 'Invalid captcha code.']
			);
			
			$data['first_name'] = $request->first_name;
			$data['last_name'] = $request->last_name;
			$data['email'] = $request->email;
			$data['user_category'] = $request->user_category;
			$data['country'] = $request->country;
			$data['city'] = $request->city;
			$data['address'] = $request->address;
			$data['comments'] = $request->comments;
			
			DB::table('order_inquiry')->insert($data);
			
			$data['title'] = $issue->title;
			$data['proposal_closing_date'] = $issue->proposal_closing_date;
			$data['status'] = $issue->status;
			
			$to   = 'armash@xolva.com'; // faizan@benthamscience.net
			$from = 'support@benthamscience.net';
			$cc   = 'arsal@xolva.com';
			$bcc = 'arsal@xolva.com';
			
			if(isset($issue->status) && $issue->status == 'open')
			{
				$subject = 'Call For Paper :: Pre-Order';
			}
			else	
			{
				$subject = 'Call For Paper :: Purchase';
			}

			SendSmtpMail('email_template.order_inquiry',$data, $to, $from, $subject, 'Admin', $cc, $bcc);
			
			$success = 'Your order inqury has been successfully submitted, we will contact you soon';
		}
		
		
		$countries = Country::GetCountryList();
		$page_name = 'order_inquiry';
		return view('callforpapers',compact('page_name','issue','countries','success'));
	}

	public function SortByChecked($request,$journals)
	{
		foreach($journals as $k => $j)
		{
			if(is_array($request->search_journals) && in_array($j->subtitle,$request->search_journals))
			{
				$journals[$k]->check = 1;
			}
		}
		$journals =  $journals->sortByDesc('check');
		return $journals;
	}
}
