<?php

namespace App\Http\Controllers;

use App\Models\Author;
use App\Models\Keywords;

class EbookOnix extends BenthamController
{

    public function GetOnix($result)
    {

        $current_timestamp = date("Ymd", time());

        $str = "<?xml version=\"1.0\"?>\r\n
                <!DOCTYPE ONIXMessage SYSTEM \"http://www.editeur.org/onix/2.1/reference/onix-international.dtd\">\r\n
                  <ONIXMessage refname=\"ONIXMessage\" shortname=\"ONIXmessage\" release=\"2.1\">
                  <Header refname=\"Header\" shortname=\"header\">
                      <SenderIdentifier refname=\"SenderIdentifier\" shortname=\"senderidentifier\">
                      <FromCompany refname=\"FromCompany\" shortname=\"m174\">Bentham Science Publishers Ltd.</FromCompany>
                      <AddresseeIdentifier refname=\"AddresseeIdentifier\" shortname=\"addresseeidentifier\">
                      <AddresseeIDType refname=\"AddresseeIDType\" shortname=\"m380\">02</AddresseeIDType>
                      </AddresseeIdentifier>
                      <MessageNumber refname=\"MessageNumber\" shortname=\"m180\">000420</MessageNumber>
                      <SentDate refname=\"SentDate\" shortname=\"m182\">" . $current_timestamp . "</SentDate>
                      <DefaultLanguageOfText refname=\"DefaultLanguageOfText\" shortname=\"m184\">eng</DefaultLanguageOfText>
                      <DefaultPriceTypeCode refname=\"DefaultPriceTypeCode\" shortname=\"m185\">01</DefaultPriceTypeCode>
                      <DefaultCurrencyCode refname=\"DefaultCurrencyCode\" shortname=\"m186\">USD</DefaultCurrencyCode>
                      </SenderIdentifier>
                  </Header> ";

        foreach ($result as $row) {

            $ebook_title  = $row->ebook_title;
            $ebook_doi    = $row->ebook_doi;
            $eisbn        = $row->eisbn;
            $isbn         = $row->isbn;
            $issn         = $row->issn;
            $volume       = $row->volume;
            $volume_id    = $row->volume_id;
            $volume_node  = $row->volume_nid;
            $volume_price = $row->ebook_price;
            $year         = $row->year;
            $pdate        = $row->publication_date;

            break;
        }

        $str .= "<Copyright>Bentham Science Publishers Ltd.</Copyright>
            <ProductForm refname=\"ProductForm\" shortname=\"b012\">DG</ProductForm>
            <RecordSourceName refname=\"RecordSourceName\" shortname=\"a197\">
            <TitleText textcase=\"00\" refname=\"TitleText\" shortname=\"b203\">" . $ebook_title . "</TitleText>
            <Subtitle textcase=\"00\" refname=\"Subtitle\" shortname=\"b029\"></Subtitle>
            </RecordSourceName>

            <Publication>
            ";

        //Get author data
        $result_authors = Author::getAuthorDataById($volume_id, 'ebook_volume_id');

        $count  = "0";
        $auth   = "1";
        $author = "";
        $editor = '';
        if ($result_authors) {
            foreach ($result_authors as $data) {

                $count = "1";

                switch ($data->iseditorcoeditor) {
                    case '0':
                        $editor = '';
                        break;
                    case 'a':
                        $editor = 'Author';
                        break;
                    case 'ca':
                        $editor = 'Co-Author';
                        break;
                    case 'e':
                        $editor = 'Editor';
                        break;
                    case 'ce':
                        $editor = 'Co-Editor';
                        break;
                    case 'ge':
                        $editor = 'Guest-Editor';
                        break;

                } //switch

                $author .= "<Contributor>
                            <ContributorRole>" . $editor . "</ContributorRole> ";

                if ($data->first_name == "") {
                    $author .= "<PersonName>Bentham Science Publisher</PersonName>\r\n";
                } else {
                    $author .= "<PersonName>" . $data->first_name . " " . $data->initials . " " . $data->last_name . "</PersonName>\r\n";
                }
				
				if (trim($data->author_affiliation) != '')
				{
					$affi = "<Affiliation><![CDATA[" . $data->web_view . "]]></Affiliation>";
				}
				else
				{
					$affi = "<Affiliation></Affiliation>";
				}

                $author .= " <PersonNameTitleDegree></PersonNameTitleDegree>
                            <ProfessionalAffiliation>";
							
				$author .= $affi;
				
                $author .= "</ProfessionalAffiliation></Contributor>";

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

            $author .= "<Contributor><ContributorRole></ContributorRole>\r\n";
            $author .= "<PersonName>Bentham Science Publisher</PersonName>\r\n";
            $author .= "<PersonNameTitleDegree></PersonNameTitleDegree>\r\n";
            $author .= "<ProfessionalAffiliation><Affiliation></Affiliation>\r\n";
            $author .= "</ProfessionalAffiliation></Contributor>";
        }

        $day   = strftime("%d", strtotime($pdate));
        $month = strftime("%B", strtotime($pdate));
        $year  = strftime("%Y", strtotime($pdate));

        //print($day); exit;

        $str .= $author;

        $str .= "<eISBN>" . $eisbn . "</eISBN>
            <ISBN>" . $isbn . "</ISBN>
            <Edition>1</Edition>
            <Series>
                <TitleText>" . $ebook_title . "</TitleText>
                <Volume>" . $volume . "</Volume>
                <ISSN>" . $issn . "</ISSN>
            </Series>";

        $str .= "<Publisher>
                <PublishingRole>Publisher</PublishingRole>
                <PublisherName>Bentham Science Publishers</PublisherName>
                <PublicationDate>" . $month . " " . $day . " ," . $year . "</PublicationDate>
            </Publisher>";

        $str .= "</Publication> ";

        foreach ($result as $row) {

            $chapter_id    = $row->chapter_id;
            $chapter_title = $row->title;
            $chapter_doi   = $row->chapter_doi;
            $first_page    = $row->first_page;
            $last_page     = $row->last_page;
            $pdate         = $row->publication_date;

            $str .= "<Record>
                    <Title refname=\"Title\" shortname=\"title\">
                      <TitleText textcase=\"00\" refname=\"TitleText\" shortname=\"b203\">" . $chapter_title . "</TitleText>
                      <Subtitle textcase=\"00\" refname=\"Subtitle\" shortname=\"b029\"></Subtitle>
                    </Title>
                        <UniqueRecordAccessionNumber>" . $chapter_doi . "</UniqueRecordAccessionNumber>
                        <Pages>
                            <FirstPage>" . $first_page . "</FirstPage>
                            <LastPage>" . $last_page . "</LastPage>
                        </Pages>";

            //Get author data

            $result_authors = Author::getAuthorDataById($chapter_id, 'chapter_id');

            $count  = "0";
            $auth   = "1";
            $author = "";

            $str .= " <Contributor refname=\"Contributor\" shortname=\"contributor\">";
            $str .= " <SequenceNumber refname=\"SequenceNumber\" shortname=\"b034\">1</SequenceNumber>
                      <ContributorRole refname=\"ContributorRole\" shortname=\"b035\">00</ContributorRole>";

            $author = "";
            if ($result_authors) {
                foreach ($result_authors as $author_array) {
                    $author .= "<PersonName refname=\"PersonName\" shortname=\"b036\">" . $author_array->first_name . " " . $author_array->last_name . "</PersonName>
                                <PersonNameTitleDegree></PersonNameTitleDegree>";

                }

                $affiliation = "<ProfessionalAffiliation refname=\"ProfessionalAffiliation\" shortname=\"professionalaffiliation\">
                        <Affiliation refname=\"Affiliation\" shortname=\"b046\">" . $this->getAffiliationPattern($author_array->web_view) ."</Affiliation>
                        </ProfessionalAffiliation>  ";

                $str .= $author . $affiliation . "</Contributor>";
            }
            $str .= " <Abstract>
                    <Text refname=\"Text\" shortname=\"d104\">" . $row->abstract . "</Text>
                    <Notes></Notes>
                </Abstract>";

            //Open URL
            $chapter_open_url = "http://www.eurekaselect.com/openurl/content.php?genre=book&isbn=$eisbn&spage=$first_page";

            // Normal URL
            $chapter_url = "http://www.eurekaselect.com/node/" . $row->chapter_nid;

            $keyword         = "";
            $result_keywords = Keywords::getKeywordDataById($chapter_id, 'chapter_id');

            if ($result_keywords) {
                foreach ($result_keywords as $data) {
                    $keyword .= "<keywords><![CDATA[" . $data->keyword . "]]></keywords>\r\n";
                } //foreach keyword
            }else{

                $keyword .= "<keywords><![CDATA[]]></keywords>\r\n";
            }

            $str .= $keyword;

            $str .= "<Link><![CDATA[" . $chapter_open_url . "]]></Link>";

            $str .= "</Record>";
        }

        $str .= "</ONIXMessage>";

        $filename = $ebook_title . ".xml";

        header('Cache-Control: must-revalidate');
        header("Content-Type: application/xml");
        //print($str); exit;
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        print($str);exit;

    }

}
