<?php
header('Content-type: text/html; charset=utf-8');

define('REPLY_SECRET', 'UKtVMine3X5tGLbb');
$dbDsn = 'sqlite:/home/itasapp/reply.support/db/reply-itas.sqlite';
$actionDelay = 30;

function overflow32($v)
{
    $v = $v % 4294967296;
    if ($v > 2147483647) return $v - 4294967296;
    elseif ($v < -2147483648) return $v + 4294967296;
    else return $v;
}

function hashCode( $s )
{
    $h = 0;
    $len = strlen($s);
    for($i = 0; $i < $len; $i++)
    {
        $h = overflow32(31 * $h + ord($s[$i]));
    }

    return $h;
}

$iprocId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
$action = $_GET['action'];
$hash = $_GET['hash'];
$callerIp = $_SERVER['REMOTE_ADDR'];
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $callerIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
}

function validateHash($id, $action, $hash)
{
    $payload = join('|', [
                            REPLY_SECRET,
                            $id,
                            $action,
                         ]);

    $hashedPayload = hashCode($payload);

    if ($hash != $hashedPayload) {
        // echo $hashedPayload . "\n";
        throw new Exception('Invalid hash');
    }
}

function checkRecentActivity($db, $id, $delay)
{
    // kontrola, jestli v nedavne dobe doslo ke kliknuti na odkaz
    $query = 'SELECT COUNT(id) FROM replies WHERE id = :id AND timestamp > strftime("%s", "now") - :delay';
    $sth = $db->prepare($query);
    $sth->bindValue(':id', $id, PDO::PARAM_INT);
    $sth->bindValue(':delay', $delay, PDO::PARAM_INT);

    $recentActivity = 0;
    if ($sth->execute()) {
        $recentActivity  = $sth->fetchColumn();
    }

    if ($recentActivity > 0) {
        throw new \Exception('Recent reply already exists for this id');
    }
}

function storeActivity($db, $id, $action, $callerIp)
{
    // zaznam aktivity

    $query = 'INSERT INTO replies(timestamp, id, action, caller) VALUES (strftime("%s", "now"), :id, :action, :caller) ';
    $sth = $db->prepare($query);
    $sth->bindValue(':id', $id, PDO::PARAM_INT);
    $sth->bindValue(':action', $action, PDO::PARAM_STR);
    $sth->bindValue(':caller', $callerIp, PDO::PARAM_STR);
    $sth->execute();
}

function sendReplyEmail($id, $action, $callerIp)
{
    $supportEmail = 'support@neit.group';
    // $supportEmail = 'lukas.zita@neit.eu';
    $sender = 'robot@reply.support.itas.app';
    // $subject = '#TEST# ||' . $id . '||' . $action . '||';
    $subject = '#ITAS_REPLY1# ||' . $id . '||' . $action . '||';
    $headers = 'From: ' . $sender ."\n" . 'Reply-To: ' . $sender . "\n". 'Conent-type: text/plain; charset="UTF-8"' . "\n";
    $parameters = '-f ' . $sender;

    $body = 'Activation from link ' . $_SERVER['REQUEST_SCHEME'] . '://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $body.= "\n";
    $body.= "\n";
    $body.= 'Link clicked from IP ' . $callerIp . ' on ' . strftime('%c');

    if (!mail($supportEmail, $subject, $body, $headers, $parameters)) {
        throw new \Exception('Activation error');
    }
}

?>
<html>
    <style>
      body {
        text-align: center;
        padding: 40px 0;
        background: #EBF0F5;
      }
        h1 {
          font-family: system-ui;
          font-weight: 900;
          font-size: 30px;
          margin-bottom: 10px;
        }
        p {
          color: #111827;
          font-family: system-ui;
          font-size:18px;
          line-height: 2rem;
          margin: 0;
        }
      i {
        font-size: 40px;
        line-height: 100px;
        font-style: normal;
        font-family: system-ui;
      }
      .success {
        color: #88B04B;
      }
      .fail {
        color: #B0404B;
      }
      .card {
        background: white;
        padding: 60px;
        border-radius: 16px;
        box-shadow: 0 2px 3px #EFF3F4;
        display: inline-block;
        margin: 0 auto;
        min-width: 30%;
        max-width: 60%
      }
    </style>
    <body>
      <div class="card">

<?php
try {
    if ($iprocId === false || $iprocId <= 0) {
        throw new \Exception('Invalid id');
    }

    if (!in_array($action, ['accept', 'reject'])) {
        throw new \Exception('Unknown method');
    }

    validateHash($iprocId, $action, $hash);

    $db = new \PDO($dbDsn, '', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

    checkRecentActivity($db, $iprocId, $actionDelay);

    error_log('Activating ' . $action . ' on id ' . $iprocId);
    sendReplyEmail($iprocId, $action, $callerIp);

    storeActivity($db, $iprocId, $action, $callerIp);
?>
      <div style="border-radius:100px; height:100px; width:100px; background: #F8FAF5; margin:0 auto;">
        <i class="checkmark success">✓</i>
        </div>
        <h1 class="success">Vaše volba byla zaznamenána</h1> 
        <p>Brzo obdržíte e-mail, v němž najdete odkaz na váš iTAS.<br>Prosíme o chvíli trpělivosti.</p></br></br><br>
        <img alt="iTAS" height="53px" src="https://admin.itas.app/assets/logos/itas_logo.png" style="height: 53px;border:0;outline:none;text-decoration:none;text-align:center" title="iTAS" />
      </div>
<?php
} catch (\Exception $e) {
?>
      <div style="border-radius:100px; height:100px; width:100px; background: #F8FAF5; margin:0 auto;">
        <i class="checkmark fail">x</i>
        </div>
        <h1 class="fail">Chyba</h1> 
        <p><?php echo $e->getMessage(); ?></p></br></br><br>
        <img alt="iTAS" height="53px" src="https://admin.itas.app/assets/logos/itas_logo.png" style="height: 53px;border:0;outline:none;text-decoration:none;text-align:center" title="iTAS" />
      </div>
<?php
}
?>

    </body>
</html>
