<?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 {
    // @todo: Create Enum.
    $allowed_origins = [
      'http://127.0.0.1:8088',
      'http://localhost:8088',
      'https://code.danchadwick.dev',
    ];
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
    // Check if the requester is in our whitelist
    if (in_array($origin, $allowed_origins)) {
      header("Access-Control-Allow-Origin: $origin");
      header("Access-Control-Allow-Credentials: true");
      header("Access-Control-Allow-Methods: GET, POST, 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
    }

    $raw_input = file_get_contents('php://input');
    $json_data = json_decode($raw_input, true) ?? [];
    $path = $json_data['path'] ?? $this->request->post('path');
    $account_id = $json_data['account'] ?? $this->request->post('account');

    if (!$path || !$account_id) {
      // Log what actually arrived to help debugging
      error_log("Missing Data - Path: $path, Account: $account_id. Raw: $raw_input");
      header("HTTP/1.1 422 Unprocessable Entity");
      die("Missing required fields");
    }
    // @todo: validate the account id.
    $entry = [
      'page' => $path,
      'account_id' => $account_id,
      'title' => $json_data['title'] ?? null,
      'user_agent' => $json_data['user_agent'] ?? null,
      'screen_res' => $json_data['screen_res'] ?? null,
      'language' => $json_data['lang'] ?? null,
      'timestamp' => $json_data['ts'] ?? null,
      'referrer' => $json_data['referrer'] ?? null,
      '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);
  }

}
