Files
ppr/webhook.php

109 lines
2.9 KiB
PHP

<?php
include("functions.php");
// Database connection details
$servername = "sasaprod.pattinson.org";
$username = "root";
$password = "PugPictureMousePen";
$dbname = "pprdevdb";
$created_by = "webhook-dev";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Webhook payload
#$payload = json_decode(file_get_contents('php://input'), true);
$payload = json_decode(file_get_contents('testhook.json'), true);
// Mapping of JSON 'name' keys to database column names
$columnMapping = [
"Aircraft Registration" => "ac_reg",
"Aircraft Type" => "ac_type",
"Callsign" => "ac_call",
"Captain or PIC Name" => "captain",
"Arriving From" => "in_from",
"ETA" => "eta",
"POB Inbound" => "pob_in",
"Fuel Required" => "fuel",
"Departing To" => "out_to",
"ETD" => "etd",
"POB Outbound" => "pob_out",
"Email" => "email",
"Phone Number" => "phone",
"Additional Information" => "notes"
];
// Prepare the SQL statement dynamically
$columns = [];
$values = [];
$placeholders = [];
$types = '';
$email = '';
$ac_reg = '';
foreach ($payload['data'] as $key => $field) {
$name = $field['name'];
if (isset($columnMapping[$name])) {
$columns[] = $columnMapping[$name];
$value = $field['value'];
// Transform ETA and ETD to MySQL datetime format
if ($name == "ETA" || $name == "ETD") {
$date = DateTime::createFromFormat('d/m/Y H:i', $value);
$value = $date->format('Y-m-d H:i:s');
}
// Handle POB Inbound and POB Outbound as integers
if ($name == "POB Inbound" || $name == "POB Outbound") {
$types .= 'i';
} else {
$types .= 's'; // Assuming all other values are strings
}
$values[] = $value;
$placeholders[] = '?';
// Capture email and aircraft registration for email sending
if ($name == "Email") {
$email = $value;
}
if ($name == "Aircraft Registration") {
$ac_reg = $value;
}
}
}
// Add created_by to the columns, values, and placeholders
$columns[] = 'created_by';
$values[] = $created_by;
$placeholders[] = '?';
$types .= 's';
$sql = "INSERT INTO submitted (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
$stmt = $conn->prepare($sql);
// Bind parameters dynamically
$stmt->bind_param($types, ...$values);
// Execute the statement
if ($stmt->execute()) {
echo "New record created successfully";
$lastId = $stmt->insert_id;
if (!empty($email)) {
generatePprEmail($lastId, $email, $ac_reg);
} else {
echo "Email is not set.";
}
} else {
echo "Error: " . $stmt->error;
}
// Close the connection
$stmt->close();
$conn->close();
?>