<?php
require_once __DIR__ . '/../connect.php';

// Get the image file from the request.
$image_file = $_FILES['image'];
$driverID = filterRequest("driverID");

// Define allowed extensions
$allowed_extensions = ['jpg', 'jpeg', 'png'];

// Get the image file from the request.
$image_file = $_FILES['image'];

// Check if the image file was uploaded successfully.
if ($image_file['error'] !== UPLOAD_ERR_OK) {
  echo "Image upload failed";
  exit;
}

// Get file information
$image_name = $image_file['name'];
$image_size = $image_file['size'];
$image_extension = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));

// Validate file extension
if (!in_array($image_extension, $allowed_extensions)) {
  echo "Invalid image format";
  exit;
}

// Generate a unique filename using timestamp and random string
$new_filename = $driverID . '.' . $image_extension;

// Set target directory for uploads
$target_dir = "card_image/";

// Construct target file path
$target_file = $target_dir . $new_filename;

// Move the image file to the target location
if (!move_uploaded_file($image_file['tmp_name'], $target_file)) {
 echo json_encode(array('status' => "Failed to save image")); ;
  exit;
}

// Store additional information (modify based on your needs)
$image_url = $target_dir . $new_filename; // Update if needed
$image_details = [
  "name" => $image_name,
  "size" => $image_size,
  "extension" => $image_extension,
  "url" => $image_url,
];

// Use the image details for further processing (e.g., display, store in database)
// ...

 echo json_encode(array('status' => 'Image uploaded successfully!'));

?>
