<?php 

require_once("../../../../spid-cie-php/proxy-spid-php.php");

const PROXY_CONFIG_FILE = "../../../../spid-cie-php/spid-php-proxy.json";
const DEBUG = false;
const ERR_REDIRECT = "/metadata.xml";

if(DEBUG) {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

$proxy_config = file_exists(PROXY_CONFIG_FILE)? json_decode(file_get_contents(PROXY_CONFIG_FILE), true) : array();
// always set to production to avoid test/validator button to be active while testing
$production = $proxy_config['production'];
$clients = $proxy_config['clients'];

$client_id = isset($_GET['client_id'])? $_GET['client_id'] : null;
$level = (isset($_GET['level']) && $_GET['level'])? $_GET['level'] : 2;
$redirect_uri = isset($_GET['redirect_uri'])? urldecode($_GET['redirect_uri']) : urldecode($clients[$client_id]['redirect_uri'][0]);
$state = (isset($_GET['state']) && $_GET['state'])? $_GET['state'] : '';
$idp = isset($_GET['idp'])? $_GET['idp'] : null;
$tenant_id = $clients[$client_id]['tenant_id'];


if($client_id==null || $client_id=='') { 
    http_response_code(404); 
    if(DEBUG) {
        echo "client_id not provided"; 
    } else {
        header("Location: " . ERR_REDIRECT);
    }
    die(); 
}

if($level==null || $level=='') { 
    http_response_code(404); 
    if(DEBUG) {
        echo "level not provided";
    } else {
        header("Location: " . ERR_REDIRECT);
    }
    die(); 
}

if($redirect_uri==null || $redirect_uri=='') { 
    http_response_code(404); 
    if(DEBUG) {
        echo "redirect_uri not provided";
    } else {
        header("Location: " . ERR_REDIRECT);
    }
    die(); 
}

if(!in_array($client_id, array_keys($clients))) { 
    http_response_code(404); 
    if(DEBUG) {
        echo "client_id not found"; 
    } else {
        header("Location: " . ERR_REDIRECT);
    }
    die(); 
}

if(!in_array($redirect_uri, $clients[$client_id]['redirect_uri'])) { 
    http_response_code(404); 
    if(DEBUG) {
        echo "redirect_uri not found"; 
    } else {
        header("Location: " . ERR_REDIRECT);
    }
    die(); 
}


$service = "service";
if($idp=="CIE" || $idp=="CIE TEST") $service = "cie";
$spidsdk = new PROXY_SPID_PHP($client_id, $redirect_uri, $state, $production, $service);

//$spidsdk->setPurpose("P");

$organization_name = isset($clients[$client_id]['description'])? $clients[$client_id]['description'] : '';

if(!$spidsdk->isAuthenticated()) {
    if($idp==null || $idp=='') {    
        
        ?>
        <!DOCTYPE html>
        <html lang="it"">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
            <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no" />
			<link href="/assets/css/custom.css?v=2.1" rel="stylesheet" />
            
           
            <link href="/assets/css/eidas-sp-access-button.min.css" rel="stylesheet" />
            <link href="/assets/css/style.css" rel="stylesheet" />
			<link rel="preconnect" href="https://fonts.googleapis.com"> 
            <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
            <link href="https://fonts.googleapis.com/css2?family=Titillium+Web:wght@200;300;400;600;700;900&display=swap" rel="stylesheet">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
            <?php $spidsdk->insertSPIDButtonCSS(); ?>
			
			<link rel="stylesheet" href="/assets/bootstrap-italia/css/bootstrap-italia.min.css">
            <link href="/assets/bootstrap-italia/css/bootstrap-italia-comuni.css" rel="stylesheet">
            

        </head>
        <body style="margin:0">
            
            <div id="importHeader"></div>
            
            <main>
                <div class="container" id="main-container">
                    <div class="row">
                        <div class="col-12 col-lg-10 offset-lg-1">
                            <div class="cmp-breadcrumbs" role="navigation">
                                <nav class="breadcrumb-container" aria-label="breadcrumb">
                                    <ol class="breadcrumb p-0" data-element="breadcrumb">
                                        <li class="breadcrumb-item"><a id="homeButton" href="homepage.html">Home</a><span class="separator">/</span></li>
                                        <li class="breadcrumb-item active" aria-current="page">Accedi</li>
                                    </ol>
                                </nav>
                            </div>        <div class="cmp-heading pb-3 pb-lg-4">
                                <h1 class="title-xxxlarge">Accedi</h1>
                                
                                <p class="subtitle-small">Per accedere al sito e ai suoi servizi, utilizza una delle seguenti modalità.</p>
                                
                                
                                
                                
                                
                            </div>
                        </div>
                    </div>
                    <hr class="d-none d-lg-block mt-0 mb-4">
                    <div class="row">
                        <div class="col-12 col-lg-8 offset-lg-2">
                            <div class="cmp-text-button mt-3">
                                <h2 class="title-xxlarge mb-0">SPID</h2>
                                <div class="text-wrapper">
                                    <p class="subtitle-small mb-3">Accedi con SPID, il sistema Pubblico di Identità Digitale.</p>
                                </div>
                                <div class="col-12 col-md-6">
                                    
                                    
                                    <?php $spidsdk->insertSPIDButton("M"); ?>
                                    
                                </div>
                                
                                <a class="simple-link" href="#">Come attivare SPID <span class="visually-hidden">Come attivare SPID</span></a>
                            </div>
                            
                            <div class="cmp-text-button">
                                <h2 class="title-xxlarge mb-0">CIE</h2>
                                <div class="text-wrapper">
                                    <p class="subtitle-small mb-3">Accedi con la tua Carta d’Identità Elettronica.</p>
                                </div>
                                <div class="col-12 col-md-6">
                                    <a id="btn-accedi" type="submit" class="btn p-0 border-0 my-3" 
                                    href="/proxy.php?action=login&client_id=<?php echo $client_id; ?>&redirect_uri=<?php echo $redirect_uri; ?>&idp=CIE&state=<?php echo $state; ?>">
                                    <img class="img-fluid" src="/assets/img/button_cie.png" alt="">
                                    <span class="sr-only">Accedi con identità digitale CIE</span>
                                </a>
                            </div>
                            
                            <a class="simple-link" href="#">Come richiedere CIE <span class="visually-hidden">Come richiedere CIE</span></a>
                        </div>
                        
                        <div class="cmp-text-button">
                            <h2 class="title-xxlarge mb-0">Altre utenze</h2>
                            <div class="text-wrapper">
                                <p class="subtitle-small mb-3">In alternativa puoi utilizzare le seguenti modalità.</p>
                            </div>
                            <div class="button-wrapper d-md-flex">
                                <button type="button" class="btn btn-outline-primary btn-re pr-md-4 bg-white">
                                    
                                    
                                    
                                    <span class="">Accedi con ID azienda</span>
                                </button>
                                <button type="button" class="btn btn-outline-primary btn-re bg-white">
                                    
                                    
                                    
                                    <span class="">Accedi come dipendente</span>
                                </button>
                            </div>
                            
                        </div>
                    </div>
                </div>
            </div>
            
        </main>
        <div id='importFooter' style="overflow: hidden"></div>
		
        
        <?php $spidsdk->insertSPIDButtonJS(); ?>
        <script src="<?= $tenant_id ?>/trisoft_custom.js"></script>
        
        <script> 
            $(function(){
                $("#importHeader").load('<?= $tenant_id ?>/header.html'); 
                $("#importFooter").load('<?= $tenant_id ?>/footer.html'); 
                
                /*$(header).fadeOut('fast', function() {
                    $.ajax({
                        url: '<?= $tenant_id ?>/header.html',
                        success: function(data,status,jqXHR) {
                            $(header).html($(data))
                            .fadeIn('fast', null);
                        }
                    });
                    
                });
                
                
                $(footer).fadeOut('fast', function() {
                    $.ajax({
                        url: '<?= $tenant_id ?>/footer.html',
                        success: function(data,status,jqXHR) {
                            $(footer).html($(data))
                            .fadeIn('fast', null);
                        }
                    });
                    
                });*/
            });
        </script> 
    </body>
    </html>
    
    <?php
} else {
    /***
    * questo branch non viene raggiunto perchè utilizzando 
    * $spidsdk->insertSPIDButton per simplicità
    * il login viene effettuato da proxy-spid.php 
    * con i valori di spid_level e atcs_index predefiniti
    * in spid-php-proxy.json
    * Quindi ogni applicativo (compreso OIDC Plugin)
    * non può gestirli a runtime
    **/
    
    if($spidsdk->isIdPAvailable($idp)) {
        $spidsdk->login($idp, $level, "", 0); 
    } else {
        if(DEBUG) {
            echo "idp not valid";
        } else {
            header("Location: " . ERR_REDIRECT);
        }
    }
    
    // set AttributeConsumingServiceIndex 2
    //$spidsdk->login($idp, 2, "", 2);
}

} else {
    $idp = $spidsdk->getIdPKey();
    $proxy_url = "/proxy-spid.php?action=login&client_id=".$client_id.
    "&redirect_uri=".$redirect_uri.
    "&state=".$state.
    "&idp=".$idp;
    
    header("Location: " . $proxy_url);
}
?>