<?php

include 'door-settings.php';

if (!isset($_REQUEST['verify'])) die("Please send the verification code");
$verify = intval($_REQUEST['verify']);

if (!isset($_REQUEST['door_id'])) die("Please send a door id");

$id = intval($_REQUEST['door_id']);
if ($id < 1 || $id > NUM_DOORS) die("Invalid door id $id");

$request = file_get_contents("request$id");

if ($request === false) die("Invalid request");

$lines = explode("\n", $request);
if (count($lines) < 4) die("Malformed request");

//file_put_contents($request_file, "$ip\n$time\n$verify\n$status");
$ip = $lines[0];
$time = intval($lines[1]);
$real_verify = intval($lines[2]);
$status = intval($lines[3]);

$time_diff = time() - $time;
if ($time_diff < 0 || $time_diff > 10) die("Request expired");

if ($ip != $_SERVER['HTTP_X_REAL_IP']) die("Not your request");

if ($status != 0 && $status != 1) die("Malformed status");

if ($verify != $real_verify) die("Unauthorized request");

file_put_contents("door$id", "$status");
