<?php
// DB credentials.
if (!defined('DB_HOST')) define('DB_HOST','localhost');
if (!defined('DB_USER')) define('DB_USER','dev020_tradersafetywiki'); 
if (!defined('DB_PASS')) define('DB_PASS','Tradersafety@wiki');
if (!defined('DB_NAME')) define('DB_NAME','dev020_tradersafetywiki');

if (!isset($dbh) || !($dbh instanceof PDO)) {
	$connectionAttempts = array(
		array(DB_USER, DB_PASS),
	);

	if (DB_HOST === 'localhost') {
		$connectionAttempts[] = array('root', '');
		$connectionAttempts[] = array('root', 'root');
	}

	$lastError = null;
	foreach ($connectionAttempts as $attempt) {
		try {
			$dbh = new PDO(
				"mysql:host=".DB_HOST.";dbname=".DB_NAME,
				$attempt[0],
				$attempt[1],
				array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")
			);
			$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$lastError = null;
			break;
		} catch (PDOException $e) {
			$lastError = $e;
		}
	}

	if ($lastError !== null) {
		exit("Error: " . $lastError->getMessage());
	}
}

/**
 * Validate admin session and prevent caching for security
 * Call this after session_start() in protected admin pages
 */
function require_admin_session() {
	if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
		header("Location: login.php");
		exit;
	}
	
	// Prevent browser caching of admin pages - critical for logout security
	header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
	header('Pragma: no-cache');
	header('Expires: 0');
	header('X-UA-Compatible: IE=Edge');
	header('X-Frame-Options: SAMEORIGIN');
	header('X-Content-Type-Options: nosniff');
}
?>
