<?php

namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Author;

class CrossRef extends BenthamController
{
	public function GetCrossRefFunderList($article_id)
    {
		$str_funder = '';
		$funder_list = Article::GetArticleFunderDetail($article_id,'article_id');
		$funder_list_exist = count($funder_list);
		$str_funder .="<fr:program name='fundref'>\r\n";
		if(!empty($funder_list_exist))
		{
			
		
			foreach($funder_list as $key => $funder_row)
			{
				
				$str_funder .=	"<fr:assertion name='fundgroup'>";
				
					$str_funder .="<fr:assertion name='funder_name'>".$funder_row->funder_name."\r\n";
					$str_funder .="<fr:assertion name='funder_identifier'>".$funder_row->funder_registry_ids."</fr:assertion>\r\n";
				$str_funder .="</fr:assertion>\r\n";
				
				$funding_award_numbers_data = explode(",",$funder_row->award_number);
				
				for($aw=0;$aw<count($funding_award_numbers_data);$aw++)
				{
					$str_funder .="<fr:assertion name='award_number'>".$funding_award_numbers_data[$aw]."</fr:assertion>\r\n";
				}
				
				$str_funder .=	"</fr:assertion>\r\n";
			}
			
			
		}
		$str_funder .="</fr:program>\r\n";
			
		return $str_funder;
	}
	
	public function GetCrossRefAbstract($article_id)
    {
		$abs = '';
		
		$abstract_fields = Article::GetArticleAbstractDetail($article_id,'article_id');
		
		$abs .= "<jats:abstract>\r\n";

		if (!empty($abstract_fields))
		{
			
			
			foreach($abstract_fields as $kay => $val)
			{
				$abs .= "<jats:sec>\r\n";
				$abs .= "<jats:title>".$val->field_name.":</jats:title>\r\n";
				$abs .= "<jats:p>".$this->ConvertToEntityNumber($val->field_description)."</jats:p>\r\n";
				$abs .= "</jats:sec>\r\n";
			}
		}
		else
		{
			$article_abstract = Article::where('article_id',$article_id)->first();
			if (!empty($article_abstract))
			{
				$abs .= "<jats:sec>\r\n";
				$abs .= "<jats:title></jats:title>\r\n";
				$abs .= "<jats:p>".$this->ConvertToEntityNumber($article_abstract->abstract)."</jats:p>\r\n";
				$abs .= "</jats:sec>\r\n";	
			}
			
		}
		
		$abs .= "</jats:abstract>\r\n";	
		
		return $abs;
	}
	

    public function GetCrossRef($result)
    {
        $publication_journal = Article::GettAllContinuePublicationJournal();
        foreach($publication_journal as $publication_journals){
            $continues_publication_journal[] = $publication_journals->subtitle;
        }
		
        $str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
	$str .= "<doi_batch xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.crossref.org/schema/4.4.0\" xmlns:fr=\"http://www.crossref.org/fundref.xsd\" xmlns:ct=\"http://www.crossref.org/clinicaltrials.xsd\" xmlns:ai=\"http://www.crossref.org/AccessIndicators.xsd\" xmlns:rel=\"http://www.crossref.org/relations.xsd\" xmlns:jats=\"http://www.ncbi.nlm.nih.gov/JATS1\" version=\"4.4.0\" xsi:schemaLocation=\"http://www.crossref.org/schema/4.4.0 crossref4.4.0.xsd\">\r\n";

        $batch = date("Y-m-d") . "_crossref_eureka_live_final_first_all";
        //print("Date = ".strftime("%Y-%m-%d-%H",strtotime(date("Y-m-d-H")))."<br>"); exit;
        $current_timestamp = date("YmdHis0000", time());
        //print("Date = ".$current_timestamp); exit;
        $str .= "<head>\r\n";
        $str .= "<doi_batch_id>" . $batch . "</doi_batch_id>\r\n";
        $str .= "<timestamp>" . $current_timestamp . "</timestamp>\r\n";
        $str .= "<depositor>\r\n";
        $str .= "<depositor_name>Bentham Science Publishers Ltd.</depositor_name>\r\n";
        $str .= "<email_address>zafar@benthamscience.net</email_address>\r\n";
        $str .= "</depositor>\r\n";
        $str .= "<registrant>BENTHAM SCIENCE PUBLISHERS</registrant>\r\n";
        $str .= "</head>\r\n";
        $str .= "\r\n<body>\r\n";
		
		if (!empty($result))
		{
			foreach ($result as $row) 
			{
				$journal           = $this->ConvertToEntityNumber($row->jour_title);
				$journal_sub_title = $row->subtitle;
				$issn              = str_replace("-", "", $row->issn);
				$volume            = $row->vol_name;
				$year              = $row->year;
				$issue             = $row->issue_name;
				$art_title         = $this->ConvertToEntityNumber($row->art_title);
				$art_file_name     = $row->file_name;

				if ($row->publication_date == 0) {

					$day    = strftime("%d", strtotime($row->art_cd));
					$month  = strftime("%m", strtotime($row->art_cd));
					$year   = strftime("%Y", strtotime($row->art_cd));
					$art_cd = $month . "/" . $year;

				} else {

					$day    = strftime("%d", $row->publication_date);
					$month  = strftime("%m", $row->publication_date);
					$year   = strftime("%Y", $row->publication_date);
					$art_cd = $month . "/" . $year;

				}

				//print("pub date = ".$row->publication_date." = ".$day."/".$month."/".$year); exit;
				$str .= "<journal>\r\n";
				$str .= "<journal_metadata language='en'>\r\n";
				$str .= "<full_title>" . $journal . "</full_title>\r\n";
				$str .= "<abbrev_title>" . $journal_sub_title . "</abbrev_title>\r\n";
				$str .= "<issn media_type='print'>" . $issn . "</issn>\r\n";
				$str .= "</journal_metadata>\r\n";
				$str .= "<journal_issue>\r\n";
				$str .= "<publication_date media_type='print'>\r\n";
				$str .= "<month>" . $month . "</month>\r\n";
				$str .= "<day>" . $day . "</day>\r\n";
				$str .= "<year>" . $year . "</year>\r\n";
				$str .= "</publication_date>\r\n";
				$str .= "<journal_volume>\r\n";
				$str .= "<volume>" . $volume . "</volume>\r\n";
				$str .= "</journal_volume>\r\n";
				$str .= "<issue>" . $issue . "</issue>\r\n";
				$str .= "</journal_issue>\r\n";

				$str .= "<journal_article publication_type=\"full_text\">\r\n";
				$str .= "<titles>\r\n";
				$str .= "<title>" . trim($art_title) . "</title>\r\n";
				$str .= "</titles>\r\n";

				$result_authors = Author::getAuthorDataById($row->article_id, 'article_id');

				$author = "";
				$auth   = "1";

				$str .= "<contributors>\r\n";
				//print(count(db_fetch_object($result_authors))); exit;

				$count = "0";
				foreach ($result_authors as $author_array) {

					$count = "1";
	                if ($auth == "1") 
	                //if ($author_array->is_principle == "1") 
					{
						$seq = "first";
					} else {
						$seq = "additional";
					}

					$author .= "<person_name sequence='" . $seq . "' contributor_role='author'>\r\n";

					if ($author_array->first_name == "") {
						$author .= "<given_name></given_name>\r\n";
					} else
					if ($author_array->initials != "") {
						$author .= "<given_name>" . trim($author_array->first_name) . " " . trim($author_array->initials) . "</given_name>\r\n";
					} else {
						$author .= "<given_name>" . trim($author_array->first_name) . "</given_name>\r\n";
					}

					$author .= "<surname>" . $author_array->last_name . "</surname>\r\n";
					if ($author_array->country == '0') {
						$author_array->country = "";
					} else {}

		              $auth_aff=explode('|', $this->getAffiliationPattern($author_array->web_view));
					
		              if(count($auth_aff) > 0)
		              { 
		                for($a=0;$a<sizeof($auth_aff);$a++)
		                {
		                  if(trim($auth_aff[$a]) != "")
		                  {
	                        $author .= "<affiliation><![CDATA[".$auth_aff[$a]."]]></affiliation>\r\n";
		                  }
		                }
		              }

					if($author_array->orcid!=""){
						$author .= "<ORCID authenticated='true'>https://orcid.org/".$author_array->orcid."</ORCID>\r\n";
					}

					$author .= "</person_name>\r\n";

					$auth = 2;

				}

				if ($count == "0") {

					$author .= "<person_name sequence='first' contributor_role='author'>\r\n";
					$author .= "<given_name></given_name>\r\n";
					$author .= "<surname></surname>\r\n";
					$author .= "</person_name>\r\n";
				}

				$str .= $author . "</contributors>\r\n";
				
				$str .= $this->GetCrossRefAbstract($row->article_id);

				$str .= "<publication_date>\r\n";
				$str .= "<month>" . $month . "</month>\r\n";
				$str .= "<day>" . $day . "</day>\r\n";
				$str .= "<year>" . $year . "</year>\r\n";
				$str .= "</publication_date>\r\n";


				if(in_array(strtoupper($journal_sub_title), $continues_publication_journal) && $row->elocator != '')
				{
					$str .= "<publisher_item>\r\n";
					$str .= "<item_number item_number_type='article_number'>" . $row->elocator . "</item_number>\r\n";
					$str .= "<identifier id_type='sici'>LiveAll1</identifier>\r\n";
					$str .= "</publisher_item>\r\n";

				}
				else
				{
					$str .= "<pages>\r\n";
					$str .= "<first_page>" . $row->first_page . "</first_page>\r\n";
					$str .= "<last_page>" . $row->last_page . "</last_page>\r\n";
					$str .= "</pages>\r\n";
					$str .= "<publisher_item>\r\n";
					$str .= "<identifier id_type='sici'>LiveAll1</identifier>\r\n";
					$str .= "</publisher_item>\r\n";
				}

				$str .="<crossmark>\r\n";
				$str .="<crossmark_version>1</crossmark_version>\r\n";
				$str .="<crossmark_policy>10.2174/BSP_crossmark_policy</crossmark_policy>\r\n";
				$str .="<crossmark_domains>\r\n";		
				$str .="<crossmark_domain>\r\n";
				$str .="<domain>eurekaselect.com</domain>\r\n";
				$str .="</crossmark_domain>\r\n";
				$str .="</crossmark_domains>\r\n";
				$str .="<crossmark_domain_exclusive>true</crossmark_domain_exclusive>\r\n";
				$str .="<custom_metadata>\r\n";
				$str .="<assertion name='review_status' label='Review Status' group_name='peer_review_details' group_label='Peer Review Details' order='0'>Peer Reviewed</assertion>\r\n";
				$str .="<assertion name='review_process' label='Review Process' group_name='peer_review_details' group_label='Peer Review Details' order='1'>Single blind</assertion>\r\n";
				$str .="<assertion name='screening_status' label='Screening Status' group_name='plagiarism_screening' group_label='Plagiarism Screening' order='0'>Checked with iThenticate</assertion>\r\n";
				// <!-- article date -->

				//check if receive date is not empty 	
				if (strtotime($row->receivedate)!='0000-00-00') {
					$str .="<assertion name='received' label='Received' group_name='publication_history' group_label='Publication History' order='0'>". $row->receivedate ."</assertion>\r\n";	
				}

				if (strtotime($row->revisedate)!='0000-00-00') {
						$str .="<assertion name='revised' label='Revised' group_name='publication_history' group_label='Publication History' order='1'>". $row->revisedate ."</assertion>\r\n";	
				}
				if (strtotime($row->acceptdate)!='0000-00-00') {
					$str .="<assertion name='accepted' label='Accepted' group_name='publication_history' group_label='Publication History' order='2'>". $row->acceptdate ."</assertion>\r\n";	
				}
				// <!-- issue date -->
				if (!empty($row->publication_date)) {
						$str .="<assertion name='published' label='Published' group_name='publication_history' group_label='Publication History' order='3'>". date('Y-m-d',$row->publication_date) ."</assertion>\r\n";	
				}

				$str .= $this->GetCrossRefFunderList($row->article_id);

				$str .="<ai:program name='AccessIndicators'>\r\n";
				$str .="<ai:license_ref>".$row->license_urls."</ai:license_ref>\r\n";
				$str .="</ai:program>";
				$str .="</custom_metadata>\r\n";
				$str .="</crossmark>\r\n";

				$str .= "<doi_data>\r\n";
				$str .= "<doi>" . $row->doi . "</doi>\r\n";
				//print($str); exit;
				$url = "https://www.eurekaselect.com";

				//$open_url = $url."/openurl/content.php?genre=article&";

				$param = "issn=" . $row->issn . "&volume=" . $volume . "&issue=" . $issue . "&spage=" . $row->first_page;

				//For Normal Url
				$article_url = $url . "/" . $row->article_node . "/article";

				//For Open URL
				//$article_url = $open_url.$param;
				$article_url = $article_url;

				$direct_download_url = "https://www.eurekaselect.com/article/download?doi=".$row->doi;

				$str .= "<resource>" . $this->ConvertToEntityNumber($article_url) . "</resource>\r\n";
				// $str .= "<collection property=\"list-based\" multi-resolution=\"unlock\" />\r\n";

				$str .= "<collection property=\"crawler-based\">";		
				$str .= "<item crawler=\"google\">";
				$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
				$str .= "</item>\r\n";
				$str .= "<item crawler=\"msn\">";
				$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
				$str .= "</item>\r\n";
				$str .= "<item crawler=\"altavista\">";
				$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
				$str .= "</item>\r\n";
				$str .= "<item crawler=\"yahoo\">";
				$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
				$str .= "</item>\r\n";
				$str .= "<item crawler=\"scirus\">";
				$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
				$str .= "</item>\r\n";
				$str .= "<item crawler=\"iParadigms\">";
				$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
				$str .= "</item>\r\n";
				$str .= "</collection>\r\n";

				$str .= "<collection property=\"text-mining\">";		
				$str .= "<item>";
				$str .= "<resource mime_type=\"application/pdf\">".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
				$str .= "</item>\r\n";
				$str .= "<item>";
				$str .= "<resource mime_type=\"text/html\">".$this->ConvertToEntityNumber($article_url)."</resource>\r\n";
				$str .= "</item>\r\n";				
				$str .= "</collection>\r\n";

				$str .= "</doi_data>\r\n";

				$result_citation = Article::getArticleCitationData($row->article_id);
				if($result_citation){		
					foreach($result_citation as $row_citation ) {						
						if($row_citation->cite_for=='open_references_crossref'){
							$str .="<citation_list>".$this->ConvertToEntityNumber($row_citation->citation_data)."</citation_list>";
						}
					}
				}

				$str .= "</journal_article>\r\n";
				$str .= "</journal>\r\n";

			}

			$str .= "</body>\r\n";
			$str .= "</doi_batch>\r\n";

			date_default_timezone_set("Asia/Karachi");
			$filename = "Bentham_Journal_" . strtoupper($journal_sub_title) . "_Vol" . intval($volume) . "_Iss" . intval($issue) . "_" . date("Y-m-d_h-i-s") . ".xml";
			//print($filename); exit;
			//
			//return $str;

       header("Content-Type: application/xml");
			//print($str); exit;
       header('Content-Disposition: attachment; filename="' . $filename . '"');
			print($str);
			exit;
		
		}
		else
		{
			echo '<center>Record Not Found</center>';
		}

    }

    public function GetEpubAbstractCrossRefDOI($result) {
	
	
	$timestamp = date("YmdHis",time())."0000";
	//201310071415090000
	
	foreach ($result as $row) {
		
		//print_r($row); exit;
		$day = strftime("%d",$row->article_created);
		$month = strftime("%m",$row->article_created);
		$year = strftime("%Y",$row->article_created);
		$volume = $row->volume_name;
		$article_no = $row->article_no;
		$journal_subtitle = $row->subtitle;
		$article_abstract = strip_tags($row->abstract);
		
		
		if($volume < 10) $volume = "0".$volume;
	
		
		$str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
				<doi_batch xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.crossref.org/schema/4.4.0\" xmlns:fr=\"http://www.crossref.org/fundref.xsd\" xmlns:ct=\"http://www.crossref.org/clinicaltrials.xsd\" xmlns:ai=\"http://www.crossref.org/AccessIndicators.xsd\" xmlns:rel=\"http://www.crossref.org/relations.xsd\" xmlns:jats=\"https://www.ncbi.nlm.nih.gov/JATS1\" version=\"4.4.0\" xsi:schemaLocation=\"http://www.crossref.org/schema/4.4.0 crossref4.4.0.xsd\">
	
				<head>
					<doi_batch_id>".date("Y-m-d",time())."_crossref_eureka_live_final_first_all</doi_batch_id>
					<timestamp>".$timestamp." </timestamp>
					<depositor>
						<depositor_name>Bentham Science Publishers Ltd.</depositor_name>
						<email_address>zafar@benthamscience.net</email_address>
						</depositor>
							<registrant>BENTHAM SCIENCE PUBLISHERS</registrant>
				</head>
				<body>
					<journal>
						<journal_metadata language='en'>
							<full_title>".$this->ConvertToEntityNumber($row->journal_title)."</full_title>
							<abbrev_title>".$row->subtitle."</abbrev_title>
							<issn media_type='print'>".str_replace("-","",$row->issn)."</issn>
						</journal_metadata>
						<journal_issue>
							<publication_date media_type='print'>
								<month>".$month."</month>
								<day>".$day."</day>
								<year>".$year."</year>
							</publication_date>
							
							<journal_volume>
								<volume>".$volume."</volume>
							</journal_volume>
				
							
						</journal_issue>
	
						<journal_article publication_type=\"full_text\">
							<titles>
								<title>".$this->ConvertToEntityNumber($row->title)."</title>
							</titles> ";
							
				$result_authors = Author::getAuthorDataById($row->article_id, 'article_id');

				$author = "";
				$auth   = "1";

				$str .= "<contributors>\r\n";
				//print(count(db_fetch_object($result_authors))); exit;

				$count = "0";
				foreach ($result_authors as $author_array) {

					$count = "1";
					if ($auth == "1") {
						$seq = "first";
					} else {
						$seq = "additional";
					}

					$author .= "<person_name sequence='" . $seq . "' contributor_role='author'>\r\n";

					if ($author_array->first_name == "") {
						$author .= "<given_name></given_name>\r\n";
					} else
					if ($author_array->initials != "") {
						$author .= "<given_name>" . trim($author_array->first_name) . " " . trim($author_array->initials) . "</given_name>\r\n";
					} else {
						$author .= "<given_name>" . trim($author_array->first_name) . "</given_name>\r\n";
					}

					$author .= "<surname>" . $author_array->last_name . "</surname>\r\n";
					if ($author_array->country == '0') {
						$author_array->country = "";
					} 

					$author .= "<affiliation>".$this->getAffiliationPattern($author_array->web_view)."</affiliation>\r\n";

					if($author_array->orcid!=""){
						$author .= "<ORCID authenticated='true'>https://orcid.org/".$author_array->orcid."</ORCID>\r\n";
					}

					$author .= "</person_name>\r\n";

					$auth = 2;

				}

				if ($count == "0") {

					$author .= "<person_name sequence='first' contributor_role='author'>\r\n";
					$author .= "<given_name></given_name>\r\n";
					$author .= "<surname></surname>\r\n";
					$author .= "</person_name>\r\n";
				}

				$str .= $author . "</contributors>\r\n";
		
		
		$str .= $this->GetCrossRefAbstract($row->article_id);
							
	
		$str .= "<publication_date>
					<month>".$month."</month>
					<day>".$day."</day>
					<year>".$year."</year>
				</publication_date>
						
				
						
				<publisher_item>
					<identifier id_type='sici'>LiveAll1</identifier>
				</publisher_item>
						
				<doi_data>
							
					<doi>".$row->doi."</doi>";
		
		$url = "https://www.eurekaselect.com";
		
		$open_url = $url."/openurl/content.php?genre=article&";
		$param = "doi=".$row->doi;
		
		//For Normal Url
		//$article_url = $url."/".$row->article_node."/article";
		
		//For Open URL
		//$article_url = $open_url.$param;
		$article_url = $url."/".$row->nid."/article";
		$direct_download_url = "https://www.eurekaselect.com/article/download/" . $row->nid;
		$str .= "<resource>
					".$this->ConvertToEntityNumber($article_url)."
				</resource>";
			
			$str .= "<collection property=\"list-based\" multi-resolution=\"unlock\" />";
			$str .= "<collection property=\"crawler-based\">";		
			$str .= "<item crawler=\"google\">";
			$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
			$str .= "</item>\r\n";
			$str .= "<item crawler=\"msn\">";
			$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
			$str .= "</item>\r\n";
			$str .= "<item crawler=\"altavista\">";
			$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
			$str .= "</item>\r\n";
			$str .= "<item crawler=\"yahoo\">";
			$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
			$str .= "</item>\r\n";
			$str .= "<item crawler=\"scirus\">";
			$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
			$str .= "</item>\r\n";
			$str .= "<item crawler=\"iParadigms\">";
			$str .= "<resource>".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
			$str .= "</item>\r\n";
			$str .= "</collection>\r\n";

			$str .= "<collection property=\"text-mining\">";		
			$str .= "<item>";
			$str .= "<resource mime_type=\"application/pdf\">".$this->ConvertToEntityNumber($direct_download_url)."</resource>\r\n";
			$str .= "</item>\r\n";
			$str .= "<item>";
			$str .= "<resource mime_type=\"text/html\">".$this->ConvertToEntityNumber($article_url)."</resource>\r\n";
			$str .= "</item>\r\n";				
			$str .= "</collection>\r\n";


			$str .="</doi_data>
			</journal_article>
		</journal>
				
		</body>
				
		</doi_batch> ";
	
	} //while
	
	

	$filename = strtoupper($journal_subtitle)."_EPUB_Abstract_doi_file_".$article_no.".xml";
	//print($filename); exit;
	
	
	header("Content-Type: application/xml");
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	print($str);
	exit;
	

} //function
}
