<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/connect.php'; // Ensure this is correct and contains the connection logic

// Get the audio file from the request
$audio_file = $_FILES['audio'];
$passengerId = filterRequest("passengerId"); // Ensure this is defined correctly

// Check if the audio file was uploaded successfully
if ($audio_file['error'] !== UPLOAD_ERR_OK) {
    error_log("File upload error: " . $audio_file['error']);
    echo json_encode(array('status' => 'The audio file was not uploaded successfully.'));
    exit;
}

// Get the file name and extension of the audio file
$audio_name = $audio_file['name'];
$audio_extension = pathinfo($audio_name, PATHINFO_EXTENSION);

// Check if the audio file is a valid audio format
if (!in_array($audio_extension, array('m4a', 'mp3', 'wav'))) {
    echo json_encode(array('status' => 'The audio file is not a valid format.'));
    exit;
}

// MIME Type validation using finfo
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $audio_file['tmp_name']);
finfo_close($finfo);

$allowed_mime_types = ['audio/mp4', 'audio/mpeg', 'audio/wav', 'audio/x-m4a'];
if (!in_array($mime_type, $allowed_mime_types)) {
    echo json_encode(array('status' => 'The audio file is not a valid format (MIME mismatch).'));
    exit;
}

// Generate a new filename using the passenger ID to avoid conflicts
$new_filename = $audio_name . '.' . $audio_extension;

// Move the audio file to the uploads directory with the new filename
$target_dir = "upload_audio/";
if (!is_dir($target_dir)) {
    mkdir($target_dir, 0755, true); // Create directory if it doesn't exist
}
$target_file = $target_dir . $new_filename;
if (!move_uploaded_file($audio_file['tmp_name'], $target_file)) {
    error_log("Failed to move file to target directory: " . print_r($audio_file, true));
    echo json_encode(array('status' => 'Failed to move the audio file.'));
    exit;
}

// Construct the link to the uploaded audio file dynamically
$host = $_SERVER['HTTP_HOST'] ?? 'api.siromove.com';
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$base_url = "$protocol://$host/siro/upload_audio/";
$linkAudio = $base_url . $new_filename;


// Respond with success and the audio file link
echo json_encode(array('status' => 'Audio file uploaded successfully.', 'link' => $linkAudio));

// Close the database connection if it was established
if (isset($conn)) {
    mysqli_close($conn);
}
?>