<?php

namespace Origo\Controller;

use Origo\Controller\ControllerBase;
use Origo\Controller\ControllerInterface;
use Origo\Services\Database;

class ApiWebhookController extends ControllerBase implements ControllerInterface {

  /**
   * The database service.
   *
   * @var Database
   */
  protected Database $database;

  /**
   * Add common services.
   */
  public function __construct() {
    parent::__construct();
    $this->database = new Database();
  }

  /**
   * Get the response.
   *
   * @return string
   *   The response.
   */
  public function getResponse(): string {
    header('Access-Control-Allow-Origin: *'); // Allow all origins.
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    // Handle preflight OPTIONS request
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
      http_response_code(200);
      exit(); // Stop here - don't process the request
    }
    // Make sure we have a path and account before proceeding.
    $path = $this->request->post('path');
    $account_id = $this->request->post('account');
    if (
      !$path ||
      !$account_id
    ) {
      header("HTTP/1.1 422 Unprocessable Entity");
      die();
    }
    // @todo: validate the account id.
    $entry = [
      'page' => $path,
      'account_id' => $account_id,
      'user_agent' => $this->request->post('user_agent'),
      'referrer' => $this->request->post('referrer'),
      'ip' => $this->request->ip(),
    ];
    $clean_entry = array_filter($entry);
    $keys = array_keys($clean_entry);
    $key_string = implode(',', $keys);
    $placeholders = ':' . implode(', :', $keys);
    $query = $this->database->prepare("INSERT INTO pageviews ($key_string) VALUES ($placeholders)");
    foreach ($clean_entry as $key => $value) {
      $query->bindValue(":$key", $value);
    }
    $success = $query->execute();

    if ($success) {
      $response = [
        "SUCCESS" => "Entry has been stored.",
      ];
      header('Content-Type: application/json');
    }
    else {
      header("HTTP/1.1 422 Unprocessable Entity");
      die();
    }

    return json_encode($response);
  }

}
