<?php error_reporting(E_ALL ^ E_NOTICE);
session_start();

include 'parameters.php';
use Twilio\Rest\Client;
/*
This page sends the API request to Twilio to send SMS to user's provided number, and the user is given is asked to
enter code received on their phone. Some basic error handling is also given using the Javascript function
*/

$phone = $_POST['country_code'] . $_POST['phone_number'];
$temp = $_POST['phone_number'];
$country_code = $_POST['country_code'];
$isTwilio = "false";

//TODO
//FIRST ATTEMPT: TEMP IS 0 and CURRRENT_ATTEMPT IS 0 and RNG IS 550
//FIRST ATTEMPT RERESH: TEMP IS 0 AND CURRENT_ATTEMPT IS 0 and RNG IS 650
//SECOND ATTEMPT: TEMP IS 1 and CURRENT_ATTEMPT IS 1
// if (isset($_POST['attempt'])) {
//     $temp = $_POST['attempt'] + 1;
//     if ($temp == $_SESSION['attempt']) {
//         $temp = 0;
//     }
// } else {
//     $temp = 0;
// }

if (!isset($_SESSION['attempt'])) {
    $temp = 0;
}

if (isset($_POST['key']) && $_POST['key'] == $_SESSION['key']) {
    $temp = 0;
}

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

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

date_default_timezone_set("Asia/Jerusalem");
$last_updated = date("Y-m-d H:i:s");

# checking to see if phone number exists in database in last 1 year, and doesn't exceed 12 allowed mac entries

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://'.$_SERVER['HOST_URL'].'/api/customer/phone?phone='.$phone.'&site='.$_SESSION['site'],
  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);

if (sizeof($result) >= 1) {

  // check mac count; allow if less than 11
  $date_start = date('Y-m-d H:i:s', strtotime('-365 day'));
  
    if (sizeof($result) >= 11) {
      header("Location: multiple_device_error.php");
    } else {
        if ($temp == 0 || $_SESSION['attempt'] == 0) {
            if ($country_code == "+970" || $country_code == "+972") {
            $isTwilio = "false";
            } else {
            $isTwilio = "true";
            }
            $curl = curl_init();
            
            $query = "phone_number=$phone&country_code=$country_code";
            $query = str_replace("+", "%2B",$query);
            
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://'.$_SERVER['HOST_URL'].'/api/customer/sendOtp',
                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 => $query,
                CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded',
                'Accept: application/json'
                ),
            ));
            
            $response = curl_exec($curl);
            curl_close($curl);
        }
    }
} else {
    if ($temp == 0 || $_SESSION['attempt'] == 0) {
        if ($country_code == "+970" || $country_code == "+972") {
            $isTwilio = "false";
        } else {
            $isTwilio = "true";
        }
        $curl = curl_init();

        $query = "phone_number=$phone&country_code=$country_code";
        $query = str_replace("+", "%2B",$query);

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://'.$_SERVER['HOST_URL'].'/api/customer/sendOtp',
            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 => $query,
            CURLOPT_HTTPHEADER => array(
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json'
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
    }
}
$key = rand(10,999);
$_SESSION['key'] = $key;
$_SESSION['attempt'] = $_SESSION['attempt'] + 1;
$_SESSION['phone'] = trim($phone);
$_SESSION['country_code'] = $country_code;
?>

<!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="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="margin_zero" class="content has-text-centered is-size-6">Please enter the 4 digit code</div>
                <div id="margin_zero" class="content has-text-centered is-size-6">received on your provided number</div>
            <form method="post" action="result.php" novalidate>
                <br>
                <div id="gap" class="content is-size-6"></div>
                <div class="field">
                    <div class="control has-icons-left">
                        <input class="input" type="tel" id="code" name="code" placeholder="Code" pattern="[0-9]{4}"style="background-color: #efefef; border-color: #efefef;" required>
                        <input type="hidden" id="isTwillio" name="isTwillio" value="<?php echo $isTwilio; ?>" style="background-color: #efefef; border-color: #efefef;" required>
                        <span class="icon is-small is-left">
                <i class="fas fa-comment"></i>
              </span>
                </div>
                </div>
                <div id="errordiv" style="display:none">
                    <div class="content is-size-7 has-text-centered has-text-danger">
                        Please enter a 4-digit code (via sms)
                    </div>
                    <br>
                </div>
                <div class="buttons is-centered">
                <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;">
                            Verify
                                <i class="fa-solid fa-arrow-right ml-2"></i>
                            </button>
                    </div>
                    <!-- <button id="button_font" class="button is-danger"></button> -->
                </div>
                <br>
            </form>
            <form id="form1" name="form1" method=POST action="verify.php">
                <input name=country_code value="<?php echo $_POST['country_code']; ?>" type="hidden">
                <input name=phone_number value="<?php echo $_POST['phone_number']; ?>"  type="hidden">
                <input name=key value="<?php echo $key; ?>"  type="hidden">
                <input name=attempt value="<?php echo $temp; ?>" type="hidden">
                <input name=current_attempt value="<?php echo $_SESSION['attempt']; ?>" type="hidden">
                <div id="countdown">
                </div>
            </form>
        </div>
        </seection>
    </div>

</div>

<script type="text/javascript">
    var ampt = <?php echo $_SESSION['attempt']; ?>;
    window.onload = function () {
        window.setTimeout(function () {
          document.getElementById("countdown").innerHTML = `<div class="buttons is-centered"><button id="button_font" class="button" style="border-radius: 99px; border-color: black; color: black; font-weight: bold; background-color: white; padding-left: 24px; padding-right: 24px; height: 56px;">Resend OTP</button></div>`;
        }, 31000);
    };
    var timeleft = 30;
    var downloadTimer = setInterval(function () {
        if (timeleft <= 0) {
            clearInterval(downloadTimer);
        } else {
            document.getElementById("countdown").innerHTML = `Resend OTP in `+ timeleft + "s";
        }
        timeleft -= 1;
    }, 1000);
</script>

<script>
    const form  = document.getElementsByTagName('form')[0];
    const code = document.getElementById('code');
    const errorMessage = document.getElementById('errordiv');
    var isTwillio = <?php echo $country_code; ?>;

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

        if (code.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 code field is valid, we let the form submit

        if(!code.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>