<?php

/**
 * @link https://www.elated.com/cms-in-an-afternoon-php-mysql/
 * https://www.elated.com/add-image-uploading-to-your-cms/
 * https://www.elated.com/mod-rewrite-tutorial-for-absolute-beginners/#friendly-urls
 */

define( "UPLOAD_RND_FILE_NAMES", false ); // Randomized file names to allow Duplicates?
define( "BLOG_NAME", "Widgetz Newz" ); // Display Name for Titles
define( "HOMEPAGE_NUM_ARTICLES", 5 );
ini_set( "display_errors", false );
date_default_timezone_set( "America/Detroit" );  // http://www.php.net/manual/en/timezones.php

$d = dirname(__DIR__, 1); // Up one level for Composer Vendor DIR
require_once $d . '/vendor/autoload.php';
$e = dirname(__DIR__,2); // Up two levels for ENV file
$dotenv = Dotenv\Dotenv::createImmutable($e);
$dotenv->load();

// Get the protocol (http or https)
$protocol = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http';
// Get the domain name
$domain = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost';
// Get the port number
$port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : '80';
// Combine for the SiteURL...
if ($port === "80" || $port === "443") {
    define( "SITE_URL", "{$protocol}://{$domain}");    
} else {
    define( "SITE_URL", "{$protocol}://{$domain}:{$port}");
}

define( "DB_DSN", $_ENV['DB_TYPE'].":host=".$_ENV['DB_HOST'].";dbname=".$_ENV['DB_NAME'] );
define( "DB_USERNAME", $_ENV['DB_USERNAME'] );
define( "DB_PASSWORD", $_ENV['DB_PASSWORD']);
define( "CLASS_PATH", "../protected/src/classes" );
define( "TEMPLATE_PATH", "../protected/src/templates" );

$admins = $_ENV['ADMIN_USERS'];
$usersArray = explode(',', $admins);
$a_admins = [];
foreach ($usersArray as $user) {
    list($username, $password) = explode(':', $user);
    $a_admins[$username] = $password;
}

define( "ADMIN_USERS", $a_admins);
define( "ARTICLE_IMAGE_PATH", "../protected/images/articles" );
define( "IMG_TYPE_FULLSIZE", "fullsize" );
define( "IMG_TYPE_THUMB", "thumb" );
define( "ARTICLE_THUMB_WIDTH", 120 );
define( "JPEG_QUALITY", 85 );
require( CLASS_PATH . "/Article.php" );
require( CLASS_PATH . "/Category.php" );

function handleException( $exception ) {
  echo "Sorry, a problem occurred. Please try later.";
//  echo $exception->getMessage();
  error_log( $exception->getMessage() );
}

set_exception_handler( 'handleException' );