<?php
session_start();

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

include 'parameters.php';

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

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

$_SESSION["mac"] = $_GET['mac'];
$_SESSION["ip"] = $_GET['ip'];
$_SESSION["apmac"] = $_GET['apmac'];
$_SESSION["post"] = $_GET['post'];
$_SESSION["site"] = $_GET['site'];
$_SESSION["video_count"] = 0;
$_SESSION["user_type"] = "new";
$_SESSION['attempt'] = 0;

//Call API TO SEE IF USER EXISTS OR NOT
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://".$_SERVER['HOST_URL']."/api/customer/find?mac=$_SESSION[mac]",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json'
  ),
));

$response = curl_exec($curl);
curl_close($curl);
$result = json_decode($response, true);

if ($result && sizeof($result) >= 1) {
    if (isset($result[0])) {
        $_SESSION["phone"] = $result[0]['user']['phone'];
        $_SESSION["video_count"] = $result[0]['video_count'];
        $_SESSION["user_type"] = "repeat";
        $date_old = $result[array_key_last($result)]['updated_at'];

        date_default_timezone_set("Asia/Jerusalem");
        $date_now = date('Y-m-d H:i:s');
        $date_diff = abs(strtotime($date_now) - strtotime($date_old)) / 60;
        if ($date_diff < 60) {
            header("Location: direct_connect.php");
        } else {
            header("Location: connect.php");
        }
    } else {
        error_log("Here is the problematic result: " . implode(" ",$result));
    }
}

?>
<!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>
    </head>
    <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>
<body>
    <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="container">

                    
                    <h3 id="login" class="title is-3">WiFi Connect</h3>
                    <div id="login" class="content is-size-6">
                        Enter the following details to use network connection.
                    </div>
                    <div id="gap" class="content is-size-6"></div>
                    <form method="post" id="phone_form" action="verify.php" novalidate>

                        <div id="phone_field" class="field has-addons ">
                            <p class="control">
                            <span class="select">
                            <select id="country_code" name="country_code" style="background-color: #efefef; border-color: #efefef;">
                                <option value="+44">(GB) +44</option>
                                <option value="+33">(FR) +33</option>
                                <option value="+92">(PK) +92</option>
                            </select>
                            </span>
                            </p>

                            <p class="control">
                                <input class="input" type="tel" name="phone_number" id="phone_number"
                                    placeholder="Phone Number" style="background-color: #efefef; border-color: #efefef;" pattern="[0-9]{10}" required>
                            </p>
                        </div>
                        <br>
                        <div id="errordiv" style="display:none">
                            <div class="content is-size-7 has-text-centered has-text-danger">
                                You entered an incorrect number, please enter a phone number, 10 digits, without special
                                characters
                            </div>
                        </div>
                        <div class="buttons">
                            <button class="button" style="border-radius: 99px; border-color: black; color: white; font-weight: bold; background-color: black; padding-left: 24px; padding-right: 24px; height: 56px;">
                                NEXT
                                <i class="fa-solid fa-arrow-right ml-2"></i>
                            </button>
                        </div>
                    </form>
                </div>
            </seection>
        </div>
    </div>

    <script>
        const form = document.getElementsByTagName('form')[0];
        const phone = document.getElementById('phone_number');
        const errorMessage = document.getElementById('errordiv');

        phone.addEventListener('input', function (event) {
            // Each time the user types something, we check if the
            // form fields are valid.

            if (phone.validity.valid) {
                // In case there is an error message visible, if the field
                // is valid, we remove the error message.
                errorMessage.style.display = "none";
            } else {
                // If there is still an error, show the correct error
                showError();
            }
        });

        form.addEventListener('submit', function (event) {
            // if the phone field is valid, we let the form submit

            if (!phone.validity.valid) {
                // If it isn't, we display an appropriate error message
                showError();
                // Then we prevent the form from being sent by canceling the event
                event.preventDefault();
            }
        });

        function showError() {
            // Set the styling appropriately
            errorMessage.style.display = "block";
        }
    </script>
</body>
</html>
