// 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ó")."
"; // --- EMAIL 1: GỬI CHO ADMIN --- $admin_subject = "Le Soleil: Đơn mới từ $name - Bàn $table_n"; $admin_message = "

YÊU CẦU ĐẶT BÀN MỚI

$info_table

Kiểm tra Dashboard để xác nhận đơn.

"; @wp_mail($admin_email, $admin_subject, $admin_message, $headers); // --- EMAIL 2: GỬI CHO KHÁCH HÀNG --- if (!empty($email)) { $customer_subject = "Xác nhận yêu cầu đặt bàn tại Le Soleil - $name"; $customer_message = "

CẢM ƠN BẠN ĐÃ ĐẶT BÀN!

Chào $name, Le Soleil đã nhận được yêu cầu của bạn:

$info_table

Chúng tôi sẽ gọi lại cho bạn qua số $phone sớm thôi!

"; @wp_mail($email, $customer_subject, $customer_message, $headers); } wp_send_json_success('Đặt bàn thành công!'); } else { wp_send_json_error('Lỗi SQL: ' . $wpdb->last_error); } wp_die(); }