<?php
// /includes/profile_settings.php

function displayUserSettings($userId) {
    global $pdo;
    
    try {
        $table_name = PREFIX . 'users';
        $stmt = $pdo->prepare("SELECT * FROM $table_name WHERE ID = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_OBJ);

        if (!$user) {
            echo "User not found.";
            return;
        }

        $group_name = '';
		if ($user->group_id) {
			$group_table = PREFIX . 'groups';
			$stmt = $pdo->prepare("SELECT group_name FROM $group_table WHERE id = ?");
			$stmt->execute([$user->group_id]);
			$group_name = $stmt->fetchColumn();
		}

        ?>

        <div class="user-settings">
			<div class="user-settings-top">
				<div class="user-settings-container">
					<h2>User Details</h2>
					<p><strong>Name:</strong> <?php echo htmlspecialchars($user->first_name . ' ' . $user->last_name); ?></p>
					<button id="changeProfileName">Change Profile Name</button>

					<form id="changeNameForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="display:none; margin-top: 10px;">
						<input type="hidden" name="action" value="update_name">
						<input type="text" name="first_name" placeholder="First Name" value="<?php echo htmlspecialchars($user->first_name); ?>" required>
						<input type="text" name="last_name" placeholder="Last Name" value="<?php echo htmlspecialchars($user->last_name); ?>" required>
						<button type="submit">Save</button>
						<button type="button" id="cancelNameButton">Cancel</button>
					</form>
					
					<p><strong>Email:</strong> <?php echo htmlspecialchars($user->user_email); ?></p>
					<p><strong>Joined On:</strong> <?php 
					// echo htmlspecialchars($user->user_registered); 
					echo date("F j, Y", strtotime($user->user_registered)); ?></p>
					<br>
					<p><strong>Group:</strong> <?php echo htmlspecialchars($group_name); ?></p>
					<p><strong>User Type:</strong> <?php echo htmlspecialchars(ucfirst($user->user_type)); ?></p>
					<?php if ($user->is_admin == 1): ?>
						<p><strong>Administrator of:</strong> <?php echo htmlspecialchars($group_name); ?></p>
					<?php endif; ?>
				</div>
				<div class="profile-picture-container">
				<h2>Profile Picture</h2>
					<?php
					$profile_picture_url = getProfilePictureUrl($userId);
					if ($profile_picture_url) {
						echo '<img src="' . htmlspecialchars($profile_picture_url) . '" alt="Profile Picture" class="profile-picture">';
						// echo '<button id="removeProfilePicture">Remove Profile Picture</button>';
					} else {
						echo '<p>No profile picture set.</p>';
					}
					?>
				</div>
				<button id="changeProfilePicture">Change Profile Picture</button>
			</div>
		</div>
        <?php
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}

function generateUniqueId($length = 16) {
    return bin2hex(random_bytes($length / 2));
}

function ensureUniqueId($pdo, $length = 16) {
    $table_name = PREFIX . 'users';
    
    do {
        $unique_id = generateUniqueId($length);
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM $table_name WHERE unique_id = ?");
        $stmt->execute([$unique_id]);
        $exists = $stmt->fetchColumn();
    } while ($exists > 0);

    return $unique_id;
}

function hasProfilePicture($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';
    
    $stmt = $pdo->prepare("SELECT profile_picture FROM $table_name WHERE ID = ?");
    $stmt->execute([$userId]);
    $profile_picture = $stmt->fetchColumn();

    return !empty($profile_picture);
}

function getProfilePictureUrl($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';
    
    $stmt = $pdo->prepare("SELECT unique_id, profile_picture FROM $table_name WHERE ID = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_OBJ);

    if ($user && $user->profile_picture) {
        return "/images/profiles/" . $user->unique_id . "/" . $user->profile_picture;
    }
    
    return ''; // Return empty string if no profile picture is set
}

function handleProfilePictureUpload($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';

    // Check if file was uploaded without errors
    if(isset($_FILES["profile_picture"]) && $_FILES["profile_picture"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["profile_picture"]["name"];
        $filetype = $_FILES["profile_picture"]["type"];
        $filesize = $_FILES["profile_picture"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) {
            return json_encode(["success" => false, "message" => "Error: Please select a valid file format."]);
        }
    
        // Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if($filesize > $maxsize) {
            return json_encode(["success" => false, "message" => "Error: File size is larger than the allowed limit."]);
        }
    
        // Verify MIME type of the file
        if(in_array($filetype, $allowed)){
            // Check if user already has a unique_id
            $stmt = $pdo->prepare("SELECT unique_id FROM $table_name WHERE ID = ?");
            $stmt->execute([$userId]);
            $unique_id = $stmt->fetchColumn();

            if(!$unique_id) {
                $unique_id = generateUniqueId();
                $stmt = $pdo->prepare("UPDATE $table_name SET unique_id = ? WHERE ID = ?");
                $stmt->execute([$unique_id, $userId]);
            }

            // Create user folder if it doesn't exist
            $user_folder = $_SERVER['DOCUMENT_ROOT'] . "/images/profiles/" . $unique_id . "/";
            if (!file_exists($user_folder)) {
                mkdir($user_folder, 0777, true);
            }

            // Generate new filename
            $new_filename = bin2hex(random_bytes(8)) . "." . $ext;

            // Save the file
            if(move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $user_folder . $new_filename)){
                // Update database
                $stmt = $pdo->prepare("UPDATE $table_name SET profile_picture = ? WHERE ID = ?");
                $stmt->execute([$new_filename, $userId]);

                return json_encode([
                    "success" => true, 
                    "message" => "Your profile picture was uploaded successfully.",
                    "newImageUrl" => "/images/profiles/" . $unique_id . "/" . $new_filename,
                    "originalFileName" => $filename  // Add this line to return the original file name
                ]);
            } else {
                return json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
            }
        } else {
            return json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
        }
    } else {
        return json_encode(["success" => false, "message" => "Error: " . $_FILES["profile_picture"]["error"]]);
    }
}

ob_start();

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/* edit user fields */
$userId = $_SESSION['front_user_id'];
$user = getUserDetails($userId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $updateData = [
        'first_name' => $_POST['first_name'],
        'last_name' => $_POST['last_name'],
        'user_email' => $_POST['user_email']
		/*
		'user_login' => $_POST['user_login'],
		'display_name' => $_POST['display_name'],
		'user_nicename' => $_POST['user_nicename'],
		'user_url' => $_POST['user_url']
		*/
    ];

    /*
    if (!empty($_POST['new_password'])) {
        if (changePassword($userId, $_POST['new_password'])) {
            $successMessage .= " Password changed successfully.";
        } else {
            $errorMessage .= " Failed to change password.";
        }
    }
    */
	
    if (updateUserSettings($userId, $updateData)) {
        $_SESSION['success_message'] = "Settings updated successfully!";
    } else {
        $_SESSION['error_message'] = "Failed to update settings.";
    }

    // Refresh user data after update
    $user = getUserDetails($userId);
}

// Display messages if they exist
if (isset($_SESSION['success_message'])) {
    echo "<div class='success-message'>" . htmlspecialchars($_SESSION['success_message']) . "</div>";
    unset($_SESSION['success_message']);
} elseif (isset($_SESSION['error_message'])) {
    echo "<div class='error-message'>" . htmlspecialchars($_SESSION['error_message']) . "</div>";
    unset($_SESSION['error_message']);
}

// Display user settings
displayUserSettings($_SESSION['front_user_id']);

?>

<script src="../js/settings_profile.js" defer></script>

<div class="user-settings-bottom">
	<div class="settings-edit-form">
		<h2>Change Settings</h2>
		<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">

			<div>
				<label for="first_name">First Name:</label>
				<input type="text" id="first_name" name="first_name" value="<?php echo htmlspecialchars($user['first_name']); ?>">
			</div>

			<div>
				<label for="last_name">Last Name:</label>
				<input type="text" id="last_name" name="last_name" value="<?php echo htmlspecialchars($user['last_name']); ?>">
			</div>

			<? /* 
			<div>
				<label for="user_email">Email:</label>
				<input type="email" id="user_email" name="user_email" value="<?php echo htmlspecialchars($user['user_email']); ?>">
			</div>
			
			<div>
				<label for="user_login">Username:</label>
				<input type="text" id="user_login" name="user_login" value="<?php echo htmlspecialchars($user['user_login']); ?>">
			</div>

			<div>
				<label for="display_name">Display Name:</label>
				<input type="text" id="display_name" name="display_name" value="<?php echo htmlspecialchars($user['display_name']); ?>">
			</div>

			<div>
				<label for="user_nicename">Nice Name (for URLs):</label>
				<input type="text" id="user_nicename" name="user_nicename" value="<?php echo htmlspecialchars($user['user_nicename']); ?>">
			</div>

			<div>
				<label for="user_url">Website:</label>
				<input type="url" id="user_url" name="user_url" value="<?php echo htmlspecialchars($user['user_url']); ?>">
			</div>

			<div>
				<label for="new_password">New Password (leave blank to keep current):</label>
				<input type="password" id="new_password" name="new_password">
			</div> */ ?>

			<div>
				<button type="submit">Update Settings</button>
			</div>
		</form>
	</div>
</div>

<?php
// End and flush the output buffer
ob_end_flush();
?>