36716-vm/decline-booking.php
2025-12-07 05:00:42 +00:00

70 lines
2.5 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
require_once 'mail/MailService.php';
require_once 'stripe/init.php';
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'coach') {
header('Location: login.php');
exit;
}
if (!isset($_GET['id'])) {
header('Location: dashboard.php');
exit;
}
$booking_id = $_GET['id'];
$coach_id = $_SESSION['user_id'];
// Verify the booking belongs to the coach
$stmt = db()->prepare("SELECT * FROM bookings WHERE id = ? AND coach_id = ?");
$stmt->execute([$booking_id, $coach_id]);
$booking = $stmt->fetch();
if ($booking) {
if (!empty($booking['stripe_payment_intent_id'])) {
try {
$refund = \Stripe\Refund::create([
'payment_intent' => $booking['stripe_payment_intent_id'],
]);
if ($refund->status == 'succeeded') {
$stmt = db()->prepare("UPDATE bookings SET status = 'declined', payment_status = 'refunded' WHERE id = ?");
$stmt->execute([$booking_id]);
} else {
header('Location: dashboard.php?status=error');
exit;
}
} catch (\Stripe\Exception\ApiErrorException $e) {
error_log('Stripe API error: ' . $e->getMessage());
header('Location: dashboard.php?status=error');
exit;
}
} else {
$stmt = db()->prepare("UPDATE bookings SET status = 'declined' WHERE id = ?");
$stmt->execute([$booking_id]);
}
// Notify client
$stmt = db()->prepare("SELECT c.email, c.name as client_name, co.name as coach_name, b.booking_time FROM bookings b JOIN clients c ON b.client_id = c.id JOIN coaches co ON b.coach_id = co.id WHERE b.id = ?");
$stmt->execute([$booking_id]);
$booking_details = $stmt->fetch();
if ($booking_details) {
$to = $booking_details['email'];
$subject = 'Booking Declined and Refunded';
$body = "<p>Hello " . htmlspecialchars($booking_details['client_name']) . ",</p>";
$body .= "<p>We are sorry to inform you that your booking with " . htmlspecialchars($booking_details['coach_name']) . " on " . htmlspecialchars(date('F j, Y, g:i a', strtotime($booking_details['booking_time']))) . " has been declined. A full refund has been issued.</p>";
$body .= "<p>Thank you for using CoachConnect.</p>";
MailService::sendMail($to, $subject, $body, strip_tags($body));
}
header('Location: dashboard.php?status=declined');
} else {
header('Location: dashboard.php?status=error');
}
exit;