Jake Vanderwerf
2026-07-10 f94860aacd6200fb24c9e7431eb379a368cb392d
inc/integrations/Square.php
@@ -1,11 +1,18 @@
<?php
namespace JVBase\integrations;
use JVBase\meta\MetaForm;
use JVBase\meta\MetaManager;
use JVBase\meta\Form;
use JVBase\meta\Meta;
use Exception;
use JVBase\registry\PostTypeRegistrar;
use JVBase\registrar\Fields;
use JVBase\registrar\Posts;
use JVBase\registrar\Registrar;
use JVBase\ui\CRUDSkeleton;
use WP_Error;
use JVBase\ui\Checkout;
use JVBase\managers\queue\TypeConfig;
use JVBase\managers\queue\executors\IntegrationExecutor;
use WP_Query;
if (!defined('ABSPATH')) {
   exit;
@@ -21,6 +28,15 @@
 */
class Square extends Integrations
{
   protected static string $syncCustomer = 'square_sync_customer';
   protected array $allowedContent = [
      'REGULAR',
      'FOOD_AND_BEV',
      'APPOINTMENTS_SERVICE',
      'DIGITAL',
      'EVENT',
      'DONATION'
   ];
   /**
    * Square API Configuration
    */
@@ -40,6 +56,9 @@
    * OAuth Configuration
    */
   protected bool $isOAuthService = true;
   protected string $orderPostType = '_square_order';
   protected array $newOrder = [];
   protected array $oauth = [
      'authorize' => '',
      'token' => '',
@@ -67,14 +86,32 @@
   protected string $locationId = '';
   protected array $locations = [];
   public function __construct(?int $userID = null)
   protected static array $instances = [];
   public static function getInstance(?int $userID = null):self
   {
      $key = is_null($userID) ? 'base' : $userID;
      if (!array_key_exists($key, self::$instances)) {
         self::$instances[$key] = new self($userID);
      }
      return self::$instances[$key];
   }
   protected function __construct(?int $userID = null)
   {
      // Display properties
      $this->title = 'Square';
      $this->icon = 'square-logo';
      $this->refresh_interval = 7 * DAY_IN_SECONDS;
      $this->newOrder = [
         'post_type'    => $this->orderPostType,
         'post_status'  => 'PROPOSED',
      ];
      // Define credential fields
      $this->fields = [
         'environment'  => [
@@ -176,7 +213,9 @@
         ]
      );
      add_action('init', [$this, 'registerSquarePostTypes']);
      add_action('init', [$this, 'registerSquarePostTypes'], 5);
      add_action('init', [$this, 'addDashboardPages'], 10);
      add_action(BASE.'dashboard_page_orders', [$this, 'renderDashPage']);
   }
   /**
@@ -213,14 +252,9 @@
   }
   public function getSquarePostConfig(string $post = 'all'):array
   public function getOrderFields():array
   {
      $posts = [
         '_sq_orders' => [
            'singular'  => 'Square Order',
            'plural' => 'Square Orders',
            'public' => false,
            'fields' => [
      return [
               'post_title' => [
                  'type' => 'text',
                  'label' => 'Order Number'
@@ -228,24 +262,20 @@
               'square_order_id' => [
                  'type' => 'text',
                  'label' => 'Square Order ID',
                  'readonly' => true
               ],
               'square_payment_id' => [
                  'type' => 'text',
                  'label' => 'Square Payment ID',
                  'readonly' => true
               ],
               'square_customer_id' => [
                  'type' => 'text',
                  'label' => 'Square Customer ID',
                  'readonly' => true
               ],
               'amount' => [
                  'type' => 'number',
                  'label' => 'Total Amount (cents)',
                  'readonly' => true
               ],
               'status' => [
               'square_payment_status' => [
                  'type' => 'select',
                  'label' => 'Order Status',
                  'options' => [
@@ -255,7 +285,6 @@
                     'COMPLETED' => 'Completed',
                     'CANCELED' => 'Canceled'
                  ],
                  'readonly' => true
               ],
               'fulfillment_status' => [
                  'type' => 'select',
@@ -268,7 +297,6 @@
                     'CANCELED' => 'Canceled',
                     'FAILED' => 'Failed'
                  ],
                  'readonly' => true
               ],
               'pickup_time' => [
                  'type' => 'datetime',
@@ -277,27 +305,23 @@
               'customer_email' => [
                  'type' => 'email',
                  'label' => 'Customer Email',
                  'readonly' => true
               ],
               'customer_name' => [
                  'type' => 'text',
                  'label' => 'Customer Name',
                  'readonly' => true
               ],
               'customer_phone' => [
                  'type' => 'tel',
                  'type' => 'phone',
                  'label' => 'Customer Phone',
                  'readonly' => true
                  'section'=> 'your-account'
               ],
               'special_instructions' => [
                  'type' => 'textarea',
                  'label' => 'Special Instructions',
                  'readonly' => true
               ],
               'items' => [
                  'type' => 'repeater',
                  'label' => 'Order Items',
                  'readonly' => true,
                  'fields' => [
                     'name' => ['type' => 'text', 'label' => 'Item Name'],
                     'quantity' => ['type' => 'number', 'label' => 'Quantity'],
@@ -308,36 +332,29 @@
               'receipt_url' => [
                  'type' => 'url',
                  'label' => 'Receipt URL',
                  'readonly' => true
               ],
               'created_at' => [
                  'type' => 'datetime',
                  'label' => 'Created At',
                  'readonly' => true
               ],
               'updated_at' => [
                  'type' => 'datetime',
                  'label' => 'Last Updated',
                  'readonly' => true
               ]
            ]
         ]
      ];
      if ($post === 'all'){
         return $posts;
      }elseif(array_key_exists($post, $posts)) {
         return $posts[$post];
      }
      return [];
            ];
   }
   public function registerSquarePostTypes():void
   {
      $squarePostTypes = $this->getSquarePostConfig();
      foreach ($squarePostTypes as $slug => $config) {
         $registrar = new PostTypeRegistrar($slug, $config);
         $registrar->register();
      $orders = Registrar::forPost($this->orderPostType, 'Square Order', 'Square Orders');
      $orders->make([
         'public' => true
      ]);
      $orders->setAll(['system']);
      $fields = $orders->fields();
      foreach ($this->getOrderFields() as $fieldName => $config) {
         $fields->addField($fieldName, $config);
      }
   }
@@ -379,8 +396,6 @@
    */
   protected function exchangeOAuthCode(string $code): ?array
   {
      error_log('Exchanging tokens with credentials: '.print_r($this->credentials, true));
      $this->ensureInitialized();
      // Prepare the request body as an array
@@ -406,7 +421,6 @@
      }
      $data = json_decode(wp_remote_retrieve_body($response), true);
      error_log('OAuth Response: '.print_r($data, true));
      if (isset($data['access_token'])) {
         return [
            'access_token' => $data['access_token'],
@@ -468,7 +482,6 @@
      $data = json_decode(wp_remote_retrieve_body($response), true);
      error_log('RefreshAccessToken Response: '.print_r($data, true));
      if (isset($data['access_token'])) {
         $this->credentials['access_token'] = $data['access_token'];
         $this->credentials['expires_at'] = time() + ($data['expires_in'] ?? 2592000); // 30 days
@@ -491,7 +504,6 @@
   {
      // Skip if we don't have credentials yet (during OAuth flow)
      if (empty($this->credentials['access_token'])) {
         error_log('[Square] Skipping loadLocations - no access token yet');
         return;
      }
      try {
@@ -777,8 +789,8 @@
                  'name' => $variation['name'],
                  'pricing_type' => 'FIXED_PRICING',
                  'price_money' => [
                     'amount' => intval($variation['price'] * 100), // Convert to cents
                     'currency' => 'USD'
                     'amount' => $this->formatPrice($variation['_square_price']??0),
                     'currency' => $this->getCurrency()
                  ]
               ]
            ];
@@ -792,8 +804,8 @@
               'name' => 'Regular',
               'pricing_type' => 'FIXED_PRICING',
               'price_money' => [
                  'amount' => intval(($itemData['price'] ?? 0) * 100),
                  'currency' => 'USD'
                  'amount' => $this->formatPrice($itemData['_square_price'] ?? 0),
                  'currency' => $this->getCurrency()
               ]
            ]
         ];
@@ -848,230 +860,69 @@
      if (!$this->isSetUp()) {
         return;
      }
      // User login tracking for security
      add_action('wp_login', [$this, 'trackUserLogin'], 10, 2);
      // Enqueue checkout scripts
      add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
        add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
      add_filter('jvbAdditionalActions', [$this, 'outputCheckout']);
   }
      add_filter('jvbAdditionalActions', [Checkout::class, 'render']);
   public function outputCheckout(array $actions):array {
      if (is_singular(BASE.'dash') || is_post_type_archive(BASE.'dash')) {
         return $actions;
      }
      $meta = new MetaForm();
      $form = '<aside id="cart" class="right main">
         <form id="checkout" data-form-id="checkout" data-save="checkout">';
            $tabs = [
               'cartItems' => [
                  'title'  => 'Your Order',
                  'icon'   => 'cart',
                  'description' => 'Here\'s your order. You can change quantities, remove items, or clear your cart.',
                  'content'   => $this->cartContent()
               ],
               'checkout'  => [
         'title'  => 'Checkout',
         'icon'   => 'checkout',
         'description' => 'Securely checkout with your name, email, and payments processed by Square.',
         'content'   => '<div class="checkout-section">
                        <h3>Customer Information</h3>
                        '.$meta->return('cart_name', null, [
                           'type'      => 'text',
                           'label'     => 'Your Name',
                           'required'  => true,
                           'autocomplete' => 'name'
                        ]).
                        $meta->return('cart_email', null, [
                           'type'      => 'email',
                           'label'     => 'Your Email',
                           'required'  => true,
                           'autocomplete'=> 'email',
                        ]).
                        $meta->return('cart_phone', null, [
                           'type'      => 'tel',
                           'label'     => 'Your Phone',
                           'required'  => true,
                           'autocomplete'=> 'phone'
                        ]).'
                        <h3>Pickup Details</h3>'.
                        $meta->return('pickup_time', null, [
                           'type'      => 'datetime',
                           'label'     => 'Pickup Type',
                           'min'    => '11:00',
                           'max'    => '20:00',
                           'required'  => true,
                        ]).
                        $meta->return('special_instructions', null, [
                           'type'      => 'textarea',
                           'label'     => 'Special Instructions',
                           'quill'     => true,
                        ]).'
                        <textarea name="special_instructions" placeholder="Special instructions or dietary notes"></textarea>
                     </div>
                     <div class="checkout-section">
                        <h3>Payment Information</h3>
                        <div id="saved-cards"></div>
                        <div id="square-card-container"></div>
                     </div>'
      ],
               'order'  => [
         'title'  => 'Your Order',
         'icon' => 'truck',
         'hidden' => true,
         'description' => '',
         'content'   => $this->renderOrderStatus()
      ]
            ];
      $form .= jvbRenderTabs($tabs, true);
      $form .= '<div class="cart-total row end"><p class="tax">Tax: <span></span></p><p class="total">GRAND TOTAL: <span></span></p></div>
      </form>
      </aside>
      <template class="restoredCart">
         <div class="restored">
            <h3>Looks like we left things hanging</h3>
            <p>We\'ve restored your cart from your last session below.</p>
            <p>If you\'d rather start over, click the button below.</p>
            <div class="row btw">
               <button type="button" onclick="window.squareCheckout.clearCart();this.closest(\'.restored\').remove()">'.jvbIcon('trash').'Clear Cart</button>
               <button type="button" onclick="this.closest(\'.restored\').remove()">'.jvbIcon('x').'Dismiss</button>
            </div>
         </div>
      </template>
      <template class="cartItem">
         <tr class="item">
            <td class="item">
               <label for="quantity"></label>
               <div class="quantity field" data-min="0" data-max="50" data-step="1" data-price="17" data-id="">
                  <button type="button" class="decrease"aria-label="Decrease Add to Order">'.jvbIcon('minus-square').'</button>
                  <input type="number" id="quantity" name="quantity" value="0" min="0" max="50" step="1" class="quantity-input">
                  <button type="button" class="increase" aria-label="Increase Add to Order">'.jvbIcon('plus-square').'</button>
               </div>
            </td>
            <td class="price">
               <span class="price"></span>
            </td>
            <td class="total">
               <span class="total"></span>
            </td>
            <td>
               <button type="button" data-remove-from-cart>'.jvbIcon('trash').'</button>
            </td>
         </tr>
      </template>
      <template class="emptyCart">
         <div class="empty">
            <p><i><b>No items in cart.</b></i></p>
            <p>You can <a href="'.get_post_type_archive_link(BASE.'menu_item').'" title="Browse our menu">browse our menu</a> to order.</p>
         </div>
      </template>';
      $actions[] = [
         'button' =>    '<button type="button" class="toggle-cart row" title="Your Cart" data-action="toggle-cart" aria-label="Open Cart" aria-controls="checkout" aria-expanded="false">
               '.jvbIcon('shopping-cart').'<span class="abs"></span><span class="abs count"></span>
            </button>',
         'content' =>   $form
      ];
      return $actions;
   }
   private function cartContent():string
   {
      ob_start();
      ?>
      <div class="cart-items">
         <table>
            <thead>
               <tr>
                  <th scope="col">Item</th>
                  <th scope="col">Price</th>
                  <th scope="col">Total</th>
               </tr>
            </thead>
            <tbody>
            </tbody>
         </table>
      </div>
      <details class="account">
         <summary>
            <?php
            if (is_user_logged_in()) {
               echo 'Your Favourites and Order History';
            } else {
               echo '<a href="'.wp_login_url(get_the_permalink()).'">Log in</a> to save your favourites and view order history.';
            }
            ?>
         </summary>
         <?php
         if (is_user_logged_in()) {
            $tabs = [
               'history' => [
                  'title'  => 'Order History',
                  'icon' => 'checkout',
                  'description' => 'View your past orders and quickly reorder',
                  'content'   => $this->renderOrderHistory()
               ],
               'favourites' => [
                  'title'  => 'Favourites',
                  'icon'   => 'heart',
                  'description'  => 'View your favourites from our menu',
                  'content'      => $this->renderFavourites()
               ]
            ];
            jvbRenderTabs($tabs);
      add_filter('jvb_checkout_description', function (string $desc, string $provider) {
         if ($provider === 'square') {
            return 'Securely checkout with your name, email, and payments processed by Square.';
         }
         return $desc;
      }, 10, 2);
         ?>
      </details>
      // Square-specific pickup fields (extracted from old outputCheckout)
      add_filter('jvb_checkout_fields', [$this, 'addPickupFields'], 10, 2);
      <?php
      return ob_get_clean();
      // Browse URL for this client (restaurant menu)
      add_filter('jvb_checkout_browse_url', function () {
         return get_post_type_archive_link(BASE . 'menu_item');
      });
      add_filter('jvb_checkout_browse_text', function () {
         return 'browse our menu';
      });
   }
   private function renderOrderHistory():string
   /**
    * Pickup/ordering fields for the shared checkout form.
    * Specific to this Square client's food ordering use case.
    */
   public function addPickupFields(string $html, string $provider): string
   {
      ob_start();
      //TODO: getRequest, cache for 1 day
      return ob_get_clean();
   }
   private function renderFavourites():string
   {
      ob_start();
      //TODO: get user's favourites and list them
      return ob_get_clean();
      if ($provider !== 'square') {
         return $html;
      }
      return $html
         . '<h3>Pickup Details</h3>'
         . Form::render('pickup_time', null, [
            'type'     => 'datetime',
            'label'    => 'Pickup Time',
            'min'      => '11:00',
            'max'      => '20:00',
            'required' => true,
         ])
         . Form::render('special_instructions', null, [
            'type'  => 'textarea',
            'label' => 'Special Instructions',
            'quill' => true,
         ]);
   }
   protected function renderOrderStatus():string
   protected function registerAdditionalQueueTypes(IntegrationExecutor $executor): void
   {
      ob_start();
      ?>
      <div class="order-confirmation">
         <h2>Order Confirmed!</h2>
         <div id="order-status" data-order="">
            <p>Order #<span class="order-num"></span></p>
            <div class="status-timeline">
               <div class="status-item active" data-status="received">Order Received</div>
               <div class="status-item" data-status="preparing">Preparing</div>
               <div class="status-item" data-status="ready">Ready for Pickup</div>
            </div>
            <div class="pickup-time">
               Estimated pickup: <span id="eta">Calculating...</span>
            </div>
         </div>
      </div>
      <?php
      return ob_get_clean();
      $queue    = JVB()->queue();
      $queue->registry()->register(self::$syncCustomer, new TypeConfig(
         executor:   $executor,
         maxRetries: 2
      ));
      $queue->registry()->register(self::$import, new TypeConfig(
         executor:   $executor,
         maxRetries: 3
      ));
   }
   /******************************************************************
@@ -1083,17 +934,15 @@
    */
   protected function handleTheSavePost(int $postID, \WP_Post $post, bool $update, array $settings): void
   {
      error_log('Queuing Sync to Square');
      // Queue the sync operation
      $this->queueOperation('sync_to_square', [
         'items' => [$postID],
         'user_id' => $this->userID
      error_log('==== [Square]::handleTheSavePost ====');
      $this->queueOperation(self::$syncTo, [
         'items'   => [$postID],
         'user'      => user_can($post->post_author, 'manage_options') ? null : $post->post_author
      ], [
         'priority' => 'high',
         'delay' => 30, // Small delay to batch multiple saves
         'delay'    => 30,
      ]);
      update_post_meta($postID, BASE . '_square_sync_status', 'queued');
      Meta::forPost($postID)->set('_'.$this->service_name.'_sync_status', 'queued');
   }
   /**
@@ -1101,41 +950,18 @@
    */
   public function handleDeletePost(int $postID): void
   {
      $square_id = get_post_meta($postID, BASE . '_square_catalog_id', true);
      $item_id = $this->getServiceItemID($postID);
      if ($square_id) {
         $this->queueOperation('delete_from_square', [
            'square_ids' => [$square_id],
            'post_id' => $postID
         ], [
            'priority' => 'high'
         ]);
      if (empty($item_id)) {
         return;
      }
   }
      $this->queueOperation(self::$deleteFrom, [
         'external_ids' => [$item_id],
         'post_id'      => $postID,
      ], [
         'priority' => 'high',
      ]);
   /**
    * Process queued operations
    */
   public function processOperation(WP_Error|array $result, object $operation, array $data): WP_Error|array
   {
      $base = strtolower($this->service_name).'_';
      $square = (array_key_exists('user', $data)) ? new self((int)$data['user']) : $this;
      switch ($operation->type) {
         case $base.'sync_to_square':
            return $square->processSyncToSquare($data);
         case $base.'delete_from_square':
            return $square->processDeleteFromSquare($data);
         case $base.'sync_from_square':
            return $square->processSyncFromSquare($data);
         case $base.'sync_customer':
            return $square->processSyncCustomer($data);
         default:
            return $result;
      }
   }
   /**
@@ -1189,19 +1015,6 @@
         if (!is_wp_error($response)) {
            $this->processBatchSyncResponse($response, $map, $success, $errors);
            $square_id = $response['objects'][0]['id'];
            update_post_meta($postID, BASE . '_square_catalog_id', $square_id);
            update_post_meta($postID, BASE . '_square_sync_status', 'synced');
            update_post_meta($postID, BASE . '_square_last_sync', current_time('mysql'));
            // Save variation IDs
            if (!empty($response['objects'][0]['item_data']['variations'])) {
               foreach ($response['objects'][0]['item_data']['variations'] as $index => $variation) {
                  update_post_meta($postID, BASE . '_square_variation_' . $index . '_id', $variation['id']);
               }
            }
            $success[] = $postID;
         } else {
            // Handle batch request failure
            $error_message = 'Batch sync failed';
@@ -1232,6 +1045,9 @@
   private function processBatchSyncResponse(array $response, array $map, array &$success, array &$errors):void
   {
      error_log('==== SQUARE::processBatchSyncResponse =====');
      error_log('Full response: '.print_r($response, true));
      // Handle successful objects
      if (!empty($response['objects'])) {
         foreach ($response['objects'] as $object) {
@@ -1318,6 +1134,7 @@
    * @param string|null $square_image_id Previously uploaded Square image ID
    * @return array|WP_Error Catalog object or error
    */
   //TODO: Get to work with Registrar settings
   protected function buildCatalogObject(int $postID, ?string $square_image_id = null): array|WP_Error
   {
      $post = get_post($postID);
@@ -1325,11 +1142,19 @@
         return new WP_Error('post_not_found', "Post $postID not found");
      }
      $meta = new MetaManager($postID, 'post');
      $meta = Meta::forPost($postID);
      $post_type = get_post_type($postID);
      // Get existing Square catalog ID if it exists
      $existing_square_id = get_post_meta($postID, BASE . '_square_catalog_id', true);
      $registrar = Registrar::getInstance($post_type);
      $product_type = 'FOOD_AND_BEV';
      if ($registrar) {
         $conf = $registrar->getIntegration($this->service_name);
         if ($conf) {
            $product_type = $conf->getContentType();
         }
      }
      // Build the base catalog object
      $catalog_object = [
@@ -1338,7 +1163,7 @@
         'item_data' => [
            'name' => $post->post_title,
            'description' => wp_strip_all_tags($post->post_content),
            'product_type' => 'FOOD_AND_BEV',
            'product_type' => $product_type,
            'variations' => [],
            'is_taxable' => true,
         ]
@@ -1350,10 +1175,9 @@
      }
      // Add variations
      $variations = $meta->getValue('product_variations');
      $variations = $meta->get('_square_product_variations');
      if (empty($variations)) {
         // Create default variation if none exist
         $price = floatval($meta->getValue('price') ?: 0);
         $catalog_object['item_data']['variations'][] = [
            'type' => 'ITEM_VARIATION',
            'id' => $existing_square_id ? null : '#'.BASE.'menu_item_' . $postID . '_var_default',
@@ -1362,32 +1186,41 @@
               'ordinal' => 0,
               'pricing_type' => 'FIXED_PRICING',
               'price_money' => [
                  'amount' => intval($price * 100), // Convert dollars to cents
                  'currency' => 'CAD'
                  'amount' => $this->formatPrice($meta->get('_square_price')),
                  'currency' => $this->getCurrency()
               ],
               'sellable' => true,
               'stockable' => true
            ]
         ];
      } else {
         $resetVariations = false;
         foreach ($variations as $index => $variation) {
            $existing_var_id = get_post_meta($postID, BASE . '_square_variation_' . $index . '_id', true);
            $id = '#'.BASE.'menu_item_' . $postID . '_var_' . $index;
            if (empty($variation['item_id'])) {
               $resetVariations = true;
               $variations[$index]['item_id'] = $id;
               $variation['item_id'] = $id;
            }
            $catalog_object['item_data']['variations'][] = [
               'type' => 'ITEM_VARIATION',
               'id' => $existing_var_id ?: '#'.BASE.'menu_item_' . $postID . '_var_' . $index,
               'id' => $variation['item_id'],
               'item_variation_data' => [
                  'name' => $variation['name'] ?? 'Variation ' . ($index + 1),
                  'ordinal' => $index,
                  'pricing_type' => 'FIXED_PRICING',
                  'price_money' => [
                     'amount' => intval(floatval($variation['price'] ?? 0) * 100),
                     'currency' => 'CAD'
                     'amount' =>$this->formatPrice($variation['price'] ?? 0),
                     'currency' => $this->getCurrency()
                  ],
                  'sellable' => true,
                  'stockable' => true
               ]
            ];
         }
         if ($resetVariations) {
            $meta->set('_square_product_variations', $variations);
         }
      }
      // Add categories if they exist
@@ -1406,7 +1239,7 @@
      }
      // Add modifiers if they exist
      $modifiers = $meta->getValue('modifiers');
      $modifiers = $meta->get('modifiers');
      if (!empty($modifiers)) {
         $modifier_ids = [];
         foreach ($modifiers as $modifier) {
@@ -1422,7 +1255,7 @@
      }
      // Add tax settings
      $tax_ids = $meta->getValue('tax_ids');
      $tax_ids = $meta->get('tax_ids');
      if (!empty($tax_ids)) {
         $catalog_object['item_data']['tax_ids'] = $tax_ids;
      }
@@ -1430,118 +1263,32 @@
      return $catalog_object;
   }
   /**
    * Build variations from repeater field
    */
   private function buildVariations(int $postID, array $values, string $post_type): array
   {
      $variations = [];
      $product_variations = $values['product_variations'] ?? [];
      // Get variation field mapping
      $variation_map = $this->getVariationMapping($post_type);
      // If we have repeater variations
      if (!empty($product_variations) && is_array($product_variations)) {
         foreach ($product_variations as $index => $variation_data) {
            // Skip empty variations
            if (empty($variation_data['name']) && empty($variation_data['sku'])) {
               continue;
            }
            $variation = [
               'type' => 'ITEM_VARIATION',
               'id' => '#' . $post_type . '_' . $postID . '_var_' . $index,
               'item_variation_data' => [
                  'name' => $variation_data['name'] ?? 'Variation ' . ($index + 1),
                  'ordinal' => $index,
                  'pricing_type' => 'FIXED_PRICING'
               ]
            ];
            // Check for existing Square variation ID
            $square_var_id = get_post_meta($postID, BASE . '_square_variation_' . $index . '_id', true);
            if ($square_var_id) {
               $variation['id'] = $square_var_id;
            }
            // Map variation fields
            foreach ($variation_map as $square_field => $wp_field) {
               if (isset($variation_data[$wp_field])) {
                  switch ($square_field) {
                     case 'price':
                        $variation['item_variation_data']['price_money'] = [
                           'amount' => intval($variation_data[$wp_field] * 100), // Convert to cents
                           'currency' => 'CAD'
                        ];
                        break;
                     case 'sku':
                        $variation['item_variation_data']['sku'] = $variation_data[$wp_field];
                        break;
                     case 'track_inventory':
                        $variation['item_variation_data']['track_inventory'] = (bool)$variation_data[$wp_field];
                        break;
                     case 'service_duration':
                        if (!empty($variation_data[$wp_field])) {
                           $variation['item_variation_data']['service_data'] = [
                              'duration_minutes' => intval($variation_data[$wp_field])
                           ];
                        }
                        break;
                     default:
                        $variation['item_variation_data'][$square_field] = $variation_data[$wp_field];
                        break;
                  }
               }
            }
            $variations[] = $variation;
         }
      }
      // If no variations exist, create a default one from base price
      if (empty($variations) && !empty($values['price'])) {
         $variations[] = [
            'type' => 'ITEM_VARIATION',
            'id' => '#' . $post_type . '_' . $postID . '_var_default',
            'item_variation_data' => [
               'name' => 'Regular',
               'ordinal' => 0,
               'pricing_type' => 'FIXED_PRICING',
               'price_money' => [
                  'amount' => intval($values['price'] * 100),
                  'currency' => 'CAD'
               ]
            ]
         ];
      }
      return $variations;
   }
   /**
    * Get variation mapping for post type
    */
   protected function getVariationMapping(string $post_type): array
   {
      $product_type = JVB_CONTENT[jvbNoBase($post_type)]['integrations']['square']['content_type'] ?? 'REGULAR';
      $registrar = Registrar::getInstance($post_type);
      if (!$registrar) {
         return [];
      }
      $config = $registrar->getIntegrationConfig($this->service_name);
      $product_type = $config['content_type']??'REGULAR';
      $valid_fields = $this->getValidFieldsForProductType($product_type);
      $defaults = [
         'name' => 'name',
         'id' => '_square_catalog_id',
         'sku' => 'sku',
         'price' => 'price',
         'track_inventory' => 'track_inventory',
         'service_duration' => 'service_duration',
         'available_for_booking' => 'available_for_booking',
         'gift_card_type' => 'gift_card_type',
         'ingredients' => 'ingredients',
         'preparation_time_duration' => 'preparation_time_duration'
         'id' => '_square_item_id',
         'sku' => '_square_sku',
         'price' => '_square_price',
         'track_inventory' => '_square_track_inventory',
         'service_duration' => '_square_service_duration',
         'available_for_booking' => '_square_available_for_booking',
         'gift_card_type' => '_square_gift_card_type',
         'ingredients' => '_square_ingredients',
         'preparation_time_duration' => '_square_preparation_time_duration'
      ];
      $extended = apply_filters(
@@ -1597,7 +1344,12 @@
    */
   protected function getFieldMapping(string $post_type): array
   {
      $product_type = JVB_CONTENT[jvbNoBase($post_type)]['integrations']['square']['content_type'] ?? 'REGULAR';
      $registrar = Registrar::getInstance($post_type);
      if (!$registrar) {
         return [];
      }
      $config = $registrar->getIntegrationConfig($this->service_name);
      $product_type = $config['content_type']??'REGULAR';
      $valid_fields = $this->getValidFieldsForProductType($product_type);
      $defaults = [
@@ -1605,15 +1357,15 @@
         'description_html' => 'post_content',
         'abbreviation' => 'abbreviation',
         'id' => '_square_catalog_id',
         'sku' => 'sku',
         'sku' => '_square_sku',
         'category_id' => 'category',
         'image_ids' => 'post_thumbnail',
         'price' => 'price',
         'price' => '_square_price',
         'tax_ids' => 'tax_ids',
         // Availability
         'available_online' => 'available_online',
         'available_for_pickup' => 'available_for_pickup',
         'available_electronically' => 'available_electronically',
         'available_online' => '_square_available_online',
         'available_for_pickup' => '_square_available_for_pickup',
         'available_electronically' => '_square_available_electronically',
         // Modifiers
         'modifier_list_info' => 'modifiers',
         // Item options
@@ -1637,6 +1389,7 @@
   /**
    * Get valid fields for Square product type
    */
   //TODO: This feels redundant now, with how we've defined fields in getAdditionalFields
   private function getValidFieldsForProductType(string $product_type): array
   {
      $fields = ['name', 'description_html', 'sku', 'price', 'image_ids', 'category_id'];
@@ -1680,6 +1433,7 @@
   /**
    * Handle customer authentication during checkout
    */
   //TODO: Is this necessary?
   public function handleCustomerAuth($data):WP_Error|array
   {
      $email = sanitize_email($data['email'] ?? '');
@@ -1730,7 +1484,8 @@
               'message' => 'Email found. Would you like to create an account to save your order history?'
            ];
         }
      } else {
      }
         // Check Square for customer
         $response = $this->postRequest('customers/search', [
            'filter' => [
@@ -1753,7 +1508,6 @@
               'message' => 'New customer'
            ];
         }
      }
   }
   private function createCustomerAccount(string $email):WP_Error|array
@@ -1772,13 +1526,9 @@
         ];
      }
      // Generate username from email
      $username = sanitize_user(current(explode('@', $email)));
      $username = $this->generateUniqueUsername($username);
      // Create user account without password (they'll set it via email)
      $user_id = wp_create_user(
         $username,
         $email,
         wp_generate_password(20, true, true), // Temporary random password
         $email
      );
@@ -1793,7 +1543,7 @@
      // Set user role (assuming you have a customer role defined)
      $user = new \WP_User($user_id);
      $user->set_role(BASE.'foodie'); // Or whatever role from JVB_USER
      $user->set_role(BASE.'foodie');
      // Generate password reset key
      $reset_key = get_password_reset_key($user);
@@ -1809,7 +1559,7 @@
      // Link to Square customer if exists
      $square_customer_id = $this->getOrCreateSquareCustomer([
         'email' => $email,
         'name' => $username
         'name' => $email
      ]);
      if ($square_customer_id) {
@@ -1824,22 +1574,6 @@
   }
   /**
    * Generate unique username
    */
   private function generateUniqueUsername(string $base): string
   {
      $username = $base;
      $counter = 1;
      while (username_exists($username)) {
         $username = $base . $counter;
         $counter++;
      }
      return $username;
   }
   /**
    * Send welcome email with password setup
    */
   private function sendWelcomeEmail(\WP_User $user, string $reset_key): void
@@ -1849,17 +1583,19 @@
      $message = sprintf(
         "Welcome to %s!\n\n" .
         "Your account has been created. Please click the link below to set your password:\n\n" .
         "Your account has been created. Please click the button below to set your password:\n\n" .
         "%s\n\n" .
         "Once you've set your password, you can log in to:\n" .
         "Or, copy and paste the link below:\n\n".
         "%s\n\n" .
         "Once you've set your password, you can:\n" .
         "- View your order history\n" .
         "- Save your favorite items\n" .
//       "- Save your favorite items\n" .
         "- Speed up checkout with saved payment methods\n\n" .
         "If you didn't create this account, please ignore this email.\n\n" .
         "Thanks,\n%s",
         "Thanks,\n",
         $site_name,
         $reset_url,
         $site_name
         JVB()->email()->button('Reset Password', $reset_url),
         JVB()->email()->link($reset_url),
      );
      JVB()->email()->sendEmail(
@@ -1869,51 +1605,6 @@
      );
   }
   /**
    * Track user login for security
    */
   public function trackUserLogin(string $user_login, \WP_User $user): void
   {
      // Check if user has Square integration
      $roles = array_keys(JVB_USER);
      $user_roles = $user->roles;
      foreach ($user_roles as $role) {
         if (isset(JVB_USER[$role]['integrations']['square']['is_customer'])) {
            $login_count = (int)get_user_meta($user->ID, BASE . '_square_login_count', true);
            $login_count++;
            update_user_meta($user->ID, BASE . '_square_login_count', $login_count);
            update_user_meta($user->ID, BASE . '_square_last_login', current_time('mysql'));
            // Check if password reset is needed
            if ($login_count % self::PASSWORD_RESET_INTERVAL === 0) {
               $this->schedulePasswordReset($user->ID);
            }
            break;
         }
      }
   }
   /**
    * Schedule password reset for security
    */
   private function schedulePasswordReset(int $user_id): void
   {
      update_user_meta($user_id, BASE . '_square_password_reset_required', true);
      // Send notification
      $user = get_user_by('ID', $user_id);
      if ($user) {
         JVB()->email()->sendEmail(
            $user->user_email,
            '['.get_bloginfo('name').'] Security Code',
            'For your security, enter this code to continue accessing your account and saved payment methods.',
         );
      }
   }
   /******************************************************************
    * WEBHOOK HANDLING
    ******************************************************************/
@@ -1994,9 +1685,6 @@
   /**
    * Handle order status webhook
    */
   /**
    * Handle order status webhook - NOW UPDATES POST TYPE
    */
   private function handleOrderWebhook(array $data): bool
   {
      $order_id = $data['object']['order']['id'] ?? '';
@@ -2008,11 +1696,11 @@
      }
      // Find the WP post for this order
      $wp_order_id = get_option(BASE . 'square_order_map_' . $order_id);
      $wp_order_id = $this->getOrderPost($order_id);
      if ($wp_order_id) {
         // Update the post meta
         $meta = new MetaManager($wp_order_id, 'post');
         $meta = Meta::forPost($wp_order_id);
         $updates = [
            'status' => $state,
            'updated_at' => current_time('mysql')
@@ -2035,10 +1723,6 @@
            do_action(BASE . 'square_order_ready', $wp_order_id, $order_id);
         }
      }
      // Also update transient cache for quick status checks
      set_transient(BASE . 'square_order_' . $order_id, $state, HOUR_IN_SECONDS);
      // Trigger action for other integrations
      do_action(BASE . 'square_order_updated', $order_id, $state, $data);
@@ -2102,8 +1786,9 @@
   /**
    * Enqueue checkout scripts with Square configuration
    */
   public function enqueueScripts():void
   public function enqueueScripts(): void
   {
      jvbInlineStyles('forms');
      $this->loadCredentials();
      $sdk_url = $this->environment === 'production'
         ? 'https://web.squarecdn.com/v1/square.js'
@@ -2114,50 +1799,38 @@
         $sdk_url,
         [],
         null,
         [
            'strategy' => 'defer',
            'in_footer' => true
         ]
         ['strategy' => 'defer', 'in_footer' => true]
      );
      // Register your custom checkout script
      // Shared cart checkout base class
      wp_register_script(
         'jvb-checkout',
         JVB_URL . 'assets/js/min/checkout.min.js',
         ['jvb-utility', 'jvb-queue', 'jvb-a11y', 'jvb-cache', 'jvb-tabs', 'jvb-popup', 'jvb-login'],
         '1.1.32',
         ['strategy' => 'defer', 'in_footer' => true]
      );
      // Square checkout extends CartCheckout
      wp_register_script(
         'jvb-square-checkout',
         JVB_URL . 'assets/js/min/square.min.js',
         [
//          'square-payments-sdk',
            'jvb-utility',
            'jvb-queue',
            'jvb-a11y',
            'jvb-cache',
            'jvb-tabs',
            'jvb-popup'
         ],
         '1.0.0',
         [
            'strategy' => 'defer',
            'in_footer' => true
         ]
         ['jvb-checkout', 'square-payments-sdk'],
         '1.1.32',
         ['strategy' => 'defer', 'in_footer' => true]
      );
      wp_enqueue_script('jvb-square-checkout');
      // Localize the checkout script with Square config
      wp_localize_script(
         'jvb-square-checkout',
         'squareConfig',
         [
            'isOpen' => jvbIsOpen(),
            'application_id' => $this->credentials['client_id'] ?? '',
            'location_id' => $this->locationId,
            'environment' => $this->environment,
            'api_url' => rest_url('jvb/v1/square/'),
            'nonce' => wp_create_nonce('wp_rest'),
            'currency' => get_option(BASE . 'currency', 'CAD'),
            'is_logged_in' => is_user_logged_in(),
            'user_email' => is_user_logged_in() ? wp_get_current_user()->user_email : '' // NEW
         ]
      );
      wp_localize_script('jvb-square-checkout', 'squareConfig', [
         'isOpen'         => jvbIsOpen()?'1':'0',
         'application_id' => $this->credentials['client_id'] ?? '',
         'location_id'    => $this->locationId,
         'environment'    => $this->environment,
         'currency'       => $this->getCurrency(),
         'is_logged_in'   => is_user_logged_in(),
         'user_email'     => is_user_logged_in() ? wp_get_current_user()->user_email : '',
      ]);
   }
   /******************************************************************
@@ -2167,7 +1840,7 @@
   /**
    * Get or create Square customer
    */
   private function getOrCreateSquareCustomer(array $customer_info): ?string
   public function getOrCreateSquareCustomer(array $customer_info): ?string
   {
      if (empty($customer_info['email'])) {
         return null;
@@ -2200,92 +1873,6 @@
      return null;
   }
   /**
    * Save order reference for status tracking
    */
   public function saveOrderReference($data): array
   {
      $order_id = sanitize_text_field($data['order_id'] ?? '');
      $payment_id = sanitize_text_field($data['payment_id'] ?? '');
      if (!$order_id) {
         return ['success' => false, 'message' => 'Invalid order data'];
      }
      // Save to user if logged in
      if (is_user_logged_in()) {
         $user_id = get_current_user_id();
         $orders = get_user_meta($user_id, BASE . '_square_orders', true) ?: [];
         $orders[] = [
            'order_id' => $order_id,
            'payment_id' => $payment_id,
            'date' => current_time('mysql'),
            'customer' => $data['customer'] ?? []
         ];
         // Keep last 50 orders
         if (count($orders) > 50) {
            $orders = array_slice($orders, -50);
         }
         update_user_meta($user_id, BASE . '_square_orders', $orders);
      }
      return [
         'success' => true,
         'order_id' => $order_id,
         'message' => 'Order saved'
      ];
   }
   /**
    * Save order to user meta
    */
   private function saveOrderToUser(int $user_id, string $order_id): void
   {
      $orders = get_user_meta($user_id, BASE . '_square_orders', true) ?: [];
      $orders[] = [
         'order_id' => $order_id,
         'date' => current_time('mysql')
      ];
      // Keep only last 50 orders
      if (count($orders) > 50) {
         $orders = array_slice($orders, -50);
      }
      update_user_meta($user_id, BASE . '_square_orders', $orders);
   }
   /**
    * Get order status (for customer feedback)
    */
   public function getOrderStatus($data): WP_Error|array
   {
      $order_id = sanitize_text_field($data['order_id'] ?? '');
      if (!$order_id) {
         return new WP_Error('error', 'Order ID required');
      }
      // Fetch from Square
      $response = $this->getRequest('v2/orders/' . $order_id);
      if (is_wp_error($response)) {
         return new WP_Error('error', 'Could not fetch order status');
      }
      $order = $response['order'] ?? [];
      $status_data = [
         'state' => $order['state'] ?? 'UNKNOWN',
         'fulfillment_eta' => $order['fulfillments'][0]['pickup_details']['pickup_at'] ?? null
      ];
      return [
         'success' => true,
         'status' => $status_data['state'],
         'eta' => $status_data['fulfillment_eta']
      ];
   }
   /**
    * Process delete from Square
@@ -2387,16 +1974,21 @@
    */
   private function importSquareItem(array $item): bool|int
   {
      //TODO: We need to add the post type to custom meta for Square, this is not good if we have multiple post types with the same product type
      // Find matching content type
      $product_type = $item['item_data']['product_type'] ?? 'REGULAR';
      $post_type = null;
      foreach (JVB_CONTENT as $key => $config) {
         if (isset($config['integrations']['square']['content_type']) &&
            $config['integrations']['square']['content_type'] === $product_type) {
            $post_type = jvbCheckBase($key);
      foreach (Registrar::getRegistered() as $registrar) {
         if (!$registrar->hasIntegration($this->service_name)) {
            continue;
         }
         $config = $registrar->getIntegration($this->service_name);
         if ($config->getContent_type() && $config->getContent_type() === $product_type) {
            $post_type = jvbCheckBase($registrar->getSlug());
            break;
         }
      }
      if (!$post_type) {
@@ -2440,7 +2032,7 @@
    */
   private function mapSquareFieldsToWordPress(int $post_id, array $item): void
   {
      $meta = new MetaManager($post_id, 'post');
      $meta = Meta::forPost($post_id);
      $field_map = $this->getFieldMapping(get_post_type($post_id));
      $values_to_save = [];
@@ -2456,7 +2048,7 @@
         foreach ($item['item_data']['variations'] as $index => $variation) {
            $var_data = [
               'name' => $variation['item_variation_data']['name'] ?? '',
               'sku' => $variation['item_variation_data']['sku'] ?? '',
               'sku' => $variation['item_variation_data']['_square_sku'] ?? '',
            ];
            // Extract price
@@ -2576,7 +2168,7 @@
         update_user_meta($user->ID, BASE . '_square_customer_updated', current_time('mysql'));
         // Clear cached customer data
         $this->cache->delete('square_customer_' . $user->ID);
         $this->cache->forget('square_customer_' . $user->ID);
      }
      return true;
@@ -2595,8 +2187,12 @@
         return false;
      }
      // Update cached payment status
      set_transient(BASE . 'square_payment_' . $payment_id, $status, HOUR_IN_SECONDS);
      if ($order_id) {
         $order = $this->getOrderPost($order_id);
         if ($order) {
            Meta::forPost($order)->set('square_payment_status', $status);
         }
      }
      // Trigger action for other integrations
      do_action(BASE . 'square_payment_updated', $payment_id, $status, $order_id, $data);
@@ -2807,7 +2403,6 @@
         // Validate environment setting
         if (isset($credentials['environment'])) {
            error_log('Environment: '.print_r($credentials['environment'], true));
            $validEnvironments = ['sandbox', 'production'];
            if (!in_array($credentials['environment'], $validEnvironments)) {
               $this->logError('Invalid environment setting', [
@@ -2897,12 +2492,83 @@
         'GIFT_CARD' => array_merge($this->setGiftCardFields())
      ];
   }
   public function getAdditionalFields(?string $content_type = null):array {
      if ($content_type === 'customer') {
         return $this->getCustomerFields();
      }
      if ($content_type && array_key_exists($content_type, $this->contentTypes)){
         $array = $this->contentTypes[$content_type];
         return array_combine(
            array_map(fn($k) => '_square_' . $k, array_keys($array)),
            $array
         );
      } else if ($content_type && !array_key_exists($content_type, $this->contentTypes)) {
         error_log('Could not get default fields for '.$this->service_name.' content type: '.$content_type);
         return [];
      }
      $array = $this->setBaseFields();
        return array_combine(
            array_map(fn($k) => '_square_' . $k, array_keys($array)),
            $array
        );
   }
   protected function getCustomerFields():array
   {
      return [
         'customer_id'  => [
            'type'   => 'text',
            'label'  => 'Square Customer ID',
            'hidden'=> true,
            'section'=> 'your-account'
         ],
         'address_line_1'  => [
            'type'   => 'text',
            'label'  => 'Address Line 1',
            'hint'   => 'ex: 6551 111 St NW',
            'required'  => true,
            'section'   => 'address'
         ],
         'address_line_2'  => [
            'type'   => 'text',
            'label'  => 'Address Line 2',
            'hint'   => 'ex: Unit 2',
            'section'   => 'address'
         ],
         'city'   => [
            'type'   => 'text',
            'label'=> 'City',
            'section'   => 'address',
            'required'  => true,
         ],
         'state' => [
            'type'   => 'text',
            'label' => 'Province',
            'hint' => 'The two-character code, example: AB',
            'default'=> 'AB',
            'section'   => 'address',
            'required'  => true,
         ],
         'zip_code' => [
            'type'   => 'text',
            'label'  => 'Postal Code',
            'section'=> 'address'
         ],
         'countryCode'  => [
            'type'   => 'text',
            'label'  => 'Country Code',
            'hint'   => 'The tw-character country code, example: CA',
            'default'   => 'CA',
            'section'   => 'address',
            'required'  => true,
         ]
      ];
   }
   protected function setBaseFields():array
   {
      return [
         'price' => [
            'type'        => 'number',
            'bulkEdit'    => true,
            'label'       => 'Price',
            'step'        => 0.01,
            'max'         => 99999,
@@ -2947,6 +2613,11 @@
            'label'       => 'Variation Name',
            'description' => 'e.g., "Small", "Large", "Red", etc.'
         ],
            'sku' => [
                'type'        => 'text',
                'label'       => 'SKU',
                'description' => 'Stock keeping unit'
            ],
         'price' => [
            'type'        => 'number',
            'label'       => 'Price',
@@ -2954,18 +2625,17 @@
            'max'         => 99999,
            'description' => 'Price for this variation'
         ],
         'track_inventory' => [
            'type'   => 'true_false',
            'label'  => 'Track Inventory',
         ],
         '_square_item_id' => [
         'item_id' => [
            'type'        => 'text',
            'label'       => 'Square Variation ID',
            'description' => 'Square catalog ID for this variation',
            'hidden'      => true
         ],
         '_square_last_sync' => [
         'last_sync' => [
            'type'   => 'datetime',
            'label'  => 'Last Sync',
            'hidden' => true
@@ -3006,7 +2676,10 @@
            ];
            break;
      }
      return $fields;
      return array_combine(
            array_map(fn($k) => '_square_' . $k, array_keys($fields)),
            $fields
        );
   }
   protected function setFoodAndBevFields():array
   {
@@ -3473,7 +3146,7 @@
      }
   }
   private function createSquareOrder(array $items, ?string $customer_id, array $data): array|WP_Error
   public function createSquareOrder(array $items, ?string $customer_id, array $data): array|WP_Error
   {
      // Build line items for Square
      $line_items = [];
@@ -3490,7 +3163,7 @@
            // Ad-hoc line item (not recommended - no tax/inventory automation)
            $line_item['name'] = $item['name'];
            $line_item['base_price_money'] = [
               'amount' => (int)$item['price'],
               'amount' => (int)$item['_square_price'],
               'currency' => $this->getCurrency()
            ];
         }
@@ -3530,7 +3203,7 @@
      return $this->postRequest('orders', $order_data);
   }
   private function createSquarePayment(
   public function createSquarePayment(
      string $source_id,
      string $idempotency_key,
      int $amount_cents,
@@ -3561,7 +3234,7 @@
      return $this->postRequest('payments', $payment_data);
   }
   private function saveOrderToWordPress(array $order_data): int
   public function saveOrderToWordPress(array $order_data): int
   {
      // Extract customer info
      $customer_email = $order_data['customer']['email'] ?? '';
@@ -3582,7 +3255,7 @@
      // Create order post
      $order_post_id = wp_insert_post([
         'post_type' => BASE . '_sq_orders',
         'post_type' => BASE.$this->orderPostType,
         'post_title' => 'Order #' . $order_data['square_order_id'],
         'post_status' => 'publish',
         'post_author' => $user_id // Associate with user if logged in
@@ -3594,10 +3267,9 @@
      }
      // Save all order meta
      $meta = new MetaManager($order_post_id, 'post');
      $fields = $this->getSquarePostConfig('_sq_orders')['fields'];
      $meta = Meta::forPost($order_post_id);
      $fields = $this->getOrderFields();
      unset($fields['post_title']);
      $meta->setFieldConfig($fields);
      $meta->setAll([
         'square_order_id' => $order_data['square_order_id'],
@@ -3617,9 +3289,6 @@
         'updated_at' => current_time('mysql')
      ]);
      // Index by Square order ID for quick webhook lookups
      update_option(BASE . 'square_order_map_' . $order_data['square_order_id'], $order_post_id);
      return $order_post_id;
   }
@@ -3674,20 +3343,157 @@
   public function checkOrderStatus(string $order_id): ?string
   {
      // Check transient cache first
      $cached = get_transient(BASE . 'square_order_' . $order_id);
      if ($cached) {
         return $cached;
      }
      // Fetch from Square
      $response = $this->getRequest('orders/' . $order_id);
      if (!is_wp_error($response)) {
         $state = $response['order']['state'] ?? null;
         set_transient(BASE . 'square_order_' . $order_id, $state, HOUR_IN_SECONDS);
         return $state;
      }
      return null;
   }
   /**
    * Single-item sync. Called by IntegrationExecutor::processSyncTo().
    * Delegates to syncBatchToService since Square uses batch-upsert.
    */
   public function syncPostToService(int $postID): array|WP_Error
   {
      return $this->syncBatchToService(['items' => [$postID]]);
   }
   /**
    * Batch sync — preferred by IntegrationExecutor when available.
    * Wraps existing processSyncToSquare which already handles batches.
    */
   public function syncBatchToService(array $data): array|WP_Error
   {
      $result = $this->processSyncToSquare($data);
      if (empty($result['success'])) {
         $errors = implode(', ', $result['result']['errors'] ?? ['Sync failed']);
         return new WP_Error('square_sync_failed', $errors);
      }
      return $result;
   }
   /**
    * Delete catalog object from Square.
    * Called by IntegrationExecutor::processDeleteFrom().
    */
   public function deleteFromService(string $externalId): array|WP_Error
   {
      $result = $this->processDeleteFromSquare(['square_ids' => [$externalId]]);
      if (empty($result['success'])) {
         return new WP_Error('square_delete_failed', $result['result']['error'] ?? 'Delete failed');
      }
      return $result;
   }
   /**
    * Import from Square catalog → WordPress.
    * Called by IntegrationExecutor::processImport().
    */
   public function importFromService(array $data): array|WP_Error
   {
      $result = $this->processSyncFromSquare($data);
      if (empty($result['success'])) {
         return new WP_Error('square_import_failed', $result['result']['error'] ?? 'Import failed');
      }
      return $result;
   }
   /**
    * Sync customer to Square.
    * Called by IntegrationExecutor::processSyncCustomer().
    */
   public function syncCustomer(array $data): array|WP_Error
   {
      $result = $this->processSyncCustomer($data);
      if (empty($result['success'])) {
         return new WP_Error('square_customer_sync_failed', $result['result']['error'] ?? 'Customer sync failed');
      }
      return $result;
   }
   public function addDashboardPages():void
   {
      $page = JVB()->dashboard()->addPage('Your Orders', 'orders', 'receipt');
      $page->setScripts(['jvb-crud']);
   }
   public function renderDashPage():void
   {
      $instance = $this->determineInstance();
      $crud = new CRUDSkeleton();
      $crud->icon('receipt');
      $crud->title('Your Orders','Here you can see your past orders, and reorder from there if you\'d like');
      $crud->content($this->orderPostType, 'Order', 'Orders');
      $crud->addSearch();
      $crud->addCapabilities(['view']);
      $crud->setEmptyState(sprintf(
         '<div class="empty-state">
            <h3>%sNothing here%s</h3>
            <p>It doesn\'t look like you have any orders yet.</p>
            <p>Head on over to <a href="%s">our menu</a> and make your first order!</p>
         </div>',
         jvbDashIcon($crud->getIcon()),
         jvbDashIcon($crud->getIcon()),
         get_post_type_archive_link(BASE.'menu_item')
      ));
      $crud->render();
   }
   protected function determineInstance():self
   {
      if (current_user_can('manage_options')) {
         return self::$instances['base'];
      }
      return self::getInstance(get_current_user_id());
   }
   public function getOrderPost(string $order_id):int|false
   {
      $posts = new WP_Query([
         'post_type'       => BASE.$this->orderPostType,
         'posts_per_page'  => 1,
         'meta_key'        => BASE.'square_order_id',
         'meta_value'      => $order_id,
         'fields'       => 'ids',
      ]);
      wp_reset_postdata();
      return $posts->have_posts() ? $posts[0] : false;
   }
   public function getOrderHistory(int $user_id):array
   {
      $posts = new WP_Query([
         'post_type'       => BASE.$this->orderPostType,
         'posts_per_page'  => 25,
         'author'       => $user_id,
         'orderby'         => 'date',
         'order'           => 'desc',
         'fields'       => 'ids',
      ]);
      wp_reset_postdata();
      return array_map(function ($post) {
         $fields = Meta::forPost($post);
         $fields['wp_order_id'] = $post;
         return $fields;
      }, $posts->posts);
   }
   public function formatPrice(string|float|int $priceValue):int
   {
      //Convert dollars to cents
      return intval(floatval($priceValue) * 100);
   }
}