// 1. Đăng ký Action với WordPress add_action('wp_ajax_save_booking_action', 'handle_booking_form'); add_action('wp_ajax_nopriv_save_booking_action', 'handle_booking_form'); function handle_booking_form() { global $wpdb; $table_name = $wpdb->prefix . 'restaurant_booking'; // 2. Lấy và làm sạch dữ liệu từ Form $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : ''; $phone = isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : ''; $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : ''; $date = isset($_POST['booking_date']) ? sanitize_text_field($_POST['booking_date']) : ''; $time = isset($_POST['booking_time']) ? sanitize_text_field($_POST['booking_time']) : ''; $guests = isset($_POST['guests']) ? intval($_POST['guests']) : 1; $floor = isset($_POST['floor']) ? sanitize_text_field($_POST['floor']) : ''; $table_n = isset($_POST['table_number']) ? sanitize_text_field($_POST['table_number']) : ''; $note = isset($_POST['note']) ? sanitize_textarea_field($_POST['note']) : ''; // 3. Kiểm tra dữ liệu bắt buộc if (empty($name) || empty($phone) || empty($table_n) || empty($date)) { wp_send_json_error('Vui lòng điền đầy đủ thông tin bắt buộc.'); } // 4. KIỂM TRA TRÙNG BÀN $check_exists = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM $table_name WHERE booking_date = %s AND table_number = %s AND status != 'cancelled'", $date, $table_n )); if ($check_exists > 0) { wp_send_json_error("Rất tiếc, bàn $table_n đã có người đặt vào ngày $date."); } // 5. CHÈN DỮ LIỆU VÀO DATABASE $inserted = $wpdb->insert( $table_name, array( 'customer_name' => $name, 'phone' => $phone, 'email' => $email, 'booking_date' => $date, 'booking_time' => $time, 'guests' => $guests, 'floor' => $floor, 'table_number' => $table_n, 'note' => $note, 'status' => 'pending' ) ); // 6. GỬI EMAIL TỰ ĐỘNG if ($inserted) { $admin_email = get_option('admin_email'); $headers = array('Content-Type: text/html; charset=UTF-8'); // Tạo bảng thông tin chi tiết cho Email $info_table = "
| Khách hàng: | $name |
| Số điện thoại: | $phone |
| Vị trí: | Bàn $table_n ($floor) |
| Thời gian: | $time ngày $date |
| Số khách: | $guests người |
| Ghi chú: | ".(!empty($note) ? $note : "Không có")." |
Kiểm tra Dashboard để xác nhận đơn.
Chào $name, Le Soleil đã nhận được yêu cầu của bạn:
$info_tableChúng tôi sẽ gọi lại cho bạn qua số $phone sớm thôi!