<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Process the POST data here
        $next_action = $_POST['next_action'];
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Second Page</title>
</head>
<body>
    <h1>Second Page</h1>
    <p>This page will quickly open a new tab with either window.open or http POST,
       depending on the original page button clicked. And it will then navigate
       back to the main page with either href change or history API</p>

    <script>
        var nextAction = "<?php echo $next_action; ?>";
        console.log('nextAction=' + nextAction);
        if (nextAction.startsWith('postnewtab')) {
           let form = document.createElement("form");
           form.action = "third_page.php";
           form.method = "post";
           form.target = "_blank"; // Open in a new tab
           document.body.appendChild(form);

           setTimeout(() => {
              console.log('Doing form submit to open new tab.');
              form.submit();
              setTimeout(() => {
                 if (nextAction.endsWith('_nav')) {
                    console.log('Use href to go back.');
                    window.location.href = "main_page.html";
                 } else if (nextAction.endsWith('_jump')) {
                    console.log('Use history jump to go back.');
                    history.back();
                 } else {
                    console.log('Instruction for going back is wrong or missing');
                 }
              }, 100);
           }, 100);
        } else if (nextAction.startsWith('opennewtab')) {
           var newTab = window.open('about:blank', '_blank');
           console.log('Doing window open for new tab.');

           setTimeout(function() {
              console.log('Setting href for the new tab.');
              newTab.location.href = "third_page.php";
              setTimeout(() => {
                 if (nextAction.endsWith('_nav')) {
                    console.log('Use href to go back.');
                    window.location.href = "main_page.html";
                 } else if (nextAction.endsWith('_jump')) {
                    console.log('Use history jump to go back.');
                    history.back();
                 } else {
                    console.log('Instruction for going back is wrong or missing');
                 }
              }, 100);
           }, 100);
        } else {
           console.log('Instruction for tab open is wrong or missing');
        }

    </script>
</body>
</html>