<?php
// /header_basic.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// require_once $_SERVER['DOCUMENT_ROOT'] . '/.sys/wp-load.php'; // for auth using wp as headless
// require_once 'config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/profile_functions.php';
include $_SERVER['DOCUMENT_ROOT'] . '/api/pro_features.php';

if (!isset($_SESSION['front_user_id'])) {
    header('Location: login');
    exit;
}

// set home
$is_home = ($_SERVER['REQUEST_URI'] === '/' || $_SERVER['SCRIPT_NAME'] === '/index.php');

$userId = $_SESSION['front_user_id'];
$userDetails = getUserDetails($userId);

function getUserDetails($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';
    
    $stmt = $pdo->prepare("SELECT u.*, g.group_name FROM $table_name u 
                          LEFT JOIN wp_groups g ON u.group_id = g.id 
                          WHERE u.ID = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    return [
        'email' => $user['user_email'] ?? '',
        'group' => $user['group_name'] ?? '',
        'is_admin' => $user['is_admin'] ?? 0,
        'is_super' => $user['user_type'] === 'super',
        'is_owner' => $user['user_type'] === 'admin',
        'first_name' => $user['first_name'] ?? '',
        'last_name' => $user['last_name'] ?? ''
    ];
}

// Change name form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_name') {
    $updateData = [
        'first_name' => trim($_POST['first_name']),
        'last_name' => trim($_POST['last_name'])
    ];

    if (updateUserSettings($userId, $updateData)) {
        $_SESSION['success_message'] = "Name updated successfully!";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $_SESSION['error_message'] = "Failed to update name.";
    }
}

function getUserDetailsWithProStatus($userId) {
    global $pdo;
    $users_table = PREFIX . 'users';
    $groups_table = PREFIX . 'groups';

    // Fetch user details along with group details
    $stmt = $pdo->prepare("SELECT u.*, g.pro_status AS group_pro_status, g.pro_expiration_date AS group_pro_expiration_date 
                        FROM $users_table u 
                        LEFT JOIN $groups_table g ON u.group_id = g.id 
                        WHERE u.ID = ?");
    $stmt->execute([$userId]);
    $userDetails = $stmt->fetch(PDO::FETCH_ASSOC);

    // Log retrieved values for debugging
	/* 
    echo "<script>console.log('User Group ID: " . ($userDetails['user_group'] ?? 'No user group') . "');</script>";
    echo "<script>console.log('Group Pro Status: " . ($userDetails['group_pro_status'] ?? 'No group status') . "');</script>";
    echo "<script>console.log('Group Pro Expiration Date: " . ($userDetails['group_pro_expiration_date'] ?? 'No group expiration date') . "');</script>";
	*/

    // Determine final pro status
    $status = 'No';
    if ($userDetails) {
        if ($userDetails['pro_status'] === 'Pro' || $userDetails['group_pro_status'] === 'Pro') {
            $status = 'Pro';
        }
    }

    // Set expiration based on group expiration date
    $expiration = $userDetails['group_pro_expiration_date'] ?: '';

    return [
        'userDetails' => $userDetails,
        'status' => $status,
        'expiration' => $expiration,
    ];
}

// Usage
$userDetailsPro = getUserDetailsWithProStatus($_SESSION['front_user_id']);

// Prepare data to pass to JavaScript
$status = $userDetailsPro['status'] ?? '';
$expiration = $userDetailsPro['expiration'] ?? '';

?>
<!DOCTYPE html>
<html lang="en" class="dark-theme">
<head>
	<?php /* <script src="js/perf.js" type="application/javascript" ></script> */ ?>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo SITE_TITLE; ?></title>
	<script>
		// Immediately execute theme detection
		(function() {
			function getCookie(name) {
				const nameEQ = name + "=";
				const ca = document.cookie.split(';');
				for(let i = 0; i < ca.length; i++) {
					let c = ca[i];
					while (c.charAt(0) === ' ') c = c.substring(1, c.length);
					if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
				}
				return null;
			}
			
			const savedTheme = getCookie('theme');
			if (savedTheme === 'light') {
				document.documentElement.classList.add('light-theme');
			}
		})();
	</script>

    <meta name="description" content="<?php echo SITE_DESCRIPTION; ?>">
    <meta name="keywords" content="<?php echo SITE_KEYWORDS; ?>">
    <meta name="author" content="<?php echo COMPANY_NAME; ?>">

    <meta property="og:title" content="<?php echo SITE_TITLE; ?>">
    <meta property="og:description" content="<?php echo SITE_DESCRIPTION; ?>">
    <meta property="og:image" content="<?php echo MYSITE_URL; ?>/images/og-image.jpg">
    <meta property="og:url" content="<?php echo MYSITE_URL; ?>">
    <meta property="og:type" content="website">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo SITE_TITLE; ?>">
    <meta name="twitter:description" content="<?php echo SITE_DESCRIPTION; ?>">
    <meta name="twitter:image" content="<?php echo MYSITE_URL; ?>/images/twitter-image.jpg">

	<link rel="icon" href="/images/icons/favicon.png" type="image/png">
    <link rel="apple-touch-icon" sizes="180x180" href="/images/icons/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/images/icons/favicon-16x16.png">
    <link rel="manifest" href="/configs/site.webmanifest">

    <meta name="robots" content="index, follow">
    <meta name="theme-color" content="#ffffff">
	
	<link rel="stylesheet" href="css/loader.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=53">
	<?php if (defined('IS_DEV') && IS_DEV) {
		echo '<link rel="stylesheet" href="../css/dev.css">';
	} ?>
	<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=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css2?family=Kadwa:wght@400;700&display=swap" rel="stylesheet">

	<script>window.userStatus = "<?php echo $status; ?>";</script>
	<script>window.userExpiration = "<?php echo $expiration; ?>";</script>
	<script>mainUrl = "<?php echo MAINSITE_URL; ?>";</script>
	
	<script src="app/scripts/prototype.js" type="application/javascript"></script>		
	
</head>
<body<?php echo $is_home ? '' : ' class="no-sidebar"'; ?>>
<?php if (defined('IS_DEV') && IS_DEV) { echo '<div id="devsite"><span>Dev Site</span></div>'; } ?>
<div id="divErrorScreen" style="display:block">
    <div id="loader-container">
        <div id="loader-animate"></div>
        <div id="loader-text"><?php echo SITE_TITLE; ?> is loading</div>
    </div>
</div>
<script src="js/loader.js" type="text/javascript" ></script>

	<div class="top-menu">
		<div class="logo">
			<a href="<?php echo MYSITE_URL; ?>"><img src="<?php echo MYSITE_URL; ?>/images/logo/logo-new-dark.png" title="<?php echo COMPANY_NAME; ?>">
			<?php /* <i class="fas fa-hospital"></i> &nbsp; <span><?php echo COMPANY_NAME; ?></span> */ ?></a>
		</div>
		<div class="center-title"><?php echo SITE_TITLE; ?></div>
		
		<div class="user-menu">
			<div class="my-account" id="my-account">
				<span>My Account</span>
				<div class="profile-picture-container">
					<?php
				$userId = $_SESSION['front_user_id'];

				if (function_exists('getProfilePictureUrl2')) {
					$profile_picture_data = getProfilePictureUrl2($userId);
					
					if ($profile_picture_data && isset($profile_picture_data->unique_id) && isset($profile_picture_data->profile_picture)) {
						$profile_picture_url = '/images/profiles/' . $profile_picture_data->unique_id . '/' . $profile_picture_data->profile_picture;
						echo '<img src="' . htmlspecialchars($profile_picture_url) . '" alt="Profile Picture" class="profile-picture">';
					} else {
						echo '<div class="icon-circle"><i class="fas fa-user-circle"></i></div>';
					}
				} else {
					echo '<div class="icon-circle"><i class="fas fa-user-circle"></i></div>';
				}
					?>
				</div>
			</div>
			
			<div class="my-settings" id="my-settings">
				<i class="fas fa-cog"></i><span>Settings</span>
			</div>
		</div>
	</div>

	<div class="second-top-bar">
		<div class="timer-score">
			<button id="toggle-sidebar" class="toggle-sidebar"><i class="fas fa-bars"></i></button>
			<div class="timer" id="btnTime">00:00:00</div>
			<div class="score" id="txtScore">Score: 0</div>
			<button class="action-button cases showCasesList"><div class="icon-circle"><i class="fas fa-folder"></i></div> View Cases</button>
			<button class="action-button preop" id="btnPreop" onclick="location.href='<?php echo isset($_SESSION['current_case']) ? '/preop' : '/'; ?>'"><div class="icon-circle"><i class="fas fa-procedures"></i></div> PreOp</button>
			<button class="action-button case-help" id="btnCaseHelp" onclick="location.href='<?php echo isset($_SESSION['current_case']) ? '/case-help' : '/'; ?>'"><div class="icon-circle"><i class="fas fa-question-circle"></i></div> Case Help</button>
			<button class="action-button case-log" id="btnCaseLog" onclick="location.href='<?php echo isset($_SESSION['current_case']) ? '/case-log' : '/'; ?>'"><div class="icon-circle"><i class="fas fa-file-medical"></i></div> Case Log</button>
		</div>
		<div class="action-buttons">
			<button class="action-button new-case" id="btnNewCase" onclick="location.href='/'"><div class="icon-circle"><i class="fas fa-plus-circle"></i></div> New Case</button>
		</div>
	</div>

	<div class="menu" id="my-settings-menu">
		<div class="my-account-menu my-account-menu-left">
			<h3 class="settings-menu-title">Settings</h3>
			<ul>
				<li class="settings-toggles theme-toggle" id="theme-toggle">
				  <i class="fas fa-moon"></i>
				  <span class="label">Theme:</span>
				  <div class="toggle-options">
					<button class="toggle-option active" data-value="dark">Dark</button>
					<button class="toggle-option" data-value="light" style="border: none;">Light</button>
				  </div>
				</li>
				
				<?php if ($userDetails['is_super']) { ?>
					<li class="settings-toggles session-toggle" id="session-toggle">
						<i class="fas fa-play"></i>
						<span class="label">Session Termination:</span>
						<span class="session-text">On</span>
					</li>
				<?php } ?>
			</ul>
		</div>
	</div>

	<div class="menu" id="my-account-menu">
		<div class="my-account-menu">
			<ul>
				<div class="just-info-outer">
					<li class="just-info">
					  <div class="text-wrapper">
						<div class="inner-text" data-text="<?php echo htmlspecialchars($userDetails['first_name'] . ' ' . $userDetails['last_name']); ?>"><?php echo htmlspecialchars($userDetails['first_name'] . ' ' . $userDetails['last_name']); ?></div>
					  </div>
					  <span class="info-mark"><i class="fa fa-info"></i><span class="info-tag">Name</span></span>
					</li>
					<li class="just-info">
					  <div class="text-wrapper text-wrapper-email">
						<div class="inner-text" data-text="<?php echo htmlspecialchars($userDetails['email']); ?>"><?php echo htmlspecialchars($userDetails['email']); ?></div>
					  </div>
					  <i class="fas fa-copy copy-icon copy-icon-email" style="display: none;"></i>
					  <span class="info-mark"><i class="fa fa-info"></i><span class="info-tag">Email</span></span>
					</li>
					<li class="just-info">
					  <div class="text-wrapper">
						<div class="inner-text-group"><?php echo htmlspecialchars($userDetails['group']); ?></div>
					  </div>
					  <span class="info-mark"><i class="fa fa-info"></i><span class="info-tag">Group</span></span>
					</li>
					<?php if ($userDetails['is_admin'] == 1) {?>
						<li class="just-info user-type-menu">Administrator
							<span class="info-mark"><i class="fa fa-info"></i>
								<span class="info-tag">User Role</span>
							</span>
						</li>
					<?php } 
						$modalContent = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/app/modal_data/modal-content.json'), true);
						$statusText = $modalContent['proModal']['statusText'] ?? [];
					?>
					<li class="pro-button">
						<a href="#" id="proButton" data-status="<?php echo htmlspecialchars($status); ?>" data-expiration="<?php echo htmlspecialchars($expiration); ?>">
							<?php 
								if (isProFeatureEnabled('additional_cases')) {
									echo $statusText['Pro'] ?? 'Pro Active';
								} else {
									echo $statusText['Upgrade'] ?? 'Upgrade to Pro';
								}
							?>
						</a>
					</li>
				</div>
				
				<?php if ($userDetails['is_super']) { ?>
					<li class="admin-dash-btn">
						<i class="fas fa-tachometer-alt"></i>
						<a href="admin">Super Admin Dashboard</a>
					</li>
				<?php } else if ($userDetails['is_owner']) { ?>
					<li class="admin-dash-btn">
						<i class="fas fa-tachometer-alt"></i>
						<a href="admin">Admin Dashboard</a>
					</li>
				<?php } ?>
				
				<hr>
				
				<a href="/cases">
					<li class="my-settings-btn view-my-cases">
						<i class="fas fa-folder-open"></i>
						<span>View My Cases</span>
					</li>
				</a>
				
				<hr>

				<?php /* <li class="my-profile-menu-title">
					<span>My Settings</span>
				</li> */ ?>
				
				<a href="/profile">
					<li class="my-settings-btn view-my-settings">
						<i class="fas fa-folder"></i>
						<span>My Profile</span>
					</li>
				</a>
				
				<?php /* <li class="my-settings-btn change-my-settings">
					<i class="fas fa-cog"></i>
					<span>Change Profile Name</span>
				</li>
				<li class="change-profile-picture">
					<i class="fas fa-camera"></i>
					<span>Change Profile Picture</span>
				</li>
				
				<hr> */ ?>
				
				<a href="<?php echo MAINSITE_URL; ?>/contact" target="_blank">
					<li class="help-item">
						<i class="fas fa-question-circle"></i>
						<span>Help</span>
					</li>
				</a>
				<a href="<?php echo MAINSITE_URL; ?>/contact" target="_blank">
					<li class="feedback-item">
						<i class="fas fa-comment"></i>
						<span>Feedback</span>
					</li>
				</a>

				<?php if ($isLoggedIn) {
					echo '<a class="logout" href="logout.php">Log Out</a>';
				} else {
					echo '<a class="logout" href="login.php">Log In</a>';
				} ?>
			</ul>
		</div>
	</div>

	<?php /* alternate pro status modal *************
	<div id="proStatusModal" class="modal" style="display: none;">
		<div class="modal-content">
			<span class="close">&times;</span>
			<h2 id="proStatus"></h2>
			<p id="proExpiration"></p>
			<ul id="proFeatures"></ul>
			<a id="proAction" href="#" class="button"></a>
		</div>
	</div>
	******************************************* */ ?>
			
	<div id="proStatusModal" class="modal" style="display: none;">
		<div class="modal-content">
			<span class="close">&times;</span>
			<h2 id="proStatus"></h2>
			<p id="proExpiration"></p>
			<ul id="proFeatures"></ul>
			<button class="upgradeYes">Yes, Upgrade</button>
			<button class="upgradeNo">No, Thanks</button>
		</div>
	</div>
			
	<div id="profilePictureModal" class="modal">
		<div class="modal-content">
			<span class="close">&times;</span>
			<h2>Change Profile Picture</h2>
			<form id="profilePictureForm" enctype="multipart/form-data">
				<input type="file" name="profile_picture" id="profile_picture" accept=".jpg,.jpeg,.png,.gif">
				<button type="submit">Upload</button>
			</form>
			<?php
			// Debug information
			echo "<!-- Debug: Checking for existing profile picture -->";
			$profilePicUrl = false;
			if (function_exists('getProfilePictureUrl2') && isset($_SESSION['front_user_id'])) {
				$userId = $_SESSION['front_user_id'];
				$profile_picture_data = getProfilePictureUrl2($userId);
				if ($profile_picture_data && isset($profile_picture_data->unique_id) && isset($profile_picture_data->profile_picture)) {
					$profilePicUrl = '/images/profiles/' . $profile_picture_data->unique_id . '/' . $profile_picture_data->profile_picture;
				}
			}
			?>
			<div id="currentProfilePicture">
				<?php if ($profilePicUrl): ?>
					<p>Current profile picture:</p>
					<img src="<?php echo htmlspecialchars($profilePicUrl); ?>" alt="Current Profile Picture" style="max-width: 200px;">
					<button id="removeProfilePicture">Remove Profile Picture</button>
				<?php else: ?>
					<p>No current profile picture.</p>
				<?php endif; ?>
			</div>
			<p id="uploadStatus"></p>
		</div>
	</div>

	<div id="exitWarningModal" class="modal" style="display: none;">
		<div class="modal-content">
			<h2>Exit Current Case</h2>
			<p>Would you like to save your progress before leaving?</p>
			<button id="saveAndExitBtn">Save &amp; Exit</button>
			<button id="exitWithoutSaveBtn">Exit Without Saving</button>
			<button id="cancelExitBtn">Cancel</button>
		</div>
	</div>

<div class="mainContentSection" id="divFullScreen">
  <div id="divMenu">
	<div class="sidebar" id="sidebar">
		<?php
		$currentCase = isset($_SESSION['current_case']) ? $_SESSION['current_case'] : null;
		$baseUrl = $currentCase ? '/' : '/';
		$sidebarItems = [
			'patient' => ['icon' => 'fas fa-bed-pulse', 'text' => 'Patient'],
			'monitors' => ['icon' => 'fas fa-heartbeat', 'text' => 'Monitors'],
			'airway' => ['icon' => 'fas fa-wind', 'text' => 'Airway'],
			'breathing' => ['icon' => 'fas fa-lungs', 'text' => 'Breathing'],
			'drugs' => ['icon' => 'fas fa-syringe', 'text' => 'Drugs'],
			'fluids' => ['icon' => 'fas fa-tint', 'text' => 'Fluids'],
			'labs' => ['icon' => 'fas fa-vials', 'text' => 'Labs'],
			'surgeon' => ['icon' => 'fas fa-user-md', 'text' => 'Surgeon'],
			'resuscitate' => ['icon' => 'fas fa-medkit', 'text' => 'Resuscitate'],
		];
		foreach ($sidebarItems as $key => $item):
		?>
		<a class="sidebar-button sidebar-<?php echo $key; ?>" href="<?php echo $currentCase ? $baseUrl . $key : $baseUrl; ?>">
			<div class="icon-circle"><i class="<?php echo $item['icon']; ?>"></i></div>
			<span><?php echo $item['text']; ?></span>
			<div class="info-show"><b><?php echo $item['text']; ?></b> View and manage <?php echo strtolower($item['text']); ?> information</div>
		</a>
		<?php endforeach; ?>
	</div>
  </div>
	

	<div class="breadcrumbs">
		<a href="/" class="breadcrumbs-item">Home</a>
		<a href="#" class="breadcrumbs-item" id="settings-breadcrumb">Settings</a>
		<a href="#" class="breadcrumbs-item" id="dynamic-breadcrumb"></a>
		<a href="#" class="breadcrumbs-item" id="case-breadcrumb" style="display: none;"></a>
	</div>

	<?php
	require_once 'includes/save_message.php';
	displayFlashMessage();
	?>