<?php

namespace AC_SYNC\Includes\Classes\Sync {
  if (!defined('ABSPATH'))
    exit; // Exit if accessed directly
  use AC_SYNC\Includes\Classes\Setting\Action_Wear_Setting_Resync_Products as Resync_Products;

  class Action_Wear_Sync
  {

    const INITIAL = 0;
    const BRANDS_GENERATED = 24;
    const CATEGORIES_GENERATED = 39;
    const PRODUCTS_GENERATED = 76;
    const IMAGES_GENERATED = 100;

    /**
     * Maximum lock time in seconds before forced unlock (safety mechanism)
     */
    const MAX_LOCK_TIME = 300; // 5 minutes

    public static function getProgress()
    {
      return (int) get_option("_ACTIONWEAR_INITIAL_SYNC_PROGRESS");
    }

    public static function setProgress($p)
    {
      update_option("_ACTIONWEAR_INITIAL_SYNC_PROGRESS", $p);
    }

    public static function lock()
    {
      update_option("_ACTIONWEAR_LOCK", time());
    }

    /**
     * Lock status
     *
     * Return the lock status or unlock it if stuck (5 minutes or more locked)
     *
     **/
    public static function isLocked()
    {
      $lock = (int) get_option("_ACTIONWEAR_LOCK", 0);
      if ($lock > 0 && (time() - $lock > self::MAX_LOCK_TIME)) {
        self::unlock();
        return false;
      }
      return $lock > 0;
    }

    /**
     * Get the current lock age in seconds
     *
     * @return int|false Lock age in seconds, or false if not locked
     */
    public static function getLockAge()
    {
      $lock = (int) get_option("_ACTIONWEAR_LOCK", 0);
      if ($lock === 0) {
        return false;
      }
      return time() - $lock;
    }

    public static function unlock()
    {
      delete_option("_ACTIONWEAR_LOCK");
    }

    public static function getNbProductsToProcess()
    {
      global $wpdb;
      return (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}actionwear_products WHERE wc_to_create = 1 AND wc_created = 0");
    }

    public static function getRealWoocommerceProducts()
    {
      global $wpdb;
      return $wpdb->get_col("
        SELECT ap.sku
        FROM {$wpdb->prefix}actionwear_products ap
        INNER JOIN {$wpdb->prefix}wc_product_meta_lookup ml ON ml.sku = ap.sku
      ");
    }

    public static function getNbProductsProcessed()
    {
      global $wpdb;
      return (int) $wpdb->get_var("
        SELECT COUNT(*)
        FROM {$wpdb->prefix}actionwear_products ap
        INNER JOIN {$wpdb->prefix}wc_product_meta_lookup ml ON ml.sku = ap.sku
      ");
    }

    public static function getNbProductsTotal()
    {
      global $wpdb;
      return (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM {$wpdb->prefix}actionwear_products WHERE wc_to_create = 1"
      );
    }

    public static function updateLastSync($time)
    {
      update_option("_ACTIONWEAR_LAST_SYNC", $time);
    }

    public static function getLastSync()
    {
      $last = get_option("_ACTIONWEAR_LAST_SYNC");
      return $last === false ? "MAI" : date("d/m/Y H:i:s", $last);
    }

    public static function isProcessingAnymore()
    {
      return self::getNbProductsToProcess() !== 0;
    }
    public static function getResyncStatusByDates(array $dates)
    {
      $resync_products = new Resync_Products();
      $last_resync = $resync_products->get();
      foreach ($dates as $date) {
        $time = strtotime($date);
        if ($time > $last_resync)
          return true;
      }
      return false;
    }
    /**
     * Align wc_created flag with actual WooCommerce products.
     * Sets wc_created=1 for SKUs that exist in WC, wc_created=0 for those that don't.
     *
     * @return array Counts of aligned/reset products
     */
    public static function alignWcCreated()
    {
      global $wpdb;
      $table = $wpdb->prefix . 'actionwear_products';

      // Get SKUs that actually exist in WooCommerce
      $wc_skus = $wpdb->get_col("
        SELECT DISTINCT ml.sku
        FROM {$wpdb->prefix}wc_product_meta_lookup ml
        INNER JOIN {$table} ap ON ap.sku = ml.sku
      ");

      // Mark existing products as wc_created = 1
      $marked = 0;
      if (!empty($wc_skus)) {
        $placeholders = implode(',', array_fill(0, count($wc_skus), '%s'));
        $marked = (int) $wpdb->query($wpdb->prepare(
          "UPDATE {$table} SET wc_created = 1, wc_to_create = 1 WHERE sku IN ($placeholders) AND wc_created = 0",
          ...$wc_skus
        ));
      }

      // Reset wc_created = 0 for products NOT in WooCommerce
      $reset = 0;
      if (!empty($wc_skus)) {
        $placeholders = implode(',', array_fill(0, count($wc_skus), '%s'));
        $reset = (int) $wpdb->query($wpdb->prepare(
          "UPDATE {$table} SET wc_created = 0 WHERE sku NOT IN ($placeholders) AND wc_created = 1",
          ...$wc_skus
        ));
      } else {
        // No WC products at all — reset everything
        $reset = (int) $wpdb->query("UPDATE {$table} SET wc_created = 0 WHERE wc_created = 1");
      }

      return [
        'marked'  => $marked,
        'reset'   => $reset,
      ];
    }

    public static function getActionWearOrders()
    {
      global $wpdb;
      // Get product IDs that have camac_cdn_urls (ActionWear products)
      // then count distinct orders containing those products
      return (int) $wpdb->get_var("
        SELECT COUNT(DISTINCT woi.order_id)
        FROM {$wpdb->prefix}woocommerce_order_itemmeta woii
        INNER JOIN {$wpdb->prefix}woocommerce_order_items woi ON woi.order_item_id = woii.order_item_id
        WHERE woii.meta_key = '_product_id'
          AND woii.meta_value IN (
            SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'camac_cdn_urls'
          )
      ");
    }
  }
}
