<?php

namespace App\Http\Controllers;

use App\Models\Author;
use App\Models\Article;

class EpubAbstractCrossRefDOIMetaData extends BenthamController
{
	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 GetEpubAbstractCrossRefDOI($result)
    {

        date_default_timezone_set("Asia/Karachi");
        $timestamp = date("YmdHis", time()) . "0000";
        //201310071415090000

        if ($result) {

            $row = $result;
            $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;

            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=\"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\">

                    <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";
            if ($result_authors != '') {
            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 .= "<given_name>".trim($author_array[0])." ".trim($author_array[1])."</given_name>\r\n";

                $author .= "<surname>" . $author_array->last_name . "</surname>\r\n";
                $auth = 2;
                if ($author_array->country == '0') {
                    $author_array->country = "";
                } else {}
				
				$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";

            }
            }
            if ($count == "0") {

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

            $str .= $author;
            //$str .= "<affiliation>".$affiliation."</affiliation>\r\n";
            $str .= "</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?doi=".$row->doi;
            $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>";
            // check if cross references available
            $article_refernces = Article::GetArticleReferences($row->article_id);
            if ($article_refernces != '') 
            {
                foreach ($article_refernces as $reference) 
                {
                    if($reference->cite_for == "open_references_crossref")
                    {
                        $str .="\r\n".$reference->citation_data;
                    }
                }
            }

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

        } //while

        date_default_timezone_set("Asia/Karachi");

        $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;

    }

}
