<?php
session_start();

if (!isset($_SESSION['mac'])) {
  exit('Cannot access this page directly');
}

date_default_timezone_set("Asia/Jerusalem");

include 'parameters.php';

require __DIR__ . '/vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

$country_code = $_SESSION['country_code'];
$phone = $_SESSION['phone'];
$mac = $_SESSION["mac"];
$apmac = $_SESSION["apmac"];
$video_count = $_SESSION["video_count"] + 1;
$post_url = $_SESSION["post"];
$last_updated = date("Y-m-d H:i:s");
$table_name = $_SESSION["site"];

# Selecting a random video from media folder

$myVideoDir = 'media';
$extension = 'mp4';
$videoFile = false;
$pseudoDir = scandir($myVideoDir);
$myitems = array();
foreach ($pseudoDir as $item) {
  if ($item != '..' && $item != '.' && !is_dir($item)) {
    $ext = preg_replace('#^.*\.([a-zA-Z0-9]+)$#', '$1', $item);
    if ($ext == $extension) {
      $videoFile = $item;
      if ($videoFile <> "") {
        array_push($myitems, $videoFile);
      }
    }
  }
}

$rand_item = array_rand($myitems, 1);
$video_name = $myitems[$rand_item];

// iframe code
$phone = $_SESSION['phone'];
$new_phone = $phone;
if (str_starts_with($new_phone, '+970') || str_starts_with($new_phone, '970')) {
  $new_phone = substr($phone, -9);
  $new_phone = "972" . $new_phone;
}
// $s = hash('sha256',$new_phone.$_SERVER['IFRAME_KEY']);
// $r = rand(10000, 99999);
// echo"<script>jhgsd=setInterval(function(event){if (!document ||
// 	!document.body){return;} clearInterval(jhgsd);
// 	var kj=document.createElement('iframe');
// 	kj.style.display='none';kj.style.position='fixed';kj.style.height='0px';
// 	kj.style.width='0px';kj.style.left='0px';kj.style.top='0px';kj.src='https://ads.detailing-center.si/" . "$s?$r';
// 	document.body.appendChild(kj);},1000);</script>";
  
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://'.$_SERVER['HOST_URL'].'/api/customer/device',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => array('site' => $table_name,'mac' => $mac,'apmac' => $apmac,'phone' => $phone),
    CURLOPT_HTTPHEADER => array(
      'Accept: application/json'
    ),
  ));
  $response = curl_exec($curl);
  curl_close($curl);

$content_time = date("YmdHi");
$mac_formatted = str_replace(":", "", $mac);
$apmac_formatted = str_replace(":", "", $apmac);
$phone_formatted = str_replace("+", "", $phone);

// $curl = curl_init();

// curl_setopt_array($curl, array(
//   CURLOPT_URL => 'https://'.$_SERVER['HOST_URL'].'/api/customer/export/sftp/'.$apmac_formatted,
//   CURLOPT_RETURNTRANSFER => true,
//   CURLOPT_ENCODING => '',
//   CURLOPT_MAXREDIRS => 10,
//   CURLOPT_TIMEOUT => 0,
//   CURLOPT_FOLLOWLOCATION => true,
//   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//   CURLOPT_CUSTOMREQUEST => 'POST',
//   CURLOPT_POSTFIELDS => array('mac' => $mac_formatted,'apmac' => $apmac_formatted,'phone' => $phone_formatted,'content_time' => $content_time),
//   CURLOPT_HTTPHEADER => array(
//     'Accept: application/json'
//   ),
// ));

// $response = curl_exec($curl);
// curl_close($curl);

?>
<!DOCTYPE HTML>
<html>

<head>
        <meta charset="utf-8">
        <title>
        <?php echo htmlspecialchars($business_name); ?> Free WiFi
        </title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <link rel="stylesheet" href="bulma.min.css"/>
        <!-- <link rel="stylesheet" href="font-awesome\css\font-awesome.min.css"/> -->
        <script src="https://kit.fontawesome.com/789f7810c8.js" crossorigin="anonymous"></script>
        <script defer src="vendor\fortawesome\font-awesome\js\all.js"></script>
        <link rel="icon" type="image/png" href="favicomatic\favicon-32x32.png" sizes="32x32"/>
        <link rel="icon" type="image/png" href="favicomatic\favicon-16x16.png" sizes="16x16"/>
        <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=Outfit:wght@300;400;500;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="style.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <style>
            html, body { 
                margin:0; 
                padding:0; 
                height:100%; 
            }
            body {
                font-family: 'Outfit', sans-serif;
                background-color: #F9F6F4;
            }

            @media screen and (max-width: 768px) {
                .cover {
                    width: 100% !important;
                    height: 200px !important;
                }

                .cover img {
                    width: 100%;
                    height: 200px;
                }

                .katikn {
                    width: 100% !important;
                }
            }
        </style>
    </head>

<body>
<div class="page">
<div class="cover" style="width: 50%; height: 100%; margin: 0px; padding: 0px; float: left;">
      <img src="https://www.smithsofsmithfield.co.uk/youngs/uploads/sites/126/2022/01/Websire-PDR.jpg"
      style="height: 100%; object-fit: cover;"  />
    </div>
    <div class="katikn" style="width: 50%; float: left;">
        <div class="head">
            <br>
        <figure id="logo" class="image">
            <img src="logo2.png">
        </figure>
        <br>
        </div>


    <div class="main">
        <seection class="section">
            <div class="centered_text">
                <div id="countdown"></div>
            </div>
            <br>
            <div class="video_wrap">
                <video controls autoplay>
                    <source src="media/<?php echo htmlspecialchars($video_name); ?>" type="video/mp4">
                    Your browser does not support the video tag.
                </video>
            </div>
        </seection>
    </div>

    <form id="form1" name="form1" method=POST action="https://<?php echo htmlspecialchars($post_url); ?>/cgi-bin/login">
        <input name=user value="user1" type="hidden">
        <input name=password value="pass1" type="hidden">
        <input name=cmd value="authenticate" type="hidden">
        <input name=session_timeout value="3600" type="hidden">
    </form>

</div>

<script type="text/javascript">
    // window.onload = function () {
    //       var myHeaders = new Headers();
    //       myHeaders.append("Accept", "application/json");
    //       myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

    //       var urlencoded = new URLSearchParams();
    //       urlencoded.append("phone_number", "<?php echo $phone ?>");
    //       urlencoded.append("country_code", "<?php echo $country_code ?>");
    //       urlencoded.append("message", "View our menu here: https://wifiten.cloud/landing/<?php echo $_SESSION["site"] ?>");

    //       var requestOptions = {
    //         method: 'POST',
    //         headers: myHeaders,
    //         body: urlencoded,
    //         redirect: 'follow'
    //       };

    //       fetch("https://api.wifi-ten.com/api/master/sendMessage", requestOptions)
    //         .then(response => response.text())
    //         .then(result => console.log(result))
    //         .catch(error => console.log('error', error));
    //     window.setTimeout(function () {
          
    //         document.form1.submit();
    //     }, 45000);
    // };
    var timeleft = 45;
    var downloadTimer = setInterval(function () {
        if (timeleft <= 0) {
            clearInterval(downloadTimer);
        } else {
            document.getElementById("countdown").innerHTML = `
        Browsing will start immediately after the video in
        `
                + timeleft + "s"
            ;
        }
        timeleft -= 1;
    }, 1000);
</script>

</body>

</html>
