<?php
session_start();

require("../includes/db_connect.php");

if (isset($_SESSION['usr_email']) && isset($_SESSION['usr_accessToken']) && isset($_SESSION['usr_accountId']) && (!empty($_SESSION['usr_accountId']))) {
  header('Location: ../user/account');
  exit();
} else if (!isset($_GET['accountId']) || !isset($_GET['token']) || !isset($_GET['email'])) {
  header('Location: ../login');
  exit();
} else {

  $accountId = $_GET['accountId'];
  $email = $_GET['email'];
  $token = $_GET['token'];

  $usr_sql = "SELECT * FROM users WHERE accountId =? AND email =? AND access_token =? LIMIT 1";
  $usr_sth = $conn->prepare($usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
  $usr_sth->execute([$accountId, $email, $token]);
  $users = $usr_sth->fetchAll();

  if (count($users) > 0) {

    foreach ($users as $key => $value) {
      $accountId = $value['accountId'];
      $email_confirmation = $value['email_confirmation'];
      $email_date = $value['email_date'];

      if ($email_confirmation == 0) {

        $datetime1 = new DateTime(convertDate($email_date));

        $datetime2 = new DateTime(convertDate(date('Y-m-d H:i:s')));

        $difference = $datetime1->diff($datetime2);

        $minutes_lapsed =  $difference->i;

        if ($minutes_lapsed < 11) {

          $user_sql = "UPDATE users SET access_token=?, email_confirmation=? WHERE accountId=?";

          $update_user = $conn->prepare($user_sql)->execute([0, 1, $accountId]);

          if ($update_user) {
            //send_welcome_mail();
          } else {
            die("Unable to activate your account. Please try again.");
          }
        } else {
          die("This link has expired.");
        }
      } else {
        die("Email already confirmed. You can now login <a href='https://rocketta.io/login'>here<a/>");
      }
    }
  } else {
    die("Invalid request.");
  }
}

function send_welcome_mail () {
  global $accountId, $email;

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, "accountId=$accountId&email=$email");
  curl_setopt($ch, CURLOPT_URL, 'https://rocketta.io/email/send_welcome_email');
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
  curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10); 
  curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
  curl_exec($ch);
  curl_close($ch);
}

function convertDate($date)
{
  $dt = str_replace('/', '-', $date);

  return date('Y-m-d H:i:s', strtotime($dt));
}


?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Account Activation</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Language" content="en">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta property="og:type" content="website" />
    <meta content="summary_large_image" name="twitter:card" />
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <meta name="msapplication-TileColor" content="#0e4656">
    <meta name="theme-color" content="#ffffff">
    <meta name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, shrink-to-fit=no" />
    <meta name="msapplication-tap-highlight" content="no">
    <link href="../img/favicon.png" rel="shortcut icon" type="image/x-icon" />
    <!-- Custom CSS -->
    <link href="../assets/css/style.min.css" rel="stylesheet" />

    <script type="text/javascript">
    function delayedRedirect() {
        window.location.href = "../login";
    }
    </script>
</head>

<body onLoad="setTimeout('delayedRedirect()', 3000)"
    style="text-align: center;background-color:#fff; height: 100%; width: 100%;  display: flex; justify-content: center; align-items: center; min-height: 100vh;">
    <!-- END SEND MAIL SCRIPT -->

    <div id="success">
        <div class="icon icon--order-success svg">
            <svg xmlns="http://www.w3.org/2000/svg" width="72px" height="72px">
                <g fill="none" stroke="#0000a2" stroke-width="2">
                    <circle cx="36" cy="36" r="35" style="stroke-dasharray:240px, 240px; stroke-dashoffset: 480px;">
                    </circle>
                    <path d="M17.417,37.778l9.93,9.909l25.444-25.393"
                        style="stroke-dasharray:50px, 50px; stroke-dashoffset: 0px;"></path>
                </g>
            </svg>
        </div>
        <h4 style="margin-top: 20px;font-family: arial; line-height: 28px;color: #514d6a;"><span>Account activated
                successfully!</span>
        </h4>
        <small style="font-size: 14px;font-family: arial; line-height: 28px;color: #514d6a;">Redirecting you
            back...</small>
    </div>
</body>

</html>