-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubmit_booking.php
More file actions
363 lines (316 loc) · 14.2 KB
/
submit_booking.php
File metadata and controls
363 lines (316 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
// submit_booking.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'message' => 'Method not allowed']);
exit();
}
// Include database configuration
require_once 'includes/config.php';
// Initialize response array
$response = ['success' => false, 'message' => ''];
try {
// Get POST data
$raw_input = file_get_contents('php://input');
if (empty($raw_input)) {
throw new Exception('No data received. Please check your form submission.');
}
$input = json_decode($raw_input, true);
// Check if input is valid
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON data received. Error: ' . json_last_error_msg());
}
if (!is_array($input)) {
throw new Exception('Invalid data format received');
}
// Debug: Log received data (remove in production)
error_log('Received booking data: ' . print_r($input, true));
// Validate required fields
$required_fields = [
'full_name', 'email', 'phone', 'country',
'start_date', 'trip_date', 'duration_days', 'number_of_people',
'booking_type', 'item_name', 'selected_package', 'package_price'
];
$missing_fields = [];
foreach ($required_fields as $field) {
if (!isset($input[$field]) || trim($input[$field]) === '') {
$missing_fields[] = $field;
}
}
if (!empty($missing_fields)) {
throw new Exception('Missing required fields: ' . implode(', ', $missing_fields));
}
// Validate email
if (!filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
throw new Exception('Invalid email address: ' . $input['email']);
}
// Validate dates
$today = new DateTime();
$today->setTime(0, 0, 0);
// Start date validation
$start_date = DateTime::createFromFormat('Y-m-d', $input['start_date']);
if (!$start_date) {
throw new Exception('Invalid start date format. Use YYYY-MM-DD. Received: ' . $input['start_date']);
}
$start_date->setTime(0, 0, 0);
if ($start_date < $today) {
throw new Exception('Start date cannot be in the past. Today is ' . $today->format('Y-m-d'));
}
// Trip date validation
$trip_date = DateTime::createFromFormat('Y-m-d', $input['trip_date']);
if (!$trip_date) {
throw new Exception('Invalid trip date format. Use YYYY-MM-DD. Received: ' . $input['trip_date']);
}
$trip_date->setTime(0, 0, 0);
if ($trip_date < $today) {
throw new Exception('Trip date cannot be in the past. Today is ' . $today->format('Y-m-d'));
}
// Validate duration
if (!is_numeric($input['duration_days']) || $input['duration_days'] < 1 || $input['duration_days'] > 365) {
throw new Exception('Invalid duration. Must be between 1 and 365 days. Received: ' . $input['duration_days']);
}
// Validate number of people
if (!is_numeric($input['number_of_people']) || $input['number_of_people'] < 1 || $input['number_of_people'] > 100) {
throw new Exception('Invalid number of people. Must be between 1 and 100. Received: ' . $input['number_of_people']);
}
// Validate package price
if (!is_numeric($input['package_price']) || $input['package_price'] < 0) {
throw new Exception('Invalid package price. Must be a positive number. Received: ' . $input['package_price']);
}
// Check if database connection exists
if (!isset($db)) {
throw new Exception('Database connection not available. Please check config.php');
}
// Check if bookings table exists (optional - for debugging)
try {
$check_table = $db->query("SHOW TABLES LIKE 'bookings'");
if ($check_table->rowCount() == 0) {
throw new Exception('Bookings table does not exist in database');
}
} catch (PDOException $e) {
// Just log, don't stop execution
error_log('Table check failed: ' . $e->getMessage());
}
// Prepare SQL query
$query = "INSERT INTO bookings SET
booking_type = :booking_type,
item_name = :item_name,
full_name = :full_name,
email = :email,
phone = :phone,
country = :country,
start_date = :start_date,
end_date = :end_date,
trip_date = :trip_date,
duration_days = :duration_days,
number_of_people = :number_of_people,
special_requests = :special_requests,
package_name = :package_name,
package_price = :package_price,
status = 'pending',
created_at = NOW(),
updated_at = NOW()";
$stmt = $db->prepare($query);
if (!$stmt) {
$errorInfo = $db->errorInfo();
throw new Exception('Failed to prepare SQL statement: ' . ($errorInfo[2] ?? 'Unknown error'));
}
// Sanitize and prepare parameters
$booking_type = htmlspecialchars(strip_tags($input['booking_type']));
$item_name = htmlspecialchars(strip_tags($input['item_name']));
$full_name = htmlspecialchars(strip_tags($input['full_name']));
$email = htmlspecialchars(strip_tags($input['email']));
$phone = htmlspecialchars(strip_tags($input['phone']));
$country = htmlspecialchars(strip_tags($input['country']));
$start_date_str = $input['start_date'];
$end_date_str = !empty($input['end_date']) ? $input['end_date'] : null;
$trip_date_str = $input['trip_date'];
$duration_days = (int)$input['duration_days'];
$number_of_people = (int)$input['number_of_people'];
$package_name = htmlspecialchars(strip_tags($input['selected_package']));
$package_price = (float)$input['package_price'];
$special_requests = !empty($input['special_requests'])
? htmlspecialchars(strip_tags($input['special_requests']))
: null;
// Debug: Log parameters (remove in production)
error_log('Binding parameters: ' . print_r([
'booking_type' => $booking_type,
'item_name' => $item_name,
'full_name' => $full_name,
'email' => $email,
'phone' => $phone,
'country' => $country,
'start_date' => $start_date_str,
'end_date' => $end_date_str,
'trip_date' => $trip_date_str,
'duration_days' => $duration_days,
'number_of_people' => $number_of_people,
'package_name' => $package_name,
'package_price' => $package_price,
'special_requests' => $special_requests
], true));
// Bind values
$stmt->bindParam(':booking_type', $booking_type);
$stmt->bindParam(':item_name', $item_name);
$stmt->bindParam(':full_name', $full_name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':start_date', $start_date_str);
$stmt->bindParam(':end_date', $end_date_str);
$stmt->bindParam(':trip_date', $trip_date_str);
$stmt->bindParam(':duration_days', $duration_days, PDO::PARAM_INT);
$stmt->bindParam(':number_of_people', $number_of_people, PDO::PARAM_INT);
$stmt->bindParam(':package_name', $package_name);
$stmt->bindParam(':package_price', $package_price, PDO::PARAM_STR);
$stmt->bindParam(':special_requests', $special_requests);
// Execute query
if ($stmt->execute()) {
$booking_id = $db->lastInsertId();
// Send confirmation email (optional)
$email_sent = false;
if (function_exists('sendConfirmationEmail')) {
$email_sent = sendConfirmationEmail($input, $booking_id);
}
$response = [
'success' => true,
'message' => 'Booking submitted successfully!',
'booking_id' => $booking_id,
'email_sent' => $email_sent,
'debug' => 'Booking ID: ' . $booking_id
];
http_response_code(201);
// Debug log
error_log('Booking successful! ID: ' . $booking_id);
} else {
$errorInfo = $stmt->errorInfo();
throw new Exception('Failed to execute query: ' . ($errorInfo[2] ?? 'Unknown error'));
}
} catch(Exception $exception) {
http_response_code(500);
$response = [
'success' => false,
'message' => 'Error: ' . $exception->getMessage(),
'debug_info' => [
'error' => $exception->getMessage(),
'line' => $exception->getLine(),
'file' => $exception->getFile(),
'trace' => $exception->getTraceAsString()
]
];
// Log detailed error
error_log('========== BOOKING ERROR ==========');
error_log('Message: ' . $exception->getMessage());
error_log('File: ' . $exception->getFile());
error_log('Line: ' . $exception->getLine());
error_log('Trace: ' . $exception->getTraceAsString());
if (isset($input)) {
error_log('Input Data: ' . print_r($input, true));
}
error_log('==================================');
}
echo json_encode($response);
exit();
// Function to send confirmation email
function sendConfirmationEmail($booking_data, $booking_id) {
try {
// Email configuration
$to = $booking_data['email'];
$subject = "Booking Confirmation - Majogoo Rangers Safaris";
// Email content
$message = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background-color: #1a5d2c; color: white; padding: 20px; text-align: center; }
.content { background-color: #f9f9f9; padding: 20px; }
.footer { background-color: #f1f3f4; padding: 15px; text-align: center; font-size: 12px; }
.booking-details { background-color: white; padding: 15px; border-radius: 5px; margin: 15px 0; }
.detail-item { margin-bottom: 10px; }
.label { font-weight: bold; color: #1a5d2c; }
</style>
</head>
<body>
<div class='container'>
<div class='header'>
<h1>Majogoo Rangers Safaris</h1>
<h2>Booking Confirmation</h2>
</div>
<div class='content'>
<p>Dear " . htmlspecialchars($booking_data['full_name']) . ",</p>
<p>Thank you for booking with Majogoo Rangers Safaris! Your booking request has been received and is being processed.</p>
<div class='booking-details'>
<h3>Booking Details</h3>
<div class='detail-item'>
<span class='label'>Booking ID:</span> MRS-" . str_pad($booking_id, 6, '0', STR_PAD_LEFT) . "
</div>
<div class='detail-item'>
<span class='label'>Safari:</span> " . htmlspecialchars($booking_data['item_name']) . "
</div>
<div class='detail-item'>
<span class='label'>Package:</span> " . htmlspecialchars($booking_data['selected_package']) . "
</div>
<div class='detail-item'>
<span class='label'>Start Date:</span> " . htmlspecialchars($booking_data['start_date']) . "
</div>
<div class='detail-item'>
<span class='label'>Duration:</span> " . htmlspecialchars($booking_data['duration_days']) . " days
</div>
<div class='detail-item'>
<span class='label'>Number of People:</span> " . htmlspecialchars($booking_data['number_of_people']) . "
</div>
<div class='detail-item'>
<span class='label'>Total Price:</span> $" . number_format($booking_data['package_price'], 2) . "
</div>
</div>
<p><strong>Next Steps:</strong></p>
<ol>
<li>Our team will review your booking and contact you within 24 hours.</li>
<li>We'll confirm availability and provide payment instructions.</li>
<li>Once payment is confirmed, your booking will be finalized.</li>
</ol>
<p>If you have any questions, please contact us at:</p>
<ul>
<li>Phone: +254 711 534 242</li>
<li>Email: majogoorangerssafaris@gmail.com</li>
</ul>
<p>Best regards,<br>The Majogoo Rangers Safaris Team</p>
</div>
<div class='footer'>
<p>© " . date('Y') . " Majogoo Rangers Safaris. All rights reserved.</p>
<p>Nairobi, Kenya | www.majogoorangers.com</p>
</div>
</div>
</body>
</html>
";
// Email headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: Majogoo Rangers Safaris <noreply@majogoorangers.com>" . "\r\n";
$headers .= "Reply-To: majogoorangerssafaris@gmail.com" . "\r\n";
// Send email
if (mail($to, $subject, $message, $headers)) {
error_log('Confirmation email sent to: ' . $to);
return true;
} else {
error_log('Failed to send confirmation email to: ' . $to);
return false;
}
} catch (Exception $e) {
error_log('Email sending failed: ' . $e->getMessage());
return false;
}
}