<?php
include('config.php');

// check for POST request
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  header("HTTP/1.1 405 Method Not Allowed");
  error_log('FAILED - not POST - '. $_SERVER['REQUEST_METHOD']);
  exit();
}

// get content type
$content_type = isset($_SERVER['CONTENT_TYPE']) ? strtolower(trim($_SERVER['CONTENT_TYPE'])) : '';

if ($content_type != 'application/json') {
  header("HTTP/1.1 403 Forbidden");
  error_log('FAILED - not application/json - '. $content_type);
  exit();
}

// get payload
$payload = trim(file_get_contents("php://input"));

if (empty($payload)) {
  header("HTTP/1.1 403 Forbidden");
  error_log('FAILED - no payload');
  exit();
}

// convert json to array
$decoded = json_decode($payload, true);

// check for json decode errors
if (json_last_error() !== JSON_ERROR_NONE) {
  header("HTTP/1.1 403 Forbidden");
  error_log('FAILED - json decode - '. json_last_error());
  exit();
}

if($decoded['secret'] != $secret_key['pr']) {
  header("HTTP/1.1 403 Forbidden");
  echo("WRONG SECRET");
  error_log('FAILED - wrong secret key');
  exit();
}

//file_put_contents("log.txt", print_r($decoded, true));

$subject = $decoded['repository']['full_name'] 
           . " - PR #" 
           . $decoded['pull_request']['number'] 
           . " (" 
           . $decoded['pull_request']['title'] 
           . ") by " 
           . $decoded['pull_request']['user']['login'];

$message = $decoded['sender']['login'] 
           . " has " . 
           ($decoded['pull_request']['merged'] ? "merged" : $decoded['action'])
           . " the pull request #" .
           $decoded['pull_request']['number']
           . " (" . $decoded['pull_request']['title'] . ") for " .
           $decoded['repository']['full_name']
           . ".\n" .
           $decoded['pull_request']['html_url']
           . "\n\n---\n\nSent to you by gitea_webhooks (https://git.chaospott.de/Chaospott/gitea_webhooks)";


foreach($recipients['pr'] as $recp) {
  mail($recp, $subject, $message, $from);
}
echo("SENT");
?>