<?php
  session_start();
  if (!isset($_SESSION['authenticated'])) {
    header("Location: /");
  }

  $cookie_key = 'Ab9pb7J66VniFdyg+ffBIBHWqSHM';
  $cookie_name = 'Applicants';
  $cookie_exp = time() + (86400 * 30);
  $cookie_loc = '/';

  $al = isset($_COOKIE[$cookie_name])
    ? deserialize_queue($_COOKIE[$cookie_name])
    : new ApplicantQueue();

  switch($_GET['action']) {
    case 'add':
      if (!isset($_POST['applicant-name'])) {
        badRequestAndDie();
      }

      $applicant = htmlspecialchars(strip_tags($_POST['applicant-name']));
      $al->addApplicant($applicant);

      setcookie($cookie_name, serialize_queue($al), $cookie_exp, $cookie_loc);
      break;

    case 'remove':
      if (isset($_POST['applicant-name'])) {
        $applicant = htmlspecialchars(strip_tags($_POST['applicant-name']));
        $al->removeApplicantByName($applicant);
      } else if (isset($_POST['applicant-index'])) {
        $al->removeApplicantByIndex($_POST['applicant-index']);
      } else {
        badRequestAndDie();
      }

      setcookie($cookie_name, serialize_queue($al), $cookie_exp, $cookie_loc);
      break;

    default:
  }

  echo $al->getApplicants();

  /******************************************
  ***************** Functions ***************
  ******************************************/

  function get_iv($secret) {
    return substr(hash('sha256', $secret), 0, 16);
  }

  function serialize_queue($queue) {
    return base64_encode(openssl_encrypt(serialize($queue), 'AES-256-CBC', $cookie_key, 0, get_iv($cookie_name)));
  }

  function deserialize_queue($queue) {
    return unserialize(openssl_decrypt(base64_decode($queue), 'AES-256-CBC', $cookie_key, 0, get_iv($cookie_name)));
  }

  function badRequestAndDie() {
    header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request");
    echo "<h2><b>400 - Bad Request</b></h2>";
    die();
  }

  function isApplicantEmpty($applicant) {
    if (strlen(trim($applicant)) > 0) {
      return true;
    } else {
      return false;
    }
  }

  /*****************************************
  ********* ApplicantQueue Class ***********
  *****************************************/

  class ApplicantQueue {
    public $applicants = [];
    private $filter = 'isApplicantEmpty';

    function addApplicant($applicant) {
      if (strlen(trim($applicant)) > 0) {
        array_push($this->applicants, $applicant);
      }
      return $this->getApplicants;
    }

    function removeApplicantByIndex($index) {
      if ($index < count($this->applicants)) {
        array_splice($this->applicants, $index, 1);
      }
    }

    function removeApplicantByName($applicant) {
      $index = array_search($applicant, $this->applicants);
      if ($index) {
        array_splice($this->applicants, $index, 1);
      }
      return $this->getApplicants();
    }

    function getApplicants() {
      return json_encode(
        array_filter($this->applicants, $this->filter)
      );
    }
  }

?>