<?php

$pageTitle="Log in to IceBear";
include realpath(__DIR__).'/../_common/header.php';

$icebearCodeVersion=config::getCodeVersion();

$messageHeader=str_replace("'","\'", htmlentities(config::get('core_prelogin_messageheader')));
$message=str_replace("'","\'", htmlentities(config::get('core_prelogin_message')));


$identityProviders=[];
/** @var string|null $wwwroot It's a string. */
$identityProvidersFile=rtrim($wwwroot,'/').'/conf/identityProviders.json';
if(file_exists($identityProvidersFile) && $json=@file_get_contents($identityProvidersFile)){
	$json=json_decode($json, true);
	if(isset($json['identityProviders'])){
		$identityProviders=$json['identityProviders'];
	}
}?>

    <!--suppress JSUnresolvedReference -->
    <script type="text/javascript">
        let identityProviders=<?php echo json_encode($identityProviders); ?>;
        let requestedUri='<?php echo $uri ?? ''; ?>';
        let icebearDbVersion='<?php echo config::get('core_icebearversion'); ?>';
        if(!icebearDbVersion){ icebearDbVersion='unknown'; }
        let icebearCodeVersion='<?php echo $icebearCodeVersion; ?>';
        if(!icebearCodeVersion){ icebearCodeVersion='unknown'; }

        let codeAndDbMatch=(icebearCodeVersion===icebearDbVersion);

        let messageHeader='<?php echo $messageHeader; ?>'.trim();
        let message='<?php echo $message; ?>'.trim();


        let grid=ui.grid();

        let loginBoxParams={
            'id':'loginbox',
            'title':'Log in to IceBear',
            'classes':'r2 c2 h1 w1'
        };
        if(!codeAndDbMatch){

            grid.box({
                'id':'message',
                'title':'Database version mismatch',
                'classes':'r1 c2 h1 w1',
                'content':'<span style="color:red">IceBear can\'t be used at the moment because its database and code don\'t match.<br/><br/>The database version ('+icebearDbVersion+') does not match the code version ('+icebearCodeVersion+'). An administrator needs to fix this</span>.'
            });
            loginBoxParams={
                'id':'loginbox',
                'title':'Administrator login',
                'classes':'r2 c2 h1 w1'
            };
//        } else if(""!==message){
//            loginBoxParams["classes"]="r2 c2 h1 w1";
        }

        let b=grid.box(loginBoxParams);
        let frm=b.form({
            'action':'/api/Login'
        });
        frm.textField({ label:"Username", name:'username' });
        frm.passwordField({ label:"Password", name:'password' });
        frm.submitButton({ label:'Log in' });
        frm.onsubmit=function(){ Login.doLogin(); return false; };
        window.addEventListener("load",function(){ document.getElementById("username").focus()});

        if(identityProviders.length && codeAndDbMatch){
            if("1"===Cookies.get("sentToDiscoveryService")){
                frm.innerHTML="Redirecting to login service...";
                let shibbolethURL="/Shibboleth.sso/Login?entityID=<?php echo $_GET['entityID'] ?? 'NULL'; ?>&return="+encodeURIComponent(Cookies.get("urlAfterAuth"));
                Cookies.unset("sentToDiscoveryService");
                Cookies.unset("ownEntityID");
                document.location.href=shibbolethURL;
            } else {
                let idpRendered=false;
                identityProviders.forEach(function(idp){
                    idpRendered=Login.renderIdentityProvider(idp);
                });
                if(idpRendered){
                    Login.renderIdentityProvider({
                        "name":"IceBear account",
                        "logoURL":"/images/icebearlogo.svg"
                    }); //Hides the default login form
                    b.dataset.originalWidth=b.clientWidth+"";
                    b.dataset.fullWidth=b.clientWidth+"";
                    let pageWidth=document.getElementById("content").clientWidth+"";
                    let links=b.querySelectorAll("a.idp");
                    let firstLink=links[0];
                    let lastLink=links[links.length-1];
                    while(firstLink.offsetTop<lastLink.offsetTop && b.clientWidth<0.9*pageWidth){
                        b.dataset.fullWidth=(1*b.dataset.fullWidth+50)+"";
                        let wrapper=b.closest(".box")
                        wrapper.style.width=b.dataset.fullWidth+"px";
                        let nowLeft=parseInt(window.getComputedStyle(wrapper).left);
                        wrapper.style.left=(nowLeft-25)+"px";
                    }

                }

            }
        }
        b.style.textAlign="center"
        setBoxHeight(b);
        //TODO Set box width if IDPs. Min-width is existing "w1" width. Expand until all buttons are on same height. Go back to w1 if IB login selected, back to full width if cancelled.


        if(""!==message){
            let msgBox=grid.box({
                'id':'prelogin',
                'title':messageHeader,
                'classes':'r1 c2 h1 w1',
                'content':"<p>"+message+"</p>"
            });
            setBoxHeight(msgBox);
        }


        let out;
        let bs=grid.box({
            'id':'logoBox',
            'classes':'r3 c2'
        });

        bs=bs.closest(".box");
        bs.closest(".box").style.border="none";

        if(codeAndDbMatch){
            out='<div style="width:20em; padding:0.5em; text-align:center;position:absolute;bottom:0;left:calc(50% - 10em); background: var(--boxAndTabBodyBackground); opacity: var(--boxAndTabBodyBackgroundOpacity); border-radius: 0.5em">' +
                '<img alt="IceBear logo" src="/im'+'ages/icebearlogo.svg" style="height:6em; float: left; margin-right: 0.5em;"/>';
            out+='<p style="margin-top:1.5em;line-height:1.75em;font-size:75%">';
            out+='IceBear version '+icebearDbVersion+' &bull; <a target="_blank" href="https://scripts.iucr.org/cgi-bin/paper?S2059798320015223">Cite IceBear</a>';
            out+='<br/>Distributed under the <a href="/LIC'+'ENSE.txt" target="_blank">MIT License</a>';
            out+='<br/>IceBear uses <a href="https://icebear.fi/resources/policies/cookies.php" target="_blank">cookies</a>';
			<?php
			$localPrivacyPolicyUrl=config::get('core_privacypolicy_url');
			$localPrivacyPolicyLinkText=config::get('core_privacypolicy_linktext');
			if(!empty(trim($localPrivacyPolicyUrl))){
				if(empty(trim($localPrivacyPolicyLinkText))){
					$localPrivacyPolicyLinkText="Privacy policy";
				}
				echo "out+=' &bull; <a target=\"_blank\" href=\"$localPrivacyPolicyUrl\">$localPrivacyPolicyLinkText</a>';";
			}
			if(1*config::isIceBox()) { ?>
            out+=' &bull; <a target="_blank" href="https://icebear.fi/resources/policies/icebox_privacy.php">IceBox privacy policy</a>';
			<?php }?>
            out+='</p></div>';
            bs.innerHTML=out;
        } else {
            out='<span style="color:red; background-color: white">Code and database version do not match'+
                '<br/>Code version: '+icebearCodeVersion+'; database version: '+icebearDbVersion+
                '<br/>Only administrators can log in.</span>';
            bs.innerHTML=out;
        }

        document.onvisibilitychange=function (){
            if(!document.hidden){
                new AjaxUtils.Request('/api/homepageuserbrick',{
                    method:"get",
                    suppressSessionExpiredMessage:true,
                    onSuccess:function (){
                        //Success means the user is logged in (another tab?). Reload.
                        document.location.reload();
                    },
                    onFailure:function(){
                        //Do nothing, user is still logged out.
                    }
                });
            }
        };

        function setBoxHeight(boxBody){
            let box=boxBody.closest(".box");
            let elem=boxBody.lastElementChild;
            box.classList.remove("h1");
            if(box.querySelector("h2")){
                boxBody.style.height="calc("+elem.clientHeight+"px + "+elem.clientTop+"px + 4em)";
                box.style.height="calc("+elem.clientHeight+"px + "+elem.clientTop+"px + 4em)";
            } else {
                boxBody.style.height="calc("+elem.clientHeight+"px + "+elem.clientTop+"px + 2em)";
                box.style.height="calc("+elem.clientHeight+"px + "+elem.clientTop+"px + 2em)";

            }
        }

    </script>

<?php include realpath(__DIR__).'/../_common/footer.php';