function event_espresso_add_attendees_to_db($event_id = NULL, $session_vars = NULL)
 {
     global $wpdb, $org_options, $espresso_premium;
     //print_r($session_vars);
     $count = $wpdb->get_col($wpdb->prepare("SELECT id FROM " . EVENTS_ATTENDEE_TABLE . " WHERE attendee_session=%s", $_SESSION['espresso_session']['id']));
     if (!empty($count) && empty($_REQUEST['confirm_registration']) && is_null($session_vars)) {
         $_SESSION['espresso_session']['id'] = array();
         ee_init_session();
     }
     $data_source = $_POST;
     $att_data_source = $_POST;
     $multi_reg = false;
     static $attendee_number = 1;
     //using this var to keep track of the first attendee
     static $loop_number = 1;
     if (!is_null($event_id) && !is_null($session_vars)) {
         $data_source = $session_vars['data'];
         //event details, ie qty, price, start..
         $att_data_source = $session_vars['event_attendees'];
         //event attendee info ie name, questions....
         $multi_reg = true;
     } else {
         $event_id = $data_source['event_id'];
     }
     //echo '<p>$att_data_source = ';print_r( $att_data_source); echo '</p>';
     static $temp_event_id = '';
     // Will be used for multi events to
     // keep track of evant id change in the loop,
     // for recording event total cost for each group
     if ($temp_event_id == '' || $temp_event_id != $event_id) {
         $temp_event_id = $event_id;
         $event_change = 1;
         $total_cost = isset($data_source['cost']) ? $data_source['cost'] : 0;
     } else {
         $event_change = 0;
         $total_cost = 0;
     }
     // echo "<pre>", print_r($data_source), "</pre>";
     //echo "<pre>", print_r($att_data_source), "</pre>";
     // exit;
     $Organization = $org_options['organization'];
     $Organization_street1 = $org_options['organization_street1'];
     $Organization_street2 = $org_options['organization_street2'];
     $Organization_city = $org_options['organization_city'];
     $Organization_state = $org_options['organization_state'];
     $Organization_zip = $org_options['organization_zip'];
     $contact = $org_options['contact_email'];
     $contact_email = $org_options['contact_email'];
     $paypal_id = $org_options['paypal_id'];
     $paypal_cur = isset($org_options['currency_format']) ? $org_options['currency_format'] : '';
     $return_url = $org_options['return_url'];
     $cancel_return = $org_options['cancel_return'];
     $notify_url = $org_options['notify_url'];
     $default_mail = $org_options['default_mail'];
     $conf_message = $org_options['message'];
     $email_before_payment = $org_options['email_before_payment'];
     $fname = isset($att_data_source['fname']) ? $att_data_source['fname'] : '';
     $lname = isset($att_data_source['lname']) ? $att_data_source['lname'] : '';
     $address = isset($att_data_source['address']) ? $att_data_source['address'] : '';
     $address2 = isset($att_data_source['address2']) ? $att_data_source['address2'] : '';
     $city = isset($att_data_source['city']) ? $att_data_source['city'] : '';
     $state = isset($att_data_source['state']) ? $att_data_source['state'] : '';
     $zip = isset($att_data_source['zip']) ? $att_data_source['zip'] : '';
     $phone = isset($att_data_source['phone']) ? $att_data_source['phone'] : '';
     $email = isset($att_data_source['email']) ? $att_data_source['email'] : '';
     //$num_people = $data_source ['num_people'];
     $amount_pd = isset($data_source["event_cost"]) && $data_source["event_cost"] != '' ? $data_source["event_cost"] : 0.0;
     //echo $amount_pd;
     //return;
     //echo '<p>$amount_pd = '.$amount_pd.'</p>';
     $questions = $wpdb->get_row("SELECT question_groups, event_meta FROM " . EVENTS_DETAIL_TABLE . " WHERE id = '" . $event_id . "'");
     $event_meta = unserialize($questions->event_meta);
     $questions = unserialize($questions->question_groups);
     //echo '<p>$data_source[price_select] = '.$data_source['price_select'].'</p>';
     //$payment = $data_source['payment'];
     //Figure out if the person has registered using a price selection
     if ($multi_reg) {
         $event_cost = $_SESSION['espresso_session']['grand_total'];
         $amount_pd = $attendee_number == 1 ? $event_cost : 0.0;
         $coupon_code = $attendee_number == 1 ? $_SESSION['espresso_session']['coupon_code'] : '';
         $price_type = isset($data_source['price_type']) ? $data_source['price_type'] : espresso_ticket_information(array('type' => 'ticket', 'price_option' => $data_source['price_id']));
         $attendee_number++;
     } elseif (isset($data_source['price_select']) && $data_source['price_select'] == true) {
         $price_options = explode('|', $data_source['price_option'], 2);
         $price_id = $price_options[0];
         $price_type = $price_options[1];
         $event_cost = event_espresso_get_final_price($price_id, $event_id);
         /* echo '$event_id = '.$event_id.'<br />';
         	  echo '$price_id = '.$price_id.'<br />';
         	  echo '$event_cost = '.$event_cost;
         	  return; */
     } else {
         $event_cost = isset($data_source['price_id']) ? event_espresso_get_final_price($data_source['price_id'], $event_id) : 0.0;
         $coupon_code = '';
         $price_type = isset($data_source['price_id']) ? espresso_ticket_information(array('type' => 'ticket', 'price_option' => $data_source['price_id'])) : '';
     }
     //Display the confirmation page
     if (!empty($data_source['confirm_registration'])) {
         $registration_id = $data_source['registration_id'];
         echo espresso_confirm_registration($registration_id);
         return;
     }
     //Check to see if the registration id already exists
     $incomplete_filter = !$multi_reg ? " AND payment_status ='Incomplete'" : '';
     $check_sql = $wpdb->get_results("SELECT attendee_session, id, registration_id FROM " . EVENTS_ATTENDEE_TABLE . " WHERE attendee_session ='" . $_SESSION['espresso_session']['id'] . "' AND event_id ='" . $event_id . "' {$incomplete_filter}");
     $num_rows = $wpdb->num_rows;
     $registration_id = empty($wpdb->last_result[0]->registration_id) ? $registration_id = uniqid('', true) : $wpdb->last_result[0]->registration_id;
     $txn_type = "";
     if (isset($data_source['admin'])) {
         $payment_status = "Completed";
         $payment = "Admin";
         $txn_type = __('Added by Admin', 'event_espresso');
         $payment_date = date("m-d-Y");
         $amount_pd = $data_source["event_cost"] == '' ? 0.0 : $data_source["event_cost"];
         $registration_id = uniqid('', true);
         $_SESSION['espresso_session']['id'] = uniqid('', true);
     } else {
         if ($org_options['use_captcha'] == 'Y' && !$multi_reg && !is_user_logged_in()) {
             //Recaptcha portion
             //require_once('includes/recaptchalib.php');
             if (!function_exists('recaptcha_check_answer')) {
                 require_once EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/recaptchalib.php';
             }
             $resp = recaptcha_check_answer($org_options['recaptcha_privatekey'], $_SERVER["REMOTE_ADDR"], $data_source["recaptcha_challenge_field"], $data_source["recaptcha_response_field"]);
             if (!$resp->is_valid) {
                 echo '<div class="attention-icon"><p class="event_espresso_attention"><strong>' . __('Sorry, you did not enter the correct anti-spam phrase. Please click your browser\'s back button and try again.', 'event_espresso') . '</strong></p></div>';
                 return;
             }
         }
         //print_r( $event_meta);
         $default_payment_status = $event_meta['default_payment_status'] != '' && $org_options['default_payment_status'] != $event_meta['default_payment_status'] ? $event_meta['default_payment_status'] : $org_options['default_payment_status'];
         $payment_status = $multi_reg && $data_source['cost'] == 0 ? "Completed" : $default_payment_status;
         $payment = '';
     }
     $times_sql = "SELECT ese.start_time, ese.end_time, e.start_date, e.end_date ";
     $times_sql .= "FROM " . EVENTS_START_END_TABLE . " ese ";
     $times_sql .= "LEFT JOIN " . EVENTS_DETAIL_TABLE . " e ON ese.event_id = e.id WHERE ";
     if (!empty($data_source['start_time_id'])) {
         $times_sql .= "ese.id='" . $data_source['start_time_id'] . "' AND ";
     }
     $times_sql .= "e.id='" . $event_id . "' ";
     $times = $wpdb->get_results($times_sql);
     foreach ($times as $time) {
         $start_time = $time->start_time;
         $end_time = $time->end_time;
         $start_date = $time->start_date;
         $end_date = $time->end_date;
     }
     //If we are using the number of attendees dropdown, add that number to the DB
     //echo $data_source['espresso_addtl_limit_dd'];
     if (isset($data_source['espresso_addtl_limit_dd'])) {
         $num_people = $data_source['num_people'];
     }
     if (isset($event_meta['additional_attendee_reg_info']) && $event_meta['additional_attendee_reg_info'] == 1) {
         $num_people = $data_source['num_people'];
     } else {
         $num_people = 1;
     }
     $start_time = empty($start_time) ? '' : $start_time;
     $end_time = empty($end_time) ? '' : $end_time;
     $start_date = empty($start_date) ? '' : $start_date;
     $end_date = empty($end_date) ? '' : $end_date;
     $organization_name = empty($organization_name) ? '' : $organization_name;
     $country_id = empty($country_id) ? '' : $country_id;
     $payment_date = empty($payment_date) ? '' : $payment_date;
     $coupon_code = empty($coupon_code) ? '' : $coupon_code;
     $sql = array('registration_id' => $registration_id, 'attendee_session' => $_SESSION['espresso_session']['id'], 'lname' => $lname, 'fname' => $fname, 'address' => $address, 'address2' => $address2, 'city' => $city, 'state' => $state, 'zip' => $zip, 'email' => $email, 'phone' => $phone, 'payment' => $payment, 'amount_pd' => $amount_pd, 'txn_type' => $txn_type, 'coupon_code' => $coupon_code, 'event_time' => $start_time, 'end_time' => $end_time, 'start_date' => $start_date, 'end_date' => $end_date, 'price_option' => $price_type, 'organization_name' => $organization_name, 'country_id' => $country_id, 'payment_status' => $payment_status, 'payment_date' => $payment_date, 'event_id' => $event_id, 'quantity' => $num_people);
     $sql_data = array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d');
     //Debugging output
     /* echo 'Debug: <br />';
     	  print_r($sql);
     	  echo '<br />';
     	  print 'Number of vars: ' . count ($sql);
     	  echo '<br />';
     	  print 'Number of cols: ' . count($sql_data); */
     if ($num_rows > 0 && $loop_number == 1) {
         if (!isset($data_source['admin'])) {
             /*
              * Added for seating chart addon
              */
             $tmp_session = $_SESSION['espresso_session']['id'];
             $rem_attendee_ids = $wpdb->get_results(" select t1.id, t1.registration_id FROM " . EVENTS_ATTENDEE_TABLE . "  t1 WHERE t1.attendee_session ='" . $_SESSION['espresso_session']['id'] . "'  {$incomplete_filter} ");
             foreach ($rem_attendee_ids as $v) {
                 if (defined('ESPRESSO_SEATING_CHART')) {
                     $wpdb->query("delete from " . EVENTS_SEATING_CHART_EVENT_SEAT_TABLE . " where attendee_id = " . $v->id);
                 }
             }
             /*
              * End
              */
             $wpdb->query(" DELETE t1, t2 FROM " . EVENTS_ATTENDEE_TABLE . "  t1 JOIN  " . EVENTS_ANSWER_TABLE . " t2 on t1.id = t2.attendee_id WHERE t1.attendee_session ='" . $_SESSION['espresso_session']['id'] . "'  {$incomplete_filter} ");
         }
         //Added by Imon
         // First delete attempt might fail if there is no data in answer table. So, second attempt without joining answer table is taken bellow -
         $wpdb->query(" DELETE t1 FROM " . EVENTS_ATTENDEE_TABLE . "  t1 WHERE t1.attendee_session ='" . $_SESSION['espresso_session']['id'] . "'  {$incomplete_filter} ");
         // Clean up any attendee information from attendee_cost table where attendee is not available in attendee table
         event_espresso_cleanup_multi_event_registration_id_group_data();
         event_espresso_cleanup_attendee_cost_data();
     }
     $loop_number++;
     //Add new or updated data
     if (!$wpdb->insert(EVENTS_ATTENDEE_TABLE, $sql, $sql_data)) {
         $error = true;
     }
     $attendee_id = $wpdb->insert_id;
     /*
      * Added for seating chart addon
      */
     $booking_id = 0;
     if (defined('ESPRESSO_SEATING_CHART')) {
         if (seating_chart::check_event_has_seating_chart($event_id) !== false) {
             if (isset($_POST['seat_id'])) {
                 $booking_id = seating_chart::parse_booking_info($_POST['seat_id']);
                 if ($booking_id > 0) {
                     seating_chart::confirm_a_seat($booking_id, $attendee_id);
                 }
             }
         }
     }
     //Add a record for the primary attendee
     $sql = array('attendee_id' => $attendee_id, 'meta_key' => 'primary_attendee', 'meta_value' => 1);
     $sql_data = array('%s', '%s', '%s');
     //Debugging output
     /* echo 'Debug: <br />';
     	  print_r($sql);
     	  echo '<br />';
     	  print 'Number of vars: ' . count ($sql);
     	  echo '<br />';
     	  print 'Number of cols: ' . count($sql_data); */
     if (!$wpdb->insert(EVENTS_ATTENDEE_META_TABLE, $sql, $sql_data)) {
         $error = true;
     }
     /**
      * Adding attenddee specific cost to events_attendee_cost table
      */
     if (!isset($data_source['admin'])) {
         if (isset($att_data_source['price_id'])) {
             $attendee_price_id = $att_data_source['price_id'];
             $events_prices = $wpdb->get_row("select * from " . EVENTS_PRICES_TABLE . "  where id = {$attendee_price_id} ");
         } elseif (isset($data_source['price_select']) && $data_source['price_select'] == true) {
             $price_options = explode('|', $data_source['price_option'], 2);
             $attendee_price_id = $price_options[0];
             $events_prices = $wpdb->get_row("select * from " . EVENTS_PRICES_TABLE . "  where id = {$attendee_price_id} ");
         } else {
             $events_prices = $wpdb->get_row("select * from " . EVENTS_PRICES_TABLE . " where event_id = {$event_id}");
             $attendee_price_id = $events_prices->id;
         }
         /*
          * Added for seating chart add-on
          * If a seat was selected then price of that seating will be used instead of event price
          */
         $attendee_quantity = 1;
         if (isset($data_source['seat_id'])) {
             $attendee_cost = seating_chart::get_purchase_price($booking_id);
         } else {
             $attendee_cost = event_espresso_get_final_price($attendee_price_id, $event_id);
             if (isset($data_source['num_people'])) {
                 $attendee_quantity = $data_source['num_people'];
             }
         }
     } else {
         /* echo  '$data_source[\'event_cost\'] = '.$data_source['event_cost'];
         	  return; */
         $attendee_quantity = 1;
         $attendee_cost = $data_source['event_cost'];
     }
     $attendee_cost_data = array("attendee_id" => $attendee_id, "quantity" => $attendee_quantity, "cost" => $attendee_cost);
     /* echo '$attendee_cost_data = ';
     	  print_r($attendee_cost_data);
     	  return; */
     $wpdb->insert(EVENTS_ATTENDEE_COST_TABLE, $attendee_cost_data);
     /**
      * End
      */
     if (get_option('event_mailchimp_active') == 'true' && $espresso_premium == true) {
         MailChimpController::list_subscribe($event_id, $attendee_id, $fname, $lname, $email);
     }
     //Since main attendee and additional attendees may have different questions,
     //$attendee_number check for 2 because is it statically set at 1 first and is incremented for the primary attendee above, hence 2
     $questions = $attendee_number > 2 && isset($event_meta['add_attendee_question_groups']) ? $event_meta['add_attendee_question_groups'] : $questions;
     add_attendee_questions($questions, $registration_id, $attendee_id, array('session_vars' => $att_data_source));
     //Add additional attendees to the database
     if ($event_meta['additional_attendee_reg_info'] == 1) {
         if (!empty($_REQUEST['num_people']) && $_REQUEST['num_people'] > 1) {
         }
     } else {
         $questions = $event_meta['add_attendee_question_groups'];
         //Debug
         //echo "<pre>".print_r($questions,true)."</pre>";
         if (isset($att_data_source['x_attendee_fname'])) {
             $amount_pd = 0.0;
             //additional attendee can't hold this info
             foreach ($att_data_source['x_attendee_fname'] as $k => $v) {
                 if (trim($v) != '' && trim($att_data_source['x_attendee_lname'][$k]) != '') {
                     /*
                      * Added for seating chart addon
                      */
                     $seat_check = true;
                     $x_booking_id = 0;
                     if (defined('ESPRESSO_SEATING_CHART')) {
                         if (seating_chart::check_event_has_seating_chart($event_id) !== false) {
                             if (!isset($att_data_source['x_seat_id'][$k]) || trim($att_data_source['x_seat_id'][$k]) == '') {
                                 $seat_check = false;
                             } else {
                                 $x_booking_id = seating_chart::parse_booking_info($att_data_source['x_seat_id'][$k]);
                                 if ($x_booking_id > 0) {
                                     $seat_check = true;
                                 } else {
                                     $seat_check = false;
                                     //Keeps the system from adding an additional attndee if no seat is selected
                                 }
                             }
                         }
                     }
                     if ($seat_check) {
                         /*
                          * End
                          */
                         $sql_a = array('registration_id' => $registration_id, 'attendee_session' => $_SESSION['espresso_session']['id'], 'lname' => $att_data_source['x_attendee_lname'][$k], 'fname' => $v, 'email' => $att_data_source['x_attendee_email'][$k], 'address' => empty($att_data_source['x_attendee_address'][$k]) ? '' : $att_data_source['x_attendee_address'][$k], 'address2' => empty($att_data_source['x_attendee_address2'][$k]) ? '' : $att_data_source['x_attendee_address2'][$k], 'city' => empty($att_data_source['x_attendee_city'][$k]) ? '' : $att_data_source['x_attendee_city'][$k], 'state' => empty($att_data_source['x_attendee_state'][$k]) ? '' : $att_data_source['x_attendee_state'][$k], 'zip' => empty($att_data_source['x_attendee_zip'][$k]) ? '' : $att_data_source['x_attendee_zip'][$k], 'phone' => empty($att_data_source['x_attendee_phone'][$k]) ? '' : $att_data_source['x_attendee_phone'][$k], 'payment' => $payment, 'amount_pd' => $amount_pd, 'event_time' => $start_time, 'end_time' => $end_time, 'start_date' => $start_date, 'end_date' => $end_date, 'price_option' => $price_type, 'organization_name' => $organization_name, 'country_id' => $country_id, 'payment_status' => $payment_status, 'payment_date' => $payment_date, 'event_id' => $event_id, 'quantity' => $num_people);
                         $sql_data_a = array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d');
                         $wpdb->insert(EVENTS_ATTENDEE_TABLE, $sql_a, $sql_data_a);
                         //Added by Imon
                         $ext_attendee_id = $wpdb->insert_id;
                         $mailchimp_attendee_id = $ext_attendee_id;
                         /**
                          * Adding attenddee specific cost to events_attendee cost table
                          */
                         $attendee_cost_data = array("attendee_id" => $ext_attendee_id, "quantity" => $attendee_quantity, "cost" => $attendee_cost);
                         $wpdb->insert(EVENTS_ATTENDEE_COST_TABLE, $attendee_cost_data);
                         /**
                          * End
                          */
                         if (get_option('event_mailchimp_active') == 'true' && $espresso_premium == true) {
                             MailChimpController::list_subscribe($event_id, $mailchimp_attendee_id, $v, $att_data_source['x_attendee_lname'][$k], $att_data_source['x_attendee_email'][$k]);
                         }
                         //Added by Imon
                         $ext_att_data_source = array('registration_id' => $registration_id, 'attendee_session' => $_SESSION['espresso_session']['id'], 'lname' => $att_data_source['x_attendee_lname'][$k], 'fname' => $v, 'email' => $att_data_source['x_attendee_email'][$k], 'address' => empty($att_data_source['x_attendee_address'][$k]) ? '' : $att_data_source['x_attendee_address'][$k], 'address2' => empty($att_data_source['x_attendee_address2'][$k]) ? '' : $att_data_source['x_attendee_address2'][$k], 'city' => empty($att_data_source['x_attendee_city'][$k]) ? '' : $att_data_source['x_attendee_city'][$k], 'state' => empty($att_data_source['x_attendee_state'][$k]) ? '' : $att_data_source['x_attendee_state'][$k], 'zip' => empty($att_data_source['x_attendee_zip'][$k]) ? '' : $att_data_source['x_attendee_zip'][$k], 'phone' => empty($att_data_source['x_attendee_phone'][$k]) ? '' : $att_data_source['x_attendee_phone'][$k], 'payment' => $payment, 'amount_pd' => $amount_pd, 'event_time' => $start_time, 'end_time' => $end_time, 'start_date' => $start_date, 'end_date' => $end_date, 'price_option' => $price_type, 'organization_name' => $organization_name, 'country_id' => $country_id, 'payment_status' => $payment_status, 'payment_date' => $payment_date, 'event_id' => $event_id, 'quantity' => $num_people);
                         $questions_in = '';
                         //Debug
                         //echo "<pre questions - >".print_r($questions,true)."</pre>";
                         if (!is_array($questions) && !empty($questions)) {
                             $questions = unserialize($questions);
                         }
                         foreach ($questions as $g_id) {
                             $questions_in .= $g_id . ',';
                         }
                         $questions_in = substr($questions_in, 0, -1);
                         $questions_list = $wpdb->get_results("SELECT q.*, qg.group_name\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM " . EVENTS_QUESTION_TABLE . " q\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tJOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ton q.id = qgr.question_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tJOIN " . EVENTS_QST_GROUP_TABLE . " qg\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ton qg.id = qgr.group_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE qgr.group_id in (" . $questions_in . ") ORDER BY q.id ASC");
                         foreach ($questions_list as $question_list) {
                             if ($question_list->system_name != '') {
                                 $ext_att_data_source[$question_list->system_name] = $att_data_source['x_attendee_' . $question_list->system_name][$k];
                             } else {
                                 $ext_att_data_source[$question_list->question_type . '_' . $question_list->id] = $att_data_source['x_attendee_' . $question_list->question_type . '_' . $question_list->id][$k];
                             }
                         }
                         echo add_attendee_questions($questions, $registration_id, $ext_attendee_id, array('session_vars' => $ext_att_data_source));
                         /*
                          * Added for seating chart addon
                          */
                     }
                     if (defined('ESPRESSO_SEATING_CHART')) {
                         if (seating_chart::check_event_has_seating_chart($event_id) !== false && $x_booking_id > 0) {
                             seating_chart::confirm_a_seat($x_booking_id, $ext_attendee_id);
                         }
                     }
                     /*
                      * End
                      */
                 }
             }
         }
     }
     //Add member data if needed
     if (get_option('events_members_active') == 'true') {
         require_once EVENT_ESPRESSO_MEMBERS_DIR . "member_functions.php";
         //Load Members functions
         require EVENT_ESPRESSO_MEMBERS_DIR . "user_vars.php";
         //Load Members functions
         if ($userid != 0) {
             event_espresso_add_user_to_event($event_id, $userid, $attendee_id);
         }
     }
     //This shows the payment page
     if (isset($data_source['admin'])) {
         return $attendee_id;
     }
     if (!$multi_reg) {
         return events_payment_page($attendee_id);
     }
     return $registration_id;
 }
Beispiel #2
0
 function event_espresso_add_attendees_to_db($event_id = NULL, $session_vars = NULL, $skip_check = FALSE)
 {
     //echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
     do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
     global $wpdb, $org_options, $espresso_premium;
     // check if user has already hit this page before ( ie: going back n forth thru reg process )
     if (is_null($session_vars)) {
         $SQL = "SELECT id FROM " . EVENTS_ATTENDEE_TABLE . " WHERE attendee_session=%s";
         $prev_sessions = $wpdb->get_col($wpdb->prepare($SQL, $_SESSION['espresso_session']['id']));
         if (!empty($prev_sessions)) {
             $_SESSION['espresso_session']['id'] = array();
             ee_init_session();
         }
     }
     $data_source = $_POST;
     $att_data_source = $_POST;
     $multi_reg = FALSE;
     $notifications = array('coupons' => '', 'groupons' => '');
     if (!is_null($event_id) && !is_null($session_vars)) {
         //event details, ie qty, price, start..
         $data_source = $session_vars['data'];
         //event attendee info ie name, questions....
         $att_data_source = $session_vars['event_attendees'];
         $multi_reg = TRUE;
     } else {
         $event_id = absint($data_source['event_id']);
     }
     $data_source['reg_form_nonce'] = isset($_POST['reg_form_nonce']) && !empty($_POST['reg_form_nonce']) ? $_POST['reg_form_nonce'] : NULL;
     wp_verify_nonce($data_source['reg_form_nonce']);
     $skip_check = $skip_check || isset($data_source['admin']) ? TRUE : FALSE;
     if (espresso_verify_recaptcha($skip_check)) {
         array_walk_recursive($data_source, 'wp_strip_all_tags');
         array_walk_recursive($att_data_source, 'wp_strip_all_tags');
         array_walk_recursive($data_source, 'espresso_apply_htmlentities');
         array_walk_recursive($att_data_source, 'espresso_apply_htmlentities');
         // Will be used for multi events to keep track of evant id change in the loop, for recording event total cost for each group
         static $temp_event_id = '';
         //using this var to keep track of the first attendee
         static $attendee_number = 1;
         static $loop_number = 1;
         static $total_cost = 0;
         static $primary_att_id = NULL;
         //		echo '<h1>$attendee_number : ' . $attendee_number . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h1>';
         //		printr( $data_source, '$data_source  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
         //		printr( $att_data_source, '$att_data_source  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
         if ($temp_event_id == '' || $temp_event_id != $event_id) {
             $temp_event_id = $event_id;
             $event_change = 1;
         } else {
             $event_change = 0;
         }
         $event_cost = isset($data_source['cost']) && $data_source['cost'] != '' ? $data_source['cost'] : 0.0;
         $final_price = $event_cost;
         $fname = isset($att_data_source['fname']) ? html_entity_decode(trim($att_data_source['fname']), ENT_QUOTES, 'UTF-8') : '';
         $lname = isset($att_data_source['lname']) ? html_entity_decode(trim($att_data_source['lname']), ENT_QUOTES, 'UTF-8') : '';
         $address = isset($att_data_source['address']) ? html_entity_decode(trim($att_data_source['address']), ENT_QUOTES, 'UTF-8') : '';
         $address2 = isset($att_data_source['address2']) ? html_entity_decode(trim($att_data_source['address2']), ENT_QUOTES, 'UTF-8') : '';
         $city = isset($att_data_source['city']) ? html_entity_decode(trim($att_data_source['city']), ENT_QUOTES, 'UTF-8') : '';
         $state = isset($att_data_source['state']) ? html_entity_decode(trim($att_data_source['state']), ENT_QUOTES, 'UTF-8') : '';
         $zip = isset($att_data_source['zip']) ? html_entity_decode(trim($att_data_source['zip']), ENT_QUOTES, 'UTF-8') : '';
         $phone = isset($att_data_source['phone']) ? html_entity_decode(trim($att_data_source['phone']), ENT_QUOTES, 'UTF-8') : '';
         $email = isset($att_data_source['email']) ? html_entity_decode(trim($att_data_source['email']), ENT_QUOTES, 'UTF-8') : '';
         $SQL = "SELECT question_groups, event_meta FROM " . EVENTS_DETAIL_TABLE . " WHERE id = %d";
         $questions = $wpdb->get_row($wpdb->prepare($SQL, $event_id));
         $event_meta = maybe_unserialize($questions->event_meta);
         $questions = maybe_unserialize($questions->question_groups);
         // Adding attenddee specific cost to events_attendee table
         if (isset($data_source['admin'])) {
             $attendee_quantity = 1;
             $final_price = $data_source['event_cost'];
             $orig_price = $data_source['event_cost'];
             $price_type = __('Admin', 'event_espresso');
             //echo '<h4>$orig_price : ' . $orig_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
             //echo '<h4>$final_price : ' . $final_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         } elseif (isset($data_source['seat_id'])) {
             // Added for seating chart add-on
             // If a seat was selected then price of that seating will be used instead of event price
             $final_price = seating_chart::get_purchase_price($data_source['seat_id']);
             $orig_price = $data_source['cost'];
             //echo '<h4>$orig_price : ' . $orig_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
             //echo '<h4>$final_price : ' . $final_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         } elseif (isset($att_data_source['price_id']) && !empty($att_data_source['price_id'])) {
             if ($att_data_source['price_id'] == 'free') {
                 $orig_price = 0.0;
                 $final_price = 0.0;
                 $price_type = __('Free Event', 'event_espresso');
             } else {
                 $orig_price = event_espresso_get_orig_price_and_surcharge($att_data_source['price_id']);
                 $final_price = isset($att_data_source['price_id']) ? event_espresso_get_final_price($att_data_source['price_id'], $event_id, $orig_price) : 0.0;
                 $price_type = isset($att_data_source['price_id']) ? espresso_ticket_information(array('type' => 'ticket', 'price_option' => $att_data_source['price_id'])) : '';
                 $surcharge = event_espresso_calculate_surcharge($orig_price->event_cost, $orig_price->surcharge, $orig_price->surcharge_type);
                 $orig_price = (double) number_format($orig_price->event_cost + $surcharge, 2, '.', '');
                 //					echo '<h4>$orig_price : ' . $orig_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                 //					echo '<h4>$final_price : ' . $final_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
             }
         } elseif (isset($data_source['price_select']) && $data_source['price_select'] == TRUE) {
             //Figure out if the person has registered using a price selection
             $price_options = explode('|', $data_source['price_option'], 2);
             $price_id = $price_options[0];
             $price_type = $price_options[1];
             $orig_price = event_espresso_get_orig_price_and_surcharge($price_id);
             $final_price = event_espresso_get_final_price($price_id, $event_id, $orig_price);
             $surcharge = event_espresso_calculate_surcharge($orig_price->event_cost, $orig_price->surcharge, $orig_price->surcharge_type);
             $orig_price = (double) number_format($orig_price->event_cost + $surcharge, 2, '.', '');
             //echo '<h4>$orig_price : ' . $orig_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
             //echo '<h4>$final_price : ' . $final_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         } else {
             if ($data_source['price_id'] == 'free') {
                 $orig_price = 0.0;
                 $final_price = 0.0;
                 $price_type = __('Free Event', 'event_espresso');
             } else {
                 $orig_price = event_espresso_get_orig_price_and_surcharge($data_source['price_id']);
                 $final_price = isset($data_source['price_id']) ? event_espresso_get_final_price($data_source['price_id'], $event_id, $orig_price) : 0.0;
                 $price_type = isset($data_source['price_id']) ? espresso_ticket_information(array('type' => 'ticket', 'price_option' => $data_source['price_id'])) : '';
                 $surcharge = event_espresso_calculate_surcharge($orig_price->event_cost, $orig_price->surcharge, $orig_price->surcharge_type);
                 $orig_price = (double) number_format($orig_price->event_cost + $surcharge, 2, '.', '');
                 //echo '<h4>$orig_price : ' . $orig_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                 //echo '<h4>$final_price : ' . $final_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
             }
         }
         $final_price = apply_filters('filter_hook_espresso_attendee_cost', $final_price);
         $attendee_quantity = isset($data_source['num_people']) ? $data_source['num_people'] : 1;
         $coupon_code = '';
         //echo '<h4>$orig_price : ' . $orig_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         //echo '<h4>$final_price : ' . $final_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         if ($multi_reg) {
             $event_cost = $_SESSION['espresso_session']['grand_total'];
             //$coupon_code = $attendee_number == 1 ? $_SESSION['espresso_session']['event_espresso_coupon_code'] : '';
         }
         do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, 'line ' . __LINE__ . ' : attendee_cost=' . $final_price);
         $event_cost = apply_filters('filter_hook_espresso_cart_grand_total', $event_cost);
         //			$amount_pd = $attendee_number == 1 ? $event_cost : 0.00;
         $amount_pd = 0.0;
         //Check to see if the registration id already exists
         $incomplete_filter = !$multi_reg ? " AND payment_status ='Incomplete'" : '';
         $SQL = "SELECT attendee_session, id, registration_id FROM " . EVENTS_ATTENDEE_TABLE . " WHERE attendee_session =%s AND event_id = %d";
         $SQL .= $incomplete_filter;
         $check_sql = $wpdb->get_results($wpdb->prepare($SQL, $_SESSION['espresso_session']['id'], $event_id));
         $nmbr_of_regs = $wpdb->num_rows;
         //Check if the registration id has been created previously.
         $registration_id = empty($wpdb->last_result[0]->registration_id) ? apply_filters('filter_hook_espresso_registration_id', $event_id) : $wpdb->last_result[0]->registration_id;
         $txn_type = "";
         if (isset($data_source['admin'])) {
             $payment_status = "Completed";
             $payment = "Admin";
             $txn_type = __('Added by Admin', 'event_espresso');
             //$payment_date = date("m-d-Y");
             $payment_date = date(get_option('date_format'));
             $amount_pd = $data_source['event_cost'] != '' ? $data_source['event_cost'] : 0.0;
             $registration_id = uniqid('', true);
             $_SESSION['espresso_session']['id'] = uniqid('', true);
         } else {
             //print_r( $event_meta);
             $default_payment_status = $event_meta['default_payment_status'] != '' ? $event_meta['default_payment_status'] : $org_options['default_payment_status'];
             $payment_status = $multi_reg && $data_source['cost'] == 0.0 ? "Completed" : $default_payment_status;
             $payment = '';
         }
         $times_sql = "SELECT ese.start_time, ese.end_time, e.start_date, e.end_date ";
         $times_sql .= "FROM " . EVENTS_START_END_TABLE . " ese ";
         $times_sql .= "LEFT JOIN " . EVENTS_DETAIL_TABLE . " e ON ese.event_id = e.id WHERE ";
         $times_sql .= "e.id=%d";
         if (!empty($data_source['start_time_id'])) {
             $times_sql .= " AND ese.id=" . $data_source['start_time_id'];
         }
         $times = $wpdb->get_results($wpdb->prepare($times_sql, $event_id));
         foreach ($times as $time) {
             $start_time = $time->start_time;
             $end_time = $time->end_time;
             $start_date = $time->start_date;
             $end_date = $time->end_date;
         }
         //If we are using the number of attendees dropdown, add that number to the DB
         //echo $data_source['espresso_addtl_limit_dd'];
         if (isset($data_source['espresso_addtl_limit_dd'])) {
             $num_people = $data_source['num_people'];
         } elseif (isset($event_meta['additional_attendee_reg_info']) && $event_meta['additional_attendee_reg_info'] == 1) {
             $num_people = $data_source['num_people'];
         } else {
             $num_people = 1;
         }
         // check for coupon
         if (function_exists('event_espresso_process_coupon')) {
             if ($coupon_results = event_espresso_process_coupon($event_id, $final_price, $multi_reg)) {
                 //printr( $coupon_results, '$coupon_results  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
                 if ($coupon_results['valid']) {
                     $final_price = number_format($coupon_results['event_cost'], 2, '.', '');
                     $coupon_code = $coupon_results['code'];
                 }
                 if (!$multi_reg && !empty($coupon_results['msg'])) {
                     $notifications['coupons'] = $coupon_results['msg'];
                 }
             }
         }
         // check for groupon
         if (function_exists('event_espresso_process_groupon')) {
             if ($groupon_results = event_espresso_process_groupon($event_id, $final_price, $multi_reg)) {
                 //printr( $groupon_results, '$groupon_results  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
                 if ($groupon_results['valid']) {
                     $final_price = number_format($groupon_results['event_cost'], 2, '.', '');
                     $coupon_code = $groupon_results['code'];
                 }
                 if (!$multi_reg && !empty($groupon_results['msg'])) {
                     $notifications['groupons'] = $groupon_results['msg'];
                 }
             }
         }
         // check for groupon
         //			$use_groupon =  isset( $data_source['use_groupon'][ $event_id ] ) && function_exists( 'espresso_apply_goupon_to_attendee' ) ? $data_source['use_groupon'][ $event_id ] == 'Y' : 'N';
         //			if ( $use_groupon && isset( $data_source['groupon'] )) {
         //				if ( $new_att_price_data = espresso_apply_goupon_to_attendee( $event_id, $final_price, $data_source['groupon'] )) {
         //					extract( $new_att_price_data );
         //					$data_source['groupon'] = $groupon;
         //				}
         //			}
         $start_time = empty($start_time) ? '' : $start_time;
         $end_time = empty($end_time) ? '' : $end_time;
         $start_date = empty($start_date) ? '' : $start_date;
         $end_date = empty($end_date) ? '' : $end_date;
         $organization_name = empty($organization_name) ? '' : $organization_name;
         $country_id = empty($country_id) ? '' : $country_id;
         $payment_date = empty($payment_date) ? '' : $payment_date;
         $coupon_code = empty($coupon_code) ? '' : $coupon_code;
         $amount_pd = number_format((double) $amount_pd, 2, '.', '');
         $orig_price = number_format((double) $orig_price, 2, '.', '');
         $final_price = number_format((double) $final_price, 2, '.', '');
         $total_cost = $total_cost + $final_price;
         //echo '<h4>$amount_pd : ' . $amount_pd . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         //echo '<h4>$orig_price : ' . $orig_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         //echo '<h4>$final_price : ' . $final_price . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
         //echo '<h4>$total_cost : ' . $total_cost . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4><br /><br /><br />';
         //echo '<h4>$payment_status : ' . $payment_status . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4><br /><br /><br />';
         $columns_and_values = array('registration_id' => $registration_id, 'is_primary' => $attendee_number == 1 ? TRUE : FALSE, 'attendee_session' => $_SESSION['espresso_session']['id'], 'lname' => $lname, 'fname' => $fname, 'address' => $address, 'address2' => $address2, 'city' => $city, 'state' => $state, 'zip' => $zip, 'email' => $email, 'phone' => $phone, 'payment' => $payment, 'txn_type' => $txn_type, 'coupon_code' => $coupon_code, 'event_time' => $start_time, 'end_time' => $end_time, 'start_date' => $start_date, 'end_date' => $end_date, 'price_option' => $price_type, 'organization_name' => $organization_name, 'country_id' => $country_id, 'payment_status' => $payment_status, 'payment_date' => $payment_date, 'event_id' => $event_id, 'quantity' => (int) $num_people, 'amount_pd' => $amount_pd, 'orig_price' => $orig_price, 'final_price' => $final_price);
         //			printr( $columns_and_values, '$columns_and_values  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
         $data_formats = array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%f', '%f', '%f');
         // delete previous entries from this session in case user is jumping back n forth between pages during the reg process
         if ($nmbr_of_regs > 0 && $loop_number == 1) {
             if (!isset($data_source['admin'])) {
                 //Added for seating chart addon
                 $tmp_session = wp_strip_all_tags($_SESSION['espresso_session']['id']);
                 $SQL = "SELECT id, registration_id FROM " . EVENTS_ATTENDEE_TABLE . ' ';
                 $SQL .= "WHERE attendee_session = %s ";
                 $SQL .= $incomplete_filter;
                 if ($rem_attendee_ids = $wpdb->get_results($wpdb->prepare($SQL, $tmp_session))) {
                     foreach ($rem_attendee_ids as $v) {
                         if (defined('ESPRESSO_SEATING_CHART')) {
                             $SQL = "DELETE FROM " . EVENTS_SEATING_CHART_EVENT_SEAT_TABLE . ' ';
                             $SQL .= "WHERE attendee_id = %d";
                             $wpdb->query($wpdb->prepare($SQL, $v->id));
                         }
                     }
                 }
                 $SQL = "DELETE t1, t2 FROM " . EVENTS_ATTENDEE_TABLE . "  t1 ";
                 $SQL .= "JOIN  " . EVENTS_ANSWER_TABLE . " t2 on t1.id = t2.attendee_id ";
                 $SQL .= "WHERE t1.attendee_session = %s ";
                 $SQL .= $incomplete_filter;
                 $wpdb->query($wpdb->prepare($SQL, $tmp_session));
             }
             //Added by Imon
             // First delete attempt might fail if there is no data in answer table. So, second attempt without joining answer table is taken bellow -
             $SQL = " DELETE FROM " . EVENTS_ATTENDEE_TABLE . ' ';
             $SQL .= "WHERE attendee_session = %s ";
             $SQL .= $incomplete_filter;
             $wpdb->query($wpdb->prepare($SQL, $tmp_session));
             // Clean up any attendee information from attendee_cost table where attendee is not available in attendee table
             event_espresso_cleanup_multi_event_registration_id_group_data();
         }
         $loop_number++;
         // save the attendee details - FINALLY !!!
         if (!$wpdb->insert(EVENTS_ATTENDEE_TABLE, $columns_and_values, $data_formats)) {
             $error = true;
         }
         $attendee_id = $wpdb->insert_id;
         // save attendee id for the primary attendee
         $primary_att_id = $attendee_number == 1 ? $attendee_id : FALSE;
         // Added for seating chart addon
         $booking_id = 0;
         if (defined('ESPRESSO_SEATING_CHART')) {
             if (seating_chart::check_event_has_seating_chart($event_id) !== false) {
                 if (isset($_POST['seat_id'])) {
                     $booking_id = seating_chart::parse_booking_info($_POST['seat_id']);
                     if ($booking_id > 0) {
                         seating_chart::confirm_a_seat($booking_id, $attendee_id);
                     }
                 }
             }
         }
         //Add a record for the primary attendee
         if ($attendee_number == 1) {
             $columns_and_values = array('attendee_id' => $primary_att_id, 'meta_key' => 'primary_attendee', 'meta_value' => 1);
             $data_formats = array('%s', '%s', '%s');
             if (!$wpdb->insert(EVENTS_ATTENDEE_META_TABLE, $columns_and_values, $data_formats)) {
                 $error = true;
             }
         }
         if (defined('EVENTS_MAILCHIMP_ATTENDEE_REL_TABLE') && $espresso_premium == true) {
             MailChimpController::list_subscribe($event_id, $attendee_id, $fname, $lname, $email);
         }
         //Defining the $base_questions variable in case there are no additional attendee questions
         $base_questions = $questions;
         //Since main attendee and additional attendees may have different questions,
         //$attendee_number check for 2 because is it statically set at 1 first and is incremented for the primary attendee above, hence 2
         $questions = $attendee_number > 1 && isset($event_meta['add_attendee_question_groups']) ? $event_meta['add_attendee_question_groups'] : $questions;
         add_attendee_questions($questions, $registration_id, $attendee_id, array('session_vars' => $att_data_source));
         //Add additional attendees to the database
         if ($event_meta['additional_attendee_reg_info'] > 1) {
             $questions = $event_meta['add_attendee_question_groups'];
             if (empty($questions)) {
                 $questions = $base_questions;
             }
             if (isset($att_data_source['x_attendee_fname'])) {
                 foreach ($att_data_source['x_attendee_fname'] as $k => $v) {
                     if (trim($v) != '' && trim($att_data_source['x_attendee_lname'][$k]) != '') {
                         // Added for seating chart addon
                         $seat_check = true;
                         $x_booking_id = 0;
                         if (defined('ESPRESSO_SEATING_CHART')) {
                             if (seating_chart::check_event_has_seating_chart($event_id) !== false) {
                                 if (!isset($att_data_source['x_seat_id'][$k]) || trim($att_data_source['x_seat_id'][$k]) == '') {
                                     $seat_check = false;
                                 } else {
                                     $x_booking_id = seating_chart::parse_booking_info($att_data_source['x_seat_id'][$k]);
                                     if ($x_booking_id > 0) {
                                         $seat_check = true;
                                     } else {
                                         $seat_check = false;
                                         //Keeps the system from adding an additional attndee if no seat is selected
                                     }
                                 }
                             }
                         }
                         if ($seat_check) {
                             $data = array('registration_id' => $registration_id, 'attendee_session' => $_SESSION['espresso_session']['id'], 'lname' => $att_data_source['x_attendee_lname'][$k], 'fname' => $v, 'email' => $att_data_source['x_attendee_email'][$k], 'address' => empty($att_data_source['x_attendee_address'][$k]) ? '' : $att_data_source['x_attendee_address'][$k], 'address2' => empty($att_data_source['x_attendee_address2'][$k]) ? '' : $att_data_source['x_attendee_address2'][$k], 'city' => empty($att_data_source['x_attendee_city'][$k]) ? '' : $att_data_source['x_attendee_city'][$k], 'state' => empty($att_data_source['x_attendee_state'][$k]) ? '' : $att_data_source['x_attendee_state'][$k], 'zip' => empty($att_data_source['x_attendee_zip'][$k]) ? '' : $att_data_source['x_attendee_zip'][$k], 'phone' => empty($att_data_source['x_attendee_phone'][$k]) ? '' : $att_data_source['x_attendee_phone'][$k], 'payment' => $payment, 'event_time' => $start_time, 'end_time' => $end_time, 'start_date' => $start_date, 'end_date' => $end_date, 'price_option' => $price_type, 'organization_name' => $organization_name, 'country_id' => $country_id, 'payment_status' => $payment_status, 'payment_date' => $payment_date, 'event_id' => $event_id, 'quantity' => (int) $num_people, 'amount_pd' => (double) 0.0, 'orig_price' => $orig_price, 'final_price' => $final_price);
                             $format = array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%f', '%f', '%f');
                             $wpdb->insert(EVENTS_ATTENDEE_TABLE, $data, $format);
                             //Added by Imon
                             $ext_attendee_id = $wpdb->insert_id;
                             $mailchimp_attendee_id = $ext_attendee_id;
                             if (defined('EVENTS_MAILCHIMP_ATTENDEE_REL_TABLE') && $espresso_premium == true) {
                                 MailChimpController::list_subscribe($event_id, $mailchimp_attendee_id, $v, $att_data_source['x_attendee_lname'][$k], $att_data_source['x_attendee_email'][$k]);
                             }
                             //Added by Imon
                             $ext_att_data_source = array('registration_id' => $registration_id, 'attendee_session' => $_SESSION['espresso_session']['id'], 'lname' => $att_data_source['x_attendee_lname'][$k], 'fname' => $v, 'email' => $att_data_source['x_attendee_email'][$k], 'address' => empty($att_data_source['x_attendee_address'][$k]) ? '' : $att_data_source['x_attendee_address'][$k], 'address2' => empty($att_data_source['x_attendee_address2'][$k]) ? '' : $att_data_source['x_attendee_address2'][$k], 'city' => empty($att_data_source['x_attendee_city'][$k]) ? '' : $att_data_source['x_attendee_city'][$k], 'state' => empty($att_data_source['x_attendee_state'][$k]) ? '' : $att_data_source['x_attendee_state'][$k], 'zip' => empty($att_data_source['x_attendee_zip'][$k]) ? '' : $att_data_source['x_attendee_zip'][$k], 'phone' => empty($att_data_source['x_attendee_phone'][$k]) ? '' : $att_data_source['x_attendee_phone'][$k], 'payment' => $payment, 'amount_pd' => (double) 0.0, 'event_time' => $start_time, 'end_time' => $end_time, 'start_date' => $start_date, 'end_date' => $end_date, 'price_option' => $price_type, 'organization_name' => $organization_name, 'country_id' => $country_id, 'payment_status' => $payment_status, 'payment_date' => $payment_date, 'event_id' => $event_id, 'quantity' => (int) $num_people);
                             if (!is_array($questions) && !empty($questions)) {
                                 $questions = unserialize($questions);
                             }
                             $questions_in = '';
                             foreach ($questions as $g_id) {
                                 $questions_in .= $g_id . ',';
                             }
                             $questions_in = substr($questions_in, 0, -1);
                             $SQL = "SELECT q.*, qg.group_name FROM " . EVENTS_QUESTION_TABLE . " q ";
                             $SQL .= "JOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id ";
                             $SQL .= "JOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id ";
                             $SQL .= "WHERE qgr.group_id in ( {$questions_in} ) ";
                             $SQL .= "ORDER BY q.id ASC";
                             $questions_list = $wpdb->get_results($wpdb->prepare($SQL, NULL));
                             foreach ($questions_list as $question_list) {
                                 if ($question_list->system_name != '') {
                                     $ext_att_data_source[$question_list->system_name] = $att_data_source['x_attendee_' . $question_list->system_name][$k];
                                 } else {
                                     $ext_att_data_source[$question_list->question_type . '_' . $question_list->id] = $att_data_source['x_attendee_' . $question_list->question_type . '_' . $question_list->id][$k];
                                 }
                             }
                             echo add_attendee_questions($questions, $registration_id, $ext_attendee_id, array('session_vars' => $ext_att_data_source));
                         }
                         // Added for seating chart addon
                         if (defined('ESPRESSO_SEATING_CHART')) {
                             if (seating_chart::check_event_has_seating_chart($event_id) !== false && $x_booking_id > 0) {
                                 seating_chart::confirm_a_seat($x_booking_id, $ext_attendee_id);
                             }
                         }
                     }
                 }
             }
         }
         //Add member data if needed
         if (defined('EVENTS_MEMBER_REL_TABLE')) {
             require_once EVENT_ESPRESSO_MEMBERS_DIR . "member_functions.php";
             //Load Members functions
             require EVENT_ESPRESSO_MEMBERS_DIR . "user_vars.php";
             //Load Members functions
             if ($userid != 0) {
                 event_espresso_add_user_to_event($event_id, $userid, $attendee_id);
             }
         }
         $attendee_number++;
         if (isset($data_source['admin'])) {
             return $attendee_id;
         }
         //This shows the payment page
         if (!$multi_reg) {
             return events_payment_page($attendee_id, $notifications);
         }
         return array('registration_id' => $registration_id, 'notifications' => $notifications);
     }
 }
function attendee_edit_record()
{
    global $wpdb, $org_options;
    do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
    $id = isset($_REQUEST['id']) ? absint($_REQUEST['id']) : FALSE;
    $registration_id = isset($_REQUEST['registration_id']) ? wp_strip_all_tags($_REQUEST['registration_id']) : FALSE;
    $req_primary = isset($_REQUEST['primary']) ? wp_strip_all_tags(absint($_REQUEST['primary'])) : $id;
    $req_p_id = isset($_REQUEST['p_id']) ? wp_strip_all_tags(absint($_REQUEST['p_id'])) : FALSE;
    if (isset($_REQUEST['r_id']) && !empty($_REQUEST['r_id'])) {
        $registration_id = wp_strip_all_tags($_REQUEST['r_id']);
    }
    if ($id && $registration_id) {
        if (!empty($_REQUEST['delete_attendee']) && $_REQUEST['delete_attendee'] == 'true') {
            $SQL = " DELETE FROM " . EVENTS_ATTENDEE_TABLE . " WHERE id = %d";
            $wpdb->query($wpdb->prepare($SQL, $id));
            $SQL = "SELECT id from " . EVENTS_ATTENDEE_TABLE . " WHERE registration_id = %s";
            $wpdb->query($wpdb->prepare($SQL, $registration_id));
            if ($wpdb->num_rows == 0) {
                $SQL = " UPDATE " . EVENTS_ATTENDEE_TABLE . " ";
                $SQL .= "SET quantity = IF(quantity IS NULL ,NULL,IF(quantity > 0,IF(quantity-1>0,quantity-1,1),0)) ";
                $SQL .= "WHERE registration_id = %s";
                $wpdb->query($wpdb->prepare($SQL, $registration_id));
                event_espresso_cleanup_multi_event_registration_id_group_data();
            }
            if (isset($req_primary) && isset($req_p_id)) {
                return events_payment_page($req_primary);
            }
        }
        // end delete attendee
        $counter = 0;
        $additional_attendees = NULL;
        $SQL = "SELECT  att.*, evt.event_name, evt.question_groups, evt.event_meta ";
        $SQL .= "FROM " . EVENTS_ATTENDEE_TABLE . " att ";
        $SQL .= "JOIN " . EVENTS_DETAIL_TABLE . " evt ON att.event_id = evt.id ";
        $SQL .= "WHERE att.id = %d AND att.registration_id = %s ";
        $SQL .= "ORDER BY att.id";
        $attendee = $wpdb->get_row($wpdb->prepare($SQL, $id, $registration_id));
        if ($attendee != FALSE) {
            $display_attendee_form = TRUE;
            $id = $attendee->id;
            $registration_id = $attendee->registration_id;
            $lname = $attendee->lname;
            $fname = $attendee->fname;
            $address = $attendee->address;
            $city = $attendee->city;
            $state = $attendee->state;
            $zip = $attendee->zip;
            $email = $attendee->email;
            $payment = $attendee->payment;
            $phone = $attendee->phone;
            $date = $attendee->date;
            $payment_status = $attendee->payment_status;
            $txn_type = $attendee->txn_type;
            $txn_id = $attendee->txn_id;
            $amount_pd = $attendee->amount_pd;
            $quantity = $attendee->quantity;
            $payment_date = $attendee->payment_date;
            $event_id = $attendee->event_id;
            $event_name = stripslashes_deep($attendee->event_name);
            $question_groups = maybe_unserialize($attendee->question_groups);
            $event_meta = maybe_unserialize($attendee->event_meta);
            if (!$attendee->is_primary && isset($event_meta['add_attendee_question_groups']) && $event_meta['add_attendee_question_groups'] != NULL) {
                $question_groups = $event_meta['add_attendee_question_groups'];
            }
            //printr( $question_groups, '$question_groups  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
            $questions_in = '';
            foreach ($question_groups as $g_id) {
                $questions_in .= $g_id . ',';
            }
            $questions_in = substr($questions_in, 0, -1);
            //			echo '<h4>$questions_in : ' . $questions_in . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
            $group_name = '';
            $counter = 0;
            //pull the list of questions that are relevant to this event
            $SQL = "SELECT q.*, q.id AS q_id, qg.group_name FROM " . EVENTS_QUESTION_TABLE . " q ";
            $SQL .= "JOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id ";
            $SQL .= "JOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id ";
            $SQL .= "WHERE qgr.group_id in ( {$questions_in} ) ";
            $SQL .= "AND q.admin_only != 'Y' ";
            $SQL .= "ORDER BY qg.group_order, qg.id, q.sequence ASC";
            $questions = $wpdb->get_results($wpdb->prepare($SQL, NULL));
            //			echo '<h4>last_query : ' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
            //			printr( $questions, '$questions  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
            $SQL = "SELECT question_id, answer FROM " . EVENTS_ANSWER_TABLE . " ans WHERE ans.attendee_id = %d";
            $answers = $wpdb->get_results($wpdb->prepare($SQL, $id));
            $answer_a = array();
            foreach ($answers as $answer) {
                array_push($answer_a, $answer->question_id);
            }
            // Update the attendee information
            if (isset($_REQUEST['attendee_action']) && $_REQUEST['attendee_action'] == 'update_attendee') {
                $fname = !empty($_POST['fname']) ? ee_sanitize_value($_POST['fname']) : '';
                $lname = !empty($_POST['lname']) ? ee_sanitize_value($_POST['lname']) : '';
                $address = !empty($_POST['address']) ? ee_sanitize_value($_POST['address']) : '';
                $city = !empty($_POST['city']) ? ee_sanitize_value($_POST['city']) : '';
                $state = !empty($_POST['state']) ? ee_sanitize_value($_POST['state']) : '';
                $zip = !empty($_POST['zip']) ? ee_sanitize_value($_POST['zip']) : '';
                $phone = !empty($_POST['phone']) ? ee_sanitize_value($_POST['phone']) : '';
                $email = !empty($_POST['email']) ? ee_sanitize_value($_POST['email']) : '';
                $SQL = "UPDATE " . EVENTS_ATTENDEE_TABLE . " SET fname=%s, lname=%s, address=%s, city=%s, state=%s, zip=%s, phone=%s, email=%s WHERE id =%d";
                $wpdb->query($wpdb->prepare($SQL, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $id));
                if ($questions) {
                    foreach ($questions as $question) {
                        switch ($question->question_type) {
                            case "TEXT":
                            case "TEXTAREA":
                            case "DROPDOWN":
                            case "SINGLE":
                                $post_val = $question->system_name != '' ? ee_sanitize_value($_POST[$question->system_name]) : ee_sanitize_value($_POST[$question->question_type . '_' . $question->q_id]);
                                break;
                            case "MULTIPLE":
                                $post_val = '';
                                if (!empty($_POST[$question->question_type . '_' . $question->id])) {
                                    for ($i = 0; $i < count($_POST[$question->question_type . '_' . $question->id]); $i++) {
                                        $post_val .= trim(ee_sanitize_value($_POST[$question->question_type . '_' . $question->id][$i])) . ',';
                                    }
                                }
                                $post_val = substr($post_val, 0, -1);
                                break;
                        }
                        $post_val = html_entity_decode($post_val, ENT_QUOTES, 'UTF-8');
                        if (in_array($question->q_id, $answer_a)) {
                            $SQL = "UPDATE " . EVENTS_ANSWER_TABLE . " SET answer = %s WHERE attendee_id = %d AND question_id =%d";
                            $wpdb->query($wpdb->prepare($SQL, $post_val, $id, $question->q_id));
                        } else {
                            $SQL = "INSERT INTO " . EVENTS_ANSWER_TABLE . " ( registration_id, answer, attendee_id, question_id ) VALUES ( %s, %s, %d, %d )";
                            $wpdb->query($wpdb->prepare($SQL, $registration_id, $post_val, $id, $question->q_id));
                        }
                        //echo '<h4>LQ : ' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                    }
                }
                //If this is not an attendee returing to edit their details, then we need to return to the payment page
                if (!isset($_REQUEST['single'])) {
                    if (espresso_registration_id($req_primary) == $registration_id && espresso_registration_id($id) == $registration_id) {
                        return events_payment_page($req_primary);
                        exit;
                    } else {
                        _e('Sorry, it seems there was an error verifying the attendee id or primary attendee id record.', 'event_espresso');
                        return;
                    }
                }
            }
        } else {
            $display_attendee_form = FALSE;
        }
        ?>

	<div id="edit-attendee-record-dv" class="event-display-boxes ui-widget">
		<h3 class="event_title ui-widget-header ui-corner-top">
			<?php 
        _e('Edit Registration', 'event_espresso');
        ?>
		</h3>
		<div class="event_espresso_form_wrapper event-data-display ui-widget-content ui-corner-bottom">

<?php 
        if ($display_attendee_form) {
            ?>

			
			<p>
				<strong><?php 
            _e('Event:', 'event_espresso');
            ?>
</strong> <?php 
            echo $event_name;
            ?>
			</p>
			
			<form method="post" action="<?php 
            echo home_url();
            ?>
/?page_id=<?php 
            echo $org_options['event_page_id'];
            ?>
" class="espresso_form" id="registration_form">
<?php 
            if (count($question_groups) > 0) {
                $questions_in = '';
                foreach ($question_groups as $g_id) {
                    $questions_in .= $g_id . ',';
                }
                $questions_in = substr($questions_in, 0, -1);
                //					echo '<h4>$questions_in : ' . $questions_in . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                $FILTER = isset($event_meta['additional_attendee_reg_info']) && $event_meta['additional_attendee_reg_info'] == '2' && isset($_REQUEST['attendee_num']) && $_REQUEST['attendee_num'] > 1 ? ' AND qg.system_group = 1 ' : '';
                //pull the list of questions that are relevant to this event
                $SQL = "SELECT q.*, q.id AS q_id, at.*, qg.group_name, qg.show_group_description, qg.show_group_name ";
                $SQL .= "FROM " . EVENTS_QUESTION_TABLE . " q ";
                $SQL .= "LEFT JOIN " . EVENTS_ANSWER_TABLE . " at on q.id = at.question_id ";
                $SQL .= "JOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id ";
                $SQL .= "JOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id ";
                $SQL .= "WHERE qg.id in ( {$questions_in} ) ";
                $SQL .= "AND (  at.attendee_id IS NULL OR at.attendee_id = %d ) ";
                $SQL .= "AND q.admin_only != 'Y' ";
                $SQL .= $FILTER;
                $SQL .= "ORDER BY qg.group_order, qg.id, q.sequence ASC";
                if ($questions = $wpdb->get_results($wpdb->prepare($SQL, $id))) {
                    //						printr( $questions, '$questions  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
                    //						echo '<h4>last_query : ' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
                    //Output the questions
                    $question_displayed = array();
                    $group_name = '';
                    $counter = 0;
                    $total_questions = count($questions);
                    foreach ($questions as $question) {
                        if (!in_array($question->id, $question_displayed)) {
                            $question_displayed[] = $question->id;
                            // if question group has changed, close prev group tags
                            echo $group_name != '' && $group_name != $question->group_name ? '
					</fieldset>
				</div>' : '';
                            // new group ?
                            if ($group_name != $question->group_name) {
                                $question->group_identifier = !empty($question->group_identifier) ? ' id="' . $question->group_identifier . '"' : '';
                                $question->group_description = !empty($question->group_description) ? $question->group_description : '';
                                echo '
				<div class="event_questions"' . $question->group_identifier . '>
					<fieldset>';
                                echo $question->show_group_name != 0 ? '
						<h3 class="section-title">' . $question->group_name . '</h3>' : '';
                                echo $question->show_group_description != 0 && $question->group_description != '' ? '
						<p>
							' . $question->group_description . '
						</p>' : '';
                                $group_name = $question->group_name;
                            }
                            echo event_form_build_edit($question, $question->answer, $show_admin_only = FALSE);
                            $counter++;
                            echo $counter == $total_questions ? '
					</fieldset>
				</div>' : '';
                        }
                    }
                }
                //end questions display
            }
            //	registration_id=1-5072fa1b52696
            //	id=318
            //	regevent_action=register
            //	form_action=edit_attendee
            //	primary=318
            //	event_id=1
            //	coupon_code=
            //	groupon_code=
            //	attendee_num=1
            ?>

				<input type="hidden" name="id" value="<?php 
            echo $id;
            ?>
" />
				<input type="hidden" name="r_id" value="<?php 
            echo $registration_id;
            ?>
" />
				<input type="hidden" name="event_id" value="<?php 
            echo $event_id;
            ?>
" />
				<input type="hidden" name="attendee_action" value="update_attendee" />
				<input type="hidden" name="regevent_action" value="edit_attendee" />
				<input type="hidden" name="primary" value="<?php 
            echo $req_primary;
            ?>
" />
				
				<p class="event_form_submit">
					<input class="event-form-submit-btn" type="submit" name="submit" value="<?php 
            _e('Update Record', 'event_espresso');
            ?>
" />
				</p>
				
			</form>
			
<?php 
        } else {
            ?>
	
			<div class="event_espresso_error">
				<h3><?php 
            _e('An error occured.', 'event_espresso');
            ?>
</h3>
				<p>
					<?php 
            _e('The requested attendee data could not be found.<br/>Please refresh the page and try again or contact the site admin if problem\'s persist.', 'event_espresso');
            ?>
				</p>
			</div>
	
<?php 
        }
        ?>

		</div><!-- / .event-display-boxes -->
	</div><!-- / .event_espresso_form_wrapper .event-data-display -->

<?php 
    } else {
        _e('No attendee record was found.', 'event_espresso');
    }
}
function attendee_edit_record()
{
    global $wpdb, $org_options;
    do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
    $id = $_REQUEST['id'];
    $registration_id = $_REQUEST['registration_id'];
    if (isset($_REQUEST['r_id'])) {
        $registration_id = $_REQUEST['r_id'];
    }
    if (!empty($_REQUEST['delete_attendee']) && $_REQUEST['delete_attendee'] == 'true') {
        $sql = " DELETE FROM " . EVENTS_ATTENDEE_TABLE . " WHERE id ='{$id}'";
        $wpdb->query($sql);
        $wpdb->query("SELECT id from " . EVENTS_ATTENDEE_TABLE . " WHERE registration_id ='{$registration_id}' ");
        if ($wpdb->num_rows == 0) {
            $sql = " UPDATE " . EVENTS_ATTENDEE_TABLE . " SET quantity = IF(quantity IS NULL ,NULL,IF(quantity > 0,IF(quantity-1>0,quantity-1,1),0)) WHERE registration_id ='{$registration_id}'";
            $wpdb->query($sql);
            $sql = " UPDATE " . EVENTS_ATTENDEE_COST_TABLE . " SET quantity = IF(quantity IS NULL ,NULL,IF(quantity > 0,IF(quantity-1>0,quantity-1,1),0)) WHERE attendee_id ='{$id}'";
            $wpdb->query($sql);
            event_espresso_cleanup_multi_event_registration_id_group_data();
            event_espresso_cleanup_attendee_cost_data();
        }
        return events_payment_page($_REQUEST['primary'], $_REQUEST['p_id']);
    }
    $counter = 0;
    $additional_attendees = NULL;
    $sql = "SELECT  t1.*, t2.event_name, t2.question_groups, t2.event_meta FROM " . EVENTS_ATTENDEE_TABLE . " t1\n\t\t\t\t JOIN " . EVENTS_DETAIL_TABLE . " t2\n\t\t\t\t ON t1.event_id = t2.id\n\t\t\t\t WHERE t1.id = '" . $id . "' AND t1.registration_id = '" . $registration_id . "'\n\t\t\t\t ORDER BY t1.id";
    //Debug
    //echo '<p>$sql- '.$sql.'</p>';
    $results = $wpdb->get_results($sql);
    foreach ($results as $result) {
        if ($counter == 0) {
            $id = $result->id;
            $registration_id = $result->registration_id;
            $lname = $result->lname;
            $fname = $result->fname;
            $address = $result->address;
            $city = $result->city;
            $state = $result->state;
            $zip = $result->zip;
            $email = $result->email;
            $payment = $result->payment;
            $phone = $result->phone;
            $date = $result->date;
            $payment_status = $result->payment_status;
            $txn_type = $result->txn_type;
            $txn_id = $result->txn_id;
            $amount_pd = $result->amount_pd;
            $quantity = $result->quantity;
            $payment_date = $result->payment_date;
            $event_id = $result->event_id;
            $event_name = stripslashes_deep($result->event_name);
            $question_groups = unserialize($result->question_groups);
            $event_meta = unserialize($result->event_meta);
            $counter = 1;
        } else {
            $additional_attendees[$result->id] = array('full_name' => $result->fname . ' ' . $result->lname, 'email' => $result->email, 'phone' => $result->phone);
        }
    }
    $response_source = $_POST;
    $questions = $wpdb->get_row("SELECT question_groups, event_meta FROM " . EVENTS_DETAIL_TABLE . " WHERE id = " . $event_id . " ");
    $question_groups = unserialize($questions->question_groups);
    //Debug
    //echo "<pre>".print_r($question_groups,true)."</pre>";
    $event_meta = unserialize($questions->event_meta);
    if (isset($event_meta['add_attendee_question_groups']) && $event_meta['add_attendee_question_groups'] != NULL) {
        $question_groups = $event_meta['add_attendee_question_groups'];
    }
    $questions_in = '';
    if (!is_array($question_groups) && !empty($question_groups)) {
        $question_groups = unserialize($question_groups);
    }
    foreach ($question_groups as $g_id) {
        $questions_in .= $g_id . ',';
    }
    $questions_in = substr($questions_in, 0, -1);
    $group_name = '';
    $counter = 0;
    //pull the list of questions that are relevant to this event
    $q_sql_1 = "SELECT q.*, q.id q_id, qg.group_name FROM " . EVENTS_QUESTION_TABLE . " q\n\t\t\t\t\t\tJOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id\n\t\t\t\t\t\tJOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id\n\t\t\t\t\t\tWHERE qgr.group_id in (" . $questions_in . ")\n\t\t\t\t\t\tAND q.admin_only = 'N'\n\t\t\t\t\t\tORDER BY qg.id, q.sequence ASC";
    $questions = $wpdb->get_results($q_sql_1);
    /* DEBUG */
    //			echo "<pre>";
    //			echo '<p>'.print_r($questions).'</p>';
    //			echo '<p>'.$q_sql_1.'</p>';
    /* END DEBUG */
    $a_sql = "SELECT question_id, answer FROM " . EVENTS_ANSWER_TABLE . " ans WHERE ans.attendee_id = '" . $id . "' ";
    /* DEBUG */
    //			echo '<p>'.$a_sql.'</p>';
    /* END DEBUG */
    $answers = $wpdb->get_results($a_sql);
    /* DEBUG */
    //			echo "<pre>";
    //			echo 'print_r($answers) = <br/>';
    //			print_r($answers);
    /* END DEBUG */
    $answer_a = array();
    foreach ($answers as $answer) {
        /* DEBUG */
        //echo '<p>$answers[question_id] = '.$answer->question_id.'</p>';
        array_push($answer_a, $answer->question_id);
    }
    /*
     * Update the attendee information
     */
    if (!empty($_REQUEST['attendee_action']) && $_REQUEST['attendee_action'] == 'update_attendee') {
        if (!empty($_POST['fname'])) {
            $fname = $_POST['fname'];
        }
        if (!empty($_POST['lname'])) {
            $lname = $_POST['lname'];
        }
        if (!empty($_POST['address'])) {
            $address = $_POST['address'];
        }
        if (!empty($_POST['city'])) {
            $city = $_POST['city'];
        }
        if (!empty($_POST['state'])) {
            $state = $_POST['state'];
        }
        if (!empty($_POST['zip'])) {
            $zip = $_POST['zip'];
        }
        if (!empty($_POST['phone'])) {
            $phone = $_POST['phone'];
        }
        if (!empty($_POST['email'])) {
            $email = $_POST['email'];
        }
        $sql = "UPDATE " . EVENTS_ATTENDEE_TABLE . " SET fname='{$fname}', lname='{$lname}', address='{$address}', city='{$city}', state='{$state}', zip='{$zip}', phone='{$phone}', email='{$email}' WHERE id ='{$id}'";
        $wpdb->query($sql);
        //echo $sql;
        /* DEBUG */
        //			echo "<pre>";
        //			echo 'print_r($answers) = <br />';
        //			print_r($answers);
        //			echo 'print_r($questions) = <br />';
        //			print_r($questions);
        //			echo 'print_r($answer_a) = <br/>';
        //			print_r($answer_a);
        //			exit();
        /* END DEBUG */
        if ($questions) {
            foreach ($questions as $question) {
                switch ($question->question_type) {
                    case "TEXT":
                    case "TEXTAREA":
                    case "DROPDOWN":
                        //$post_val = $_POST [ $question->question_type . '_' . $question->question_id ];
                        $post_val = $question->system_name != '' ? $response_source[$question->system_name] : $response_source[$question->question_type . '_' . $question->q_id];
                        if (in_array($question->q_id, $answer_a)) {
                            $sql = "UPDATE " . EVENTS_ANSWER_TABLE . " SET answer='{$post_val}' WHERE attendee_id = '{$id}' AND question_id ='{$question->q_id}'";
                        } else {
                            $sql = "INSERT INTO " . EVENTS_ANSWER_TABLE . " (registration_id, answer,attendee_id,question_id) VALUES ('{$registration_id}','{$post_val}', {$id},{$question->q_id})";
                        }
                        $wpdb->query($sql);
                        break;
                    case "SINGLE":
                        //$post_val = $_POST [ $question->question_type . '_' . $question->question_id ];
                        $post_val = $question->system_name != '' ? $response_source[$question->system_name] : $response_source[$question->question_type . '_' . $question->q_id];
                        if (in_array($question->q_id, $answer_a)) {
                            $sql = "UPDATE " . EVENTS_ANSWER_TABLE . " SET answer='{$post_val}' WHERE attendee_id = '{$id}' AND question_id ='{$question->q_id}'";
                        } else {
                            $sql = "INSERT INTO " . EVENTS_ANSWER_TABLE . " (registration_id, answer,attendee_id,question_id) VALUES ('{$registration_id}','{$post_val}', {$id},{$question->q_id})";
                        }
                        $wpdb->query($sql);
                        break;
                    case "MULTIPLE":
                        $value_string = '';
                        for ($i = 0; $i < count($response_source[$question->question_type . '_' . $question->id]); $i++) {
                            $value_string .= trim($response_source[$question->question_type . '_' . $question->id][$i]) . ",";
                        }
                        if (in_array($question->q_id, $answer_a)) {
                            $sql = "UPDATE " . EVENTS_ANSWER_TABLE . " SET answer='{$value_string}' WHERE attendee_id = '{$id}' AND question_id ='{$question->q_id}'";
                        } else {
                            $sql = "INSERT INTO " . EVENTS_ANSWER_TABLE . " (registration_id, answer,attendee_id,question_id) VALUES ('{$registration_id}','{$value_string}', {$id}, {$question->q_id})";
                        }
                        $wpdb->query($sql);
                        /* DEBUG */
                        //echo '<p>'.$sql.'</p>';
                        //$sql = "UPDATE " . EVENTS_ANSWER_TABLE . " SET answer='$value_string' WHERE attendee_id = '$id' AND question_id ='$question->question_id'";
                        //echo '<p>$question->q_id = '.$question->q_id.'</p>';
                        /* echo '<p> in_array($question->q_id, $answers) = ';
                        	  echo in_array($question->q_id, $answers) ? 'true':'false';
                        	  echo '</p>'; */
                        //echo '<p>'.print_r($answers).'</p>';
                        //echo '<p>$answers[question_id]'.$answers['question_id'].'</p>';
                        //print_r($answer_a);
                        //print_r($answers);
                        /* if (!array_key_exists($question->id , $answers)) {
                        	  echo 'test = '.$question->id.'<br />';
                        	  } */
                        /* END DEBUG */
                        break;
                }
            }
        }
        //If this is not an attendee returing to edit thier details, then we need to return to the payment page
        if (!isset($_REQUEST['single'])) {
            return events_payment_page($_REQUEST['primary'], $_REQUEST['p_id']);
        }
    }
    ?>
	<div id="event_espresso_registration_form" class="event-display-boxes">
 	 <div class="event_espresso_form_wrapper event-data-display">
		<h3 class="section-heading"><?php 
    if ($_REQUEST['registration_id'] = 'true') {
        echo __('Edit Your', 'event_espresso') . ' ';
    }
    _e('Registration', 'event_espresso');
    ?>
</h3>
		<p><strong><?php 
    _e('Event:', 'event_espresso');
    ?>
 <?php 
    echo $event_name;
    ?>
</strong></p>
		<form method="post" action="<?php 
    echo $_SERVER['REQUEST_URI'];
    ?>
" class="espresso_form" id="registration_form">
			<?php 
    if (count($question_groups) > 0) {
        $questions_in = '';
        foreach ($question_groups as $g_id) {
            $questions_in .= $g_id . ',';
        }
        $questions_in = substr($questions_in, 0, -1);
        $group_name = '';
        $counter = 0;
        $FILTER = '';
        if (isset($event_meta['additional_attendee_reg_info']) && $event_meta['additional_attendee_reg_info'] == '2' && isset($_REQUEST['attendee_num']) && $_REQUEST['attendee_num'] > 1) {
            $FILTER .= " AND qg.system_group = 1 ";
        }
        //pull the list of questions that are relevant to this event
        $q_sql_2 = "SELECT q.*, q.id q_id, at.*, qg.group_name, qg.show_group_description, qg.show_group_name FROM " . EVENTS_QUESTION_TABLE . " q\n\t\t\t\t\tLEFT JOIN " . EVENTS_ANSWER_TABLE . " at on q.id = at.question_id\n\t\t\t\t\tJOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id\n\t\t\t\t\tJOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id\n\t\t\t\t\tWHERE qgr.group_id in (" . $questions_in . ")\n\t\t\t\t\tAND (at.attendee_id IS NULL OR at.attendee_id = '" . $id . "')\n\t\t\t\t\tAND q.admin_only != 'Y'\n\t\t\t\t\t" . $FILTER . "\n\t\t\t\t\tORDER BY qg.id, q.id ASC";
        /* DEBUG */
        //echo '<p>$q_sql_2 - '.$q_sql_2.'</p>';
        $questions = '';
        $questions = $wpdb->get_results($q_sql_2);
        $num_rows = $wpdb->num_rows;
        if ($num_rows > 0) {
            $q_ids = '';
            foreach ($questions as $question_ids) {
                $q_ids .= $question_ids->question_id . ',';
            }
            // DEBUG
            //echo '<p>$q_ids - '. rtrim($q_ids, ",").'</p>';
            $existing_questions = rtrim($q_ids, ",");
            $q_sql_3 = "SELECT q.* FROM " . EVENTS_QUESTION_TABLE . " q  JOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr ON q.id = qgr.question_id JOIN " . EVENTS_QST_GROUP_TABLE . " qg ON qg.id = qgr.group_id WHERE qgr.group_id IN (" . $questions_in . ") AND q.id NOT IN (" . $existing_questions . ") GROUP BY q.question ORDER BY qg.id, q.id ASC";
            //DEBUG
            //echo '$q_sql_3 - <p>'.$q_sql_3.'</p>';
            $questions_2 = $wpdb->get_results($q_sql_3);
            $num_rows_2 = $wpdb->num_rows;
            //Merge the existing questions with any missing questions
            if ($num_rows_2 > 0) {
                $questions = array_merge($questions, $questions_2);
            }
            //Output the questions
            $question_displayed = array();
            foreach ($questions as $question) {
                if (!in_array($question->id, $question_displayed)) {
                    $question_displayed[] = $question->id;
                    //if new group, close fieldset
                    echo $group_name != '' && $group_name != $question->group_name ? '</fieldset>' : '';
                    // DEBUG
                    //echo '<p>'.print_r($question).'</p>';
                    //END DEBUG
                    echo $group_name != '' && $group_name != $question->group_name ? '</div>' : '';
                    if ($group_name != $question->group_name) {
                        $group_id = !empty($question->group_identifier) ? 'id="' . $question->group_identifier . '"' : '';
                        if (empty($question->group_description)) {
                            $question->group_description = '';
                        }
                        echo '<div class="event_questions" ' . $group_id . '>';
                        echo $question->show_group_name != 0 ? '<h4 class="section-title">' . $question->group_name . '</h4>' : '';
                        echo $question->show_group_description != 0 ? '<p>' . $question->group_description . '</p>' : '';
                        $group_name = $question->group_name;
                    }
                    echo '<p>';
                    echo event_form_build_edit($question, $question->answer, $show_admin_only = false);
                    echo "</p>";
                    $counter++;
                    echo $counter == $num_rows ? '</div>' : '';
                }
            }
        }
        //end questions display
    }
    ?>
			<input type="hidden" name="id" value="<?php 
    echo $id;
    ?>
" />
			<input type="hidden" name="event_id" value="<?php 
    echo $event_id;
    ?>
" />
			<input type="hidden" name="form_action" value="edit_attendee" />
			<input type="hidden" name="attendee_action" value="update_attendee" />
			<input type="hidden" name="regevent_action" value="register" />
			<input type="hidden" name="primary" value="<?php 
    echo $_REQUEST['primary'];
    ?>
" />
			<p class="espresso_confirm_registration"><input class="btn_event_form_submit" type="submit" name="submit" value="<?php 
    _e('Update Record', 'event_espresso');
    ?>
" /></p>
		</form>
	</div><!-- / .event-display-boxes -->
	</div><!-- / .event_espresso_form_wrapper .event-data-display -->
	<?php 
}