route.php
93 lines
| 1 | <?php |
| 2 | |
| 3 | namespace ShopEngine\Modules\Wishlist; |
| 4 | |
| 5 | use ShopEngine\Base\Api; |
| 6 | |
| 7 | class Route extends Api { |
| 8 | |
| 9 | public function config() { |
| 10 | |
| 11 | $this->prefix = 'wishlist'; |
| 12 | $this->param = ""; |
| 13 | $this->customer_only = true; |
| 14 | } |
| 15 | |
| 16 | public function post_add_to_list() { |
| 17 | |
| 18 | // Verify nonce for CSRF protection |
| 19 | $nonce = $this->request->get_header('X-WP-Nonce'); |
| 20 | if (empty($nonce) || !wp_verify_nonce($nonce, 'wp_rest')) { |
| 21 | return new \WP_Error('rest_forbidden', esc_html__('Invalid nonce.', 'shopengine'), array('status' => 403)); |
| 22 | } |
| 23 | |
| 24 | $data = $this->request->get_params(); |
| 25 | $idd = $data['product_id']; |
| 26 | |
| 27 | if(empty($idd)) { |
| 28 | |
| 29 | return [ |
| 30 | 'status' => 'failed', |
| 31 | 'message' => esc_html__('Product id not found.', 'shopengine'), |
| 32 | ]; |
| 33 | } |
| 34 | |
| 35 | if(is_user_logged_in()) { |
| 36 | |
| 37 | $uid = get_current_user_id(); |
| 38 | |
| 39 | $content = get_user_meta( $uid, Wishlist::UMK_WISHLIST, true ); |
| 40 | $content = empty($content) ? [] : $content; |
| 41 | |
| 42 | if(isset($content[$idd])) { |
| 43 | |
| 44 | $msg = esc_html__('Successfully removed from wishlist', 'shopengine'); |
| 45 | $action = 'removed'; |
| 46 | unset($content[$idd]); |
| 47 | |
| 48 | } else { |
| 49 | |
| 50 | $msg = esc_html__('Successfully added into wishlist', 'shopengine'); |
| 51 | $action = 'add'; |
| 52 | $content[$idd] = $idd; |
| 53 | } |
| 54 | |
| 55 | update_user_meta( $uid, Wishlist::UMK_WISHLIST, $content ); |
| 56 | |
| 57 | return [ |
| 58 | 'status' => 'success', |
| 59 | 'message' => $msg, |
| 60 | 'todo' => $action, |
| 61 | ]; |
| 62 | } |
| 63 | |
| 64 | $cck = empty($_COOKIE[Wishlist::COOKIE_KEY]) ? '' : sanitize_text_field(wp_unslash($_COOKIE[Wishlist::COOKIE_KEY])); |
| 65 | $cck = explode(',', $cck); |
| 66 | $content = array_combine($cck, $cck); |
| 67 | |
| 68 | if(isset($content[$idd])) { |
| 69 | |
| 70 | $msg = esc_html__('Successfully removed from wishlist', 'shopengine'); |
| 71 | $action = 'removed'; |
| 72 | unset($content[$idd]); |
| 73 | |
| 74 | } else { |
| 75 | |
| 76 | $msg = esc_html__('Successfully added into wishlist', 'shopengine'); |
| 77 | $action = 'add'; |
| 78 | $content[$idd] = $idd; |
| 79 | } |
| 80 | |
| 81 | $val = implode(',', $content); |
| 82 | |
| 83 | setcookie(Wishlist::COOKIE_KEY, $val, strtotime( '+30 days'), '/' ); |
| 84 | |
| 85 | return [ |
| 86 | 'status' => 'success', |
| 87 | 'message' => $msg, |
| 88 | 'dd' => Wishlist::COOKIE_KEY, |
| 89 | 'todo' => $action, |
| 90 | ]; |
| 91 | } |
| 92 | } |
| 93 |