prepare(
'SELECT o.id FROM orders o ' .
'JOIN driver_assignments da ON o.id = da.order_id ' .
'WHERE o.id = ? AND da.driver_id = ?'
);
$check_stmt->execute([$order_id, $driver_id]);
$assignment = $check_stmt->fetch();
if (!$assignment) {
header('Location: index.php?error=You are not authorized to update this order.');
exit;
}
// Update the order status
$update_stmt = $pdo->prepare('UPDATE orders SET status = ? WHERE id = ?');
if ($update_stmt->execute([$status, $order_id])) {
// Notify customer by email
require_once __DIR__ . '/../mail/MailService.php';
$user_stmt = $pdo->prepare('SELECT u.email, u.name FROM users u JOIN orders o ON u.id = o.user_id WHERE o.id = ?');
$user_stmt->execute([$order_id]);
$customer = $user_stmt->fetch();
if ($customer) {
$subject = '';
$body = '';
if ($status === 'picked up') {
$subject = 'Your order is on its way!';
$body = 'Hi ' . $customer['name'] . ',
Good news! Your order #' . $order_id . ' has been picked up by your driver and is on its way to you.
Thanks for using Majuro Eats!';
} elseif ($status === 'delivered') {
$subject = 'Your order has been delivered!';
$body = 'Hi ' . $customer['name'] . ',
Your order #' . $order_id . ' has been delivered. We hope you enjoy your meal!
Thanks for using Majuro Eats!';
}
if ($subject && $body) {
MailService::sendMail($customer['email'], $subject, $body, $body);
}
}
header('Location: index.php?success=Order status updated successfully.');
exit;
}
} else {
header('Location: index.php?error=Failed to update order status.');
exit;
}
} catch (PDOException $e) {
header('Location: index.php?error=A database error occurred.');
exit;
}
} else {
header('Location: index.php');
exit;
}
?>