<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class SamlSettings extends BaseConfig
{
  
    // IdP (Identity Provider)
    public $idpEntityId;
    public $idpSSOUrl;
    public $idpSLOUrl;
    public $idpX509Cert;

    // SP (Service Provider)
    public $spEntityId;
    public $spAssertionConsumerServiceUrl;
    public $spSingleLogoutServiceUrl;
    public $spCert;
    public $spPrivateKey;

    public $strict = true; // Enable strict mode
    public $debug = true;  // Enable debug mode for development

    private $publicCertPath;
    private $privateKeyPath;


  



    public function __construct()
    {
        parent::__construct();

        // Define idp details
        $this->idpEntityId = env('IDP_EntityId');
        $this->idpSSOUrl = env('IDP_SSOUrl');
        $this->idpSLOUrl = env('IDP_SLOUrl');
        $this->idpX509Cert = env('IDP_X509Cert');


        // Define the public and private key file paths
        $this->publicCertPath = ROOTPATH . 'sp_cert.pem';
        $this->privateKeyPath = ROOTPATH . 'sp_private_key.pem';

        // Set SP URLs
        $this->spEntityId = base_url();
        $this->spAssertionConsumerServiceUrl = base_url() . 'acs';
        $this->spSingleLogoutServiceUrl = base_url() . 'logout';

        // Load the public certificate
        $this->spCert = $this->loadFile($this->publicCertPath);

        // Load the private key
        $this->spPrivateKey = $this->loadPrivateKey($this->privateKeyPath);
    }

    /**
     * Load a file and return its contents.
     *
     * @param string $filePath Path to the file.
     * @return string The file contents.
     */
    private function loadFile($filePath)
    {
        $fileContents = file_get_contents($filePath);

        if ($fileContents === false) {
            die("Failed to load the public certificate from {$filePath}");
        }

        return $fileContents;
    }

    /**
     * Load and validate a private key.
     *
     * @param string $filePath Path to the private key file.
     * @return string The private key contents.
     */
    private function loadPrivateKey($filePath)
    {
        $privateKey = file_get_contents($filePath);

        if ($privateKey === false) {
            die("Failed to read private key from {$filePath}");
        }

        // Validate the private key
        if (openssl_pkey_get_private($privateKey) === false) {
            die("Invalid private key at {$filePath}");
        }

        return $privateKey;
    }

}
