<?php
// index.php
// in /Games/Sudoku/
// RJM Programming - December, 2022

 $wel='';

 if (isset($_GET['noaction'])) {
 if (file_exists('./sudoku.htm')) {
   echo file_get_contents('./sudoku.htm');
 } else if (file_exists('./sudoku.html')) {
   echo file_get_contents('./sudoku.html');
 }
 exit;
 } else if (isset($_GET['thegame']) && isset($_GET['random'])) {
 $sofarx=";";
 $thisb="";
 $maxb="";
 $allcontentx=file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'index.php');
 $lcsx=explode('/' . '*', $allcontentx);
 //file_put_contents('azx.azx', '' . sizeof($lcs) . ' ' . $cuda . ';' . $thisset);
 if (sizeof($lcsx) > 1) {
   $collabx=explode('*' . '/', $lcsx[1])[0];
   $linesx=explode("\n", $collabx);
   $thisxset=str_replace('+',' ',urldecode($_GET['thegame'])); //'' . str_replace('(','9',str_replace('*','8',str_replace('&','7',str_replace('^','6',str_replace('$','4',str_replace('#','3',str_replace('@','2',str_replace('!','1',str_replace('1','(',str_replace('2','*',str_replace('3','&',str_replace('4','^',str_replace('6','$',str_replace('7','#',str_replace('8','@',str_replace('9','!',str_replace('+',' ',urldecode($_GET['thegame']))))))))))))))))));
   //$thisxset='' . str_replace('(','9',str_replace('*','8',str_replace('&','7',str_replace('^','6',str_replace('$','4',str_replace('#','3',str_replace('@','2',str_replace('!','1',str_replace('1','(',str_replace('2','*',str_replace('3','&',str_replace('4','^',str_replace('6','$',str_replace('7','#',str_replace('8','@',str_replace('9','!',str_replace('+',' ',urldecode($_GET['thegame']))))))))))))))))));
   $taxbit="";
   for ($ilx=0; $ilx<sizeof($linesx); $ilx++) {
     if ($sofarx == ";") {
       $sofarx.=str_replace('   ',' + ',str_replace('+',' ',urldecode(explode(';', $linesx[$ilx])[1]))) . ';';
     } else if (sizeof(explode(';' . explode(';', $linesx[$ilx])[1] . ';', $sofarx)) == 1) {
       $maxb.=" ";
       $thisb=$maxb;
       $sofarx.=str_replace('   ',' + ',str_replace('+',' ',urldecode(explode(';', $linesx[$ilx])[1]))) . ';';
     } else {
       $rest=explode(';' . explode(';', $linesx[$ilx])[1] . ';', $sofarx)[0];
       $thisb="";
       if ($rest != "") {
         for ($iop=1; $iop<sizeof(explode(';', $rest)); $iop++) {
           $thisb.=" ";
         }
       }
     }
     $parts=explode('' . $thisxset . ';', $linesx[$ilx]);
     if (sizeof($parts) == 2) {
       $taxbit=$thisb . str_replace('   ',' + ',str_replace('+',' ',urldecode($parts[1]))) . "\n" . $taxbit;
     }
   }
   if ($taxbit != "") {
     echo '<html><body onload=" parent.document.getElementById(' . "'toright'" . ').style.display=' . "'table-cell'" . '; parent.document.getElementById(' . "'tais'" . ').value=' . "'" . str_replace("\n","' + String.fromCharCode(10) + '",$taxbit) . "'" . '; "></body></html>'; 
   }
 }
 exit;
 } else if (isset($_GET['startgame'])) {
 $wel="Last chat you contributed was ... Welcome to our Sudoku game!";
 }
 
 $initiator='0';
 if (isset($_GET['startgame'])) {
   $initiator='1';
 } else if (strpos($_SERVER['QUERY_STRING'], 'startgame=') !== false) {
   $initiator='1';
 }
 $changes=false;
 $totallyrellinenum=-1;
 $starth='';
 $jsis="\n<scr" . "ipt type='text/javascript'>
   var tabit='';
   var thenums='';
   var yourname='';
   var amhost=false;
   var lastbofyours='';
   
   function tenminus(instg) {
     var outstg='';
     for (var ih=0; ih<instg.length; ih++) {
       outstg+='' + eval(10 - eval('' + instg.substring(ih).substring(0,1)));
     }
     return outstg;
   }
   
   function aeclick(athis) {
     var orighref=athis.href;
     var aeto=prompt('Please enter email address to invite regarding this Sudoku game collaboration and sharing', '');
     if (aeto == null) { aeto=''; }
     if (aeto.indexOf('@') != -1) {
    var esels=document.getElementsByTagName('select');
    thenums='';
    for (var ejj=0; ejj<esels.length; ejj++) {
      if (('' + esels[ejj].id) != 'smode') {
        thenums+=esels[ejj].getAttribute('data-answer');
      }
    }
      amhost=true;
      document.getElementById('sudokuif').src='./index.php?startgame=' + thenums.substring(0,81);
      athis.href=(athis.href + encodeURIComponent(document.URL.replace('httJUNKps:','http:').split('?')[0].split('#')[0] + '?thegame=' + tenminus(thenums.substring(0,81)))).replace('mailto:?', 'mailto:' + aeto + '?');
      athis.click();
      athis.href=orighref;
     }
   }
   
   function asclick(athis) {
     var orighref=athis.href;
     var aeto=prompt('Please enter SMS number to invite regarding this Sudoku game collaboration and sharing', '');
     if (aeto == null) { aeto=''; }
     //if (aeto.indexOf('@') != -1) {
    var esels=document.getElementsByTagName('select');
    thenums='';
    for (var ejj=0; ejj<esels.length; ejj++) {
      if (('' + esels[ejj].id) != 'smode') {
        thenums+=esels[ejj].getAttribute('data-answer');
      }
    }
      amhost=true;
      document.getElementById('sudokuif').src='./index.php?startgame=' + thenums.substring(0,81);
      athis.href=(athis.href + encodeURIComponent(document.URL.replace('httJUNKps:','http:').split('?')[0].split('#')[0] + '?thegame=' + tenminus(thenums.substring(0,81)))).replace('sms:&', 'sms:' + aeto + '&');
      athis.click();
      athis.href=orighref;
     //}
   }
   
   function iblur(ithis) {
    thenums='';
    var esels=document.getElementsByTagName('select');
    for (var ejj=0; ejj<esels.length; ejj++) {
      if (('' + esels[ejj].id) != 'smode') {
        thenums+=esels[ejj].getAttribute('data-answer');
      }
    }
     if (ithis.value.trim() != '' && eval('' + thenums.length) >= 81) {
      if (yourname == '' && ithis.value.indexOf(':') != -1) {
        yourname=ithis.value.split(':')[0];
      } else if (ithis.value.indexOf(':') != -1) {
        if (ithis.value.split(':')[0].indexOf(' ') == -1) {
          yourname=ithis.value.split(':')[0];
        }
      }
     //alert('yes');
      ithis.value=ithis.value.replace(/\//g,' ').replace(/\*/g,' ').replace(/\;/g,' ').replace(/\\\"/g,' ').replace(/\'/g,' ').replace(/\(/g,'{').replace(/\)/g,'}');
      if (yourname.trim() != '' && ithis.value.indexOf(':') == -1) {
        ithis.value=yourname + ': ' + ithis.value;
      }
      lastbofyours=ithis.value;
      document.getElementById('sudokuif').src='./index.php?thegame=' + tenminus(thenums.substring(0,81)) + '&newmsg=' + encodeURIComponent(ithis.value);
      var hdate=new Date();
      ithis.title='Last chat you contributed at ' + hdate + ' was ... ' + ithis.value.replace(String.fromCharCode(34),String.fromCharCode(39)).replace(String.fromCharCode(34),String.fromCharCode(39)); 
      ithis.value='';
      ithis.placeholder='Optionally chat here (bit before a colon is your name) ... last chat was at ' + hdate;
     } //else {
     //alert('no');
     //}
   }
   
   function tacheck() {
    var esels=document.getElementsByTagName('select');
    thenums='';
    for (var ejj=0; ejj<esels.length; ejj++) {
      if (('' + esels[ejj].id) != 'smode') {
        thenums+=esels[ejj].getAttribute('data-answer');
      }
    }
    if (eval('' + thenums.length) < 81) {
      thenums='';
      setTimeout(tacheck, 3000);
    }
   }
   
   function ifcheck() {
    if (eval('' + thenums.length) >= 81) {
      document.getElementById('sudokuif').src='./index.php?thegame=' + thenums.substring(0,81) + '&random=' + encodeURIComponent(Math.floor(Math.random() * 19878654));
     var vstabit=tabit;
     if (document.getElementById('tais')) {
       vstabit=document.getElementById('tais').value;
       if (vstabit != tabit) {
         document.getElementById('tais').rows='' + vstabit.split(String.fromCharCode(10)).length;
         tabit=vstabit;
         var hhdate=new Date();
         document.getElementById('sudokui').placeholder='Optionally chat here (bit before a colon is your name) ... last chat was at ' + hhdate;
         document.getElementById('sudokui').focus();
         if (document.getElementById('tais').value.split(String.fromCharCode(10))[0].trim() != '') {
         if ((lastbofyours.indexOf(document.getElementById('tais').value.split(String.fromCharCode(10))[0].trim()) != -1 && document.getElementById('tais').value.split(String.fromCharCode(10))[0].trim() != '' && lastbofyours != '') || (amhost && document.getElementById('tais').value.split(String.fromCharCode(10))[0].indexOf('Welcome to our Sudoku game') != -1)) {
         tabit=tabit;
         } else {
         if (yourname.trim() != '' && document.getElementById('tais').value.split(String.fromCharCode(10))[0].indexOf(':') == -1) {
         document.getElementById('notif').src='/HTMLCSS/notifications_ideas.php?scheduledblurb=' + encodeURIComponent(document.getElementById('tais').value.split(String.fromCharCode(10))[0] + ' (' + yourname + ')');
         } else {
         document.getElementById('notif').src='/HTMLCSS/notifications_ideas.php?scheduledblurb=' + encodeURIComponent(document.getElementById('tais').value.split(String.fromCharCode(10))[0]);
         }
         }
         }
       }
     }
    }
   }
      
   setTimeout(tacheck, 3000);
   setInterval(ifcheck, 3000);
</scr" . "ipt>\n";

 function server_remote_addr() {
    global $stfle;
    $rma = $_SERVER['REMOTE_ADDR'];
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    // you can add different browsers with the same way ..
    if(preg_match('/(chromium)[ \/]([\w.]+)/', $ua))
            $rma = '000000'.$rma;
    elseif(preg_match('/(chrome)[ \/]([\w.]+)/', $ua))
            $rma = '00000'.$rma;
    elseif(preg_match('/(safari)[ \/]([\w.]+)/', $ua))
            $rma = '0000'.$rma;
    elseif(preg_match('/(opera)[ \/]([\w.]+)/', $ua))
            $rma = '000'.$rma;
    elseif(preg_match('/(msie)[ \/]([\w.]+)/', $ua))
            $rma = '00'.$rma;
    elseif(preg_match('/(mozilla)[ \/]([\w.]+)/', $ua))
            $rma = '0'.$rma;
    return str_replace(":", "_", $rma);
 }

 while (file_exists('./sudoku.pleasewait')) {
   sleep(1);
 }
 $thisset='youllneverfind' . 'this';
// // file_put_contents('azxpp.azxpp', '' . $_SERVER['QUERY_STRING']);
 if (isset($_GET['thegame'])) {
   $thisset='' . str_replace('(','9',str_replace('*','8',str_replace('&','7',str_replace('^','6',str_replace('$','4',str_replace('#','3',str_replace('@','2',str_replace('!','1',str_replace('1','(',str_replace('2','*',str_replace('3','&',str_replace('4','^',str_replace('6','$',str_replace('7','#',str_replace('8','@',str_replace('9','!',str_replace('+',' ',urldecode($_GET['thegame']))))))))))))))))));
   file_put_contents('./sudoku.pleasewait', $thisset);
 } else if (isset($_GET['startgame'])) {
// //  file_put_contents('azxppp.azxppp', '');
   $initiator='1';
   $thisset='' . str_replace('+',' ',urldecode($_GET['startgame']));
   file_put_contents('./sudoku.pleasewait', $thisset);
   $changes=true;
 } else {
   file_put_contents('./sudoku.pleasewait', 'y');
 }
 $allcontent=file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'index.php');
 $collab='';
 $tabit='';
 $lines=[];
 $rellines=[];
 $leavelines=[];
 $cuda=date('D, d M Y');
 $weare='' . server_remote_addr();
 $lcs=explode('/' . '*', $allcontent);
 //file_put_contents('azx.azx', '' . sizeof($lcs) . ' ' . $cuda . ';' . $thisset);
 if (sizeof($lcs) > 1) {
   $collab=explode('*' . '/', $lcs[1])[0];
   $lines=explode("\n", $collab);
// //  file_put_contents('azxp.azxp', '' . sizeof($lines) . ' ' . $cuda . "\n" . substr($thisset,0,81) . "\n" . $lines[0] . "\n" . $lines[1]);
   for ($il=0; $il<sizeof($lines); $il++) {
     if (trim($lines[$il]) == '') {
       $collab=$collab;
     } else if (strpos($lines[$il], ';' . substr($thisset,0,81) . ';') !== false) {
// //  file_put_contents('azxv.azxv', '' . sizeof($lcs));
       if ($initiator == '0' || (isset($_GET['newmsg']) && strlen($_GET['newmsg']) == 0)) {
// //  file_put_contents('azxw.azxw', '' . sizeof($lcs));
        $tabit=str_replace('   ',' + ',str_replace('+',' ',urldecode(explode(';' . substr($thisset,0,81) . ';', $lines[$il])[1]))) . "\n" . $tabit;
        array_push($leavelines, $lines[$il] . "\n");
        array_push($rellines, $lines[$il] . "\n");
        if (strpos($lines[$il], ';' . $weare . ';') !== false && isset($_GET['newmsg'])) {
         $totallyrellinenum=(-1 + sizeof($leavelines));
         $changes=true;
        } else {
         $changes=true; // new
        }
        //$changes=true; // new
       } else {
// //  file_put_contents('azxx.azxx', '' . sizeof($lcs));
        array_push($leavelines, $lines[$il] . "\n");
        $changes=true;
       }
       // $changes=true; // new
     } else if (strpos($lines[$il], ($cuda . ';')) !== false) {
// //  file_put_contents('azxy.azxy', '' . sizeof($lcs));
       array_push($leavelines, $lines[$il] . "\n");
     } else {
// //  file_put_contents('azxz.azxz', '' . $cuda . ';');
       $changes=true;
     }
   }
 }
 
 if (isset($_GET['newmsg'])) { 
  $changes=true;         
  if (strlen($_GET['newmsg']) > 0) {
    $tabit=str_replace('   ',' + ',str_replace('+',' ',urldecode($_GET['newmsg']))) . "\n" . $tabit; 
  }
 }

 //if (file_exists('./sudoku.htm')) {
 //  echo file_get_contents('./sudoku.htm');
 //} else if (file_exists('./sudoku.html')) {
 //  echo file_get_contents('./sudoku.html');
 //}
 
 if ($changes && sizeof($lcs) > 1) {
   if (file_exists('./sudoku.htm')) {
     $starth=file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'sudoku.htm');
   } else if (file_exists('./sudoku.html')) {
     $starth=file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'sudoku.html');
   }
   $starth=str_replace("<scr" . "ipt type='text/javascript'>", explode("</scr" . "ipt>", $jsis)[0], $starth);
   $jsis="";
   $starth=str_replace('</bo' . 'dy>', '<iframe id=notif src="./index.php?noaction=y" style="display:none;"></iframe><iframe id=sudokuif src="./index.php?noaction=y" style="display:none;"></iframe><a id=aemail style=display:none; target=_blank href="mailto:?subject=Sudoku%20game%20share%20invitation%20link%20&body=">Email</a><a id=asms style=display:none; target=_blank href="sms:&body=Sudoku%20game%20share%20invitation%20link%20">SMS</a>' . $jsis . '</bo' . 'dy>', $starth);
   $starth=str_replace('</t' . 'h><t' . '', '&nbsp;<button title="Email collaboration and sharing" onclick="aeclick(document.getElementById(' . "'" . 'aemail' . "'" . '));">&#128231;</button>&nbsp;<button title="SMS collaboration and sharing" onclick="asclick(document.getElementById(' . "'" . 'asms' . "'" . '));">&#128223;</button>&nbsp;<button style=background-color:yellow; onclick=checksels();>Check My Answers</button>&nbsp;<button style=background-color:orange; onclick="location.href=document.URL;">New Game</button></t' . 'h><t' . '', $starth);
   $starth=str_replace("location.search.split('thegame=')[1] ? decodeURIComponent(", "location.search.split('thegame=')[1] ? tenminus(", $starth);
   if (sizeof($rellines) > 0 || isset($_GET['newmsg'])) {
 //file_put_contents('azxww.azxww', '' . $starth);
     $starth=str_replace('</t' . 'h></t' . 'r', '</t' . 'h><t' . 'h id=toright><input onblur="iblur(this);" type=text placeholder="Optionally chat here (bit before a colon is your name) ..." id=sudokui value=""></input><br><br><textarea id=tais rows=3 cols=80 value="">' . $tabit . '</textarea></t' . 'h></t' . 'r', $starth);
   }
   $sofar=$lcs[0] . '/' . '*' . "\n";
   for ($jl=0; $jl<sizeof($leavelines); $jl++) {
     $sofar.=$leavelines[$jl];
   }
 $initiator='0';
 if (isset($_GET['startgame']) || isset($_GET['newmsg'])) {
   $initiator='1';
// //  file_put_contents('azxxa.azxxa', '' . $totallyrellinenum . ' ... ' . $initiator);
 } else if (strpos($_SERVER['QUERY_STRING'], 'startgame=') !== false) {
   $initiator='1';
 file_put_contents('azxxb.azxxb', '' . $totallyrellinenum . ' ... ' . $initiator);
 }
 //file_put_contents('azxx.azxx', '' . $totallyrellinenum . ' ... ' . $initiator);
   if (isset($_GET['newmsg']) && strlen($_GET['newmsg']) > 0) {
     if (strlen($_GET['newmsg']) > 0) {
     $sofar.=$cuda . ';' . $weare . ';' . substr($thisset,0,81) . ';' . urlencode(str_replace('+',' ',urldecode($_GET['newmsg']))) . "\n" . '*' . '/' . "\n" . '?' . '>';
     }
// //  file_put_contents('azxxf.azxxf', '' . $sofar);
   } else if ($totallyrellinenum >= 0) {
     $sofar.=$cuda . ';' . $weare . ';' . substr($thisset,0,81) . ';' . urlencode(str_replace('+',' ',urldecode($_GET['newmsg']))) . "\n" . '*' . '/' . "\n" . '?' . '>';
        } else if ($initiator != '0' || isset($_GET['startgame'])) {
// //  file_put_contents('azxxcc.azxxcc', '' . $totallyrellinenum . ' ... ' . $initiator);
     $sofar.=$cuda . ';' . $weare . ';' . substr($thisset,0,81) . ';' . urlencode('Welcome to our Sudoku game!') . "\n" . '*' . '/' . "\n" . '?' . '>';
// //  file_put_contents('azxxe.azxxe', '' . $sofar);
   } else if (isset($_GET['newmsg'])) {
     if (strlen($_GET['newmsg']) > 0) {
     $sofar.=$cuda . ';' . $weare . ';' . substr($thisset,0,81) . ';' . urlencode(str_replace('+',' ',urldecode($_GET['newmsg']))) . "\n" . '*' . '/' . "\n" . '?' . '>';
     }
// //  file_put_contents('azxxf.azxxf', '' . $sofar);
   } else {
// //  file_put_contents('azxxff.azxxff', '' . $sofar);
   if (strpos($sofar, '?' . '>') === false) { $sofar.='*' . '/' . "\n" . '?' . '>'; }
   }
   $sofar=str_replace('sudokuif src="./index.php?noaction=y"', 'sudokuif src="./index.php?noaction=y"', $sofar);
// //  file_put_contents('azxxd.azxxd', '' . $sofar);
   $iw=file_put_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'index.php', $sofar);
// //    if ($iw == 0) { file_put_contents('azxxddd.azxxddd', '' . dirname(__FILE__) . DIRECTORY_SEPARATOR . 'index.php');  } else {  file_put_contents('azxxddd.azxxddd', '' . $ix);  }
 } else if (sizeof($lcs) > 1) {
   if (file_exists('./sudoku.htm')) {
     $starth=file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'sudoku.htm');
   } else if (file_exists('./sudoku.html')) {
     $starth=file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'sudoku.html');
   }
   $starth=str_replace("<scr" . "ipt type='text/javascript'>", explode("</scr" . "ipt>", $jsis)[0], $starth);
   $jsis="";
   $starth=str_replace('</bo' . 'dy>', '<iframe id=notif src="./index.php?noaction=y" style="display:none;"></iframe><iframe id=sudokuif src="./index.php?noaction=y" style="display:none;"></iframe><a id=aemail style=display:none; target=_blank href="mailto:?subject=Sudoku%20game%20share%20invitation%20link%20&body=">Email</a><a id=asms style=display:none; target=_blank href="sms:&body=Sudoku%20game%20share%20invitation%20link%20">SMS</a>' . $jsis . '</bo' . 'dy>', $starth);
   $starth=str_replace('</t' . 'h><t' . '', '&nbsp;<button title="Email collaboration and sharing" onclick="aeclick(document.getElementById(' . "'" . 'aemail' . "'" . '));">&#128231;</button>&nbsp;<button title="SMS collaboration and sharing" onclick="asclick(document.getElementById(' . "'" . 'asms' . "'" . '));">&#128223;</button>&nbsp;<button style=background-color:yellow; onclick=checksels();>Check My Answers</button>&nbsp;<button style=background-color:orange; onclick="location.href=document.URL;">New Game</button></t' . 'h><t' . '', $starth);
   $starth=str_replace("location.search.split('thegame=')[1] ? decodeURIComponent(", "location.search.split('thegame=')[1] ? tenminus(", $starth);
   if (sizeof($rellines) > 0) {
 //file_put_contents('azxw.azxw', '' . $starth);
     $starth=str_replace('</t' . 'h></t' . 'r', '</t' . 'h><t' . 'h id=toright><input onblur="iblur(this);" type=text title="' . $wel . '" placeholder="Optionally chat here (bit before a colon is your name) ..." id=sudokui value=""></input><br><br><textarea id=tais rows=3 cols=50 value=""></textarea></t' . 'h></t' . 'r', $starth);
   }
 }

 if ($starth != '') {
   if (isset($_GET['newmsg'])) {
    if (strlen($_GET['newmsg']) > 0) {
     $starth=str_replace('y onload="', 'y onload=" parent.document.getElementById(' . "'tais'" . ').value=' . "'" . str_replace('+',' ',urldecode($_GET['newmsg'])) . "'" . ' + String.fromCharCode(10) + parent.document.getElementById(' . "'tais'" . ').value; ', $starth); 
    } else {
     $starth=str_replace('y onload="', 'y onload=" parent.document.getElementById(' . "'tais'" . ').value=' . "'" . str_replace("\n","' + String.fromCharCode(10) + '",$tabit) . "'" . '; ', $starth); 
    }
   }
   echo $starth;
 } else if (file_exists('./sudoku.htm')) {
   echo file_get_contents('./sudoku.htm');
 } else if (file_exists('./sudoku.html')) {
   echo file_get_contents('./sudoku.html');
 }
 
 if (file_exists('./sudoku.pleasewait')) {
   unlink('./sudoku.pleasewait');
 }
 
 
exit;
/*
*/
?>