Files
ppr/webhook.php
2025-03-13 18:11:19 +00:00

104 lines
2.7 KiB
PHP

<?php
include("functions.php");
$created_by = "Website (DEV)";
$conn = connectDb();
// Check if the URL has a 'test' parameter set
if (isset($_GET['test'])) {
$payload = json_decode(file_get_contents('testhook.json'), true);
} else {
$payload = json_decode(file_get_contents('php://input'), true);
}
// Log the received payload for debugging
error_log("Received payload: " . print_r($payload, 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()) {
error_log("New record created successfully");
$lastId = $stmt->insert_id;
if (!empty($email)) {
generatePprEmail($lastId, $email, $ac_reg);
} else {
error_log("Email is not set.");
}
} else {
error_log("Error: " . $stmt->error);
}
// Close the connection
$stmt->close();
$conn->close();
?>