class-studiou-wc-fpp-single-product.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. if (!defined('WPINC')) {
  3. die;
  4. }
  5. class Studiou_WC_FPP_Single_Product {
  6. /** @var Studiou_WC_FPP_DB */
  7. private $db;
  8. public function __construct($db) {
  9. $this->db = $db;
  10. // Render upload cards UI at priority 35 on single product page.
  11. // Also suppress pvtfw's variant table + available-options button on FPP products.
  12. add_action('wp', array($this, 'maybe_suppress_pvtfw'), 5);
  13. // Read-only price overview rendered right above the dropzone (1.5.12+).
  14. add_action('woocommerce_single_product_summary', array($this, 'render_variant_price_table'), 34);
  15. add_action('woocommerce_single_product_summary', array($this, 'render_upload_area'), 35);
  16. // Add a body class on FPP product pages for CSS scoping
  17. add_filter('body_class', array($this, 'body_class'));
  18. // Server-side validation: block add-to-cart without photo (priority 1 = very early)
  19. add_filter('woocommerce_add_to_cart_validation', array($this, 'validate_add_to_cart'), 1, 6);
  20. // Safety net: if item was added without photo, remove it immediately
  21. add_action('woocommerce_add_to_cart', array($this, 'check_after_add_to_cart'), 10, 6);
  22. }
  23. /**
  24. * Detach pvtfw's variant-table + available-options-button hooks on FPP products.
  25. *
  26. * pvtfw assigns its singletons to `$pvtfw_print_table` / `$pvtfw_available_btn` at the
  27. * top of its class files, but the `require_once` call lives inside pvtfw's
  28. * PVTFW_TABLE::includes() method — so those assignments end up as method-locals, NOT
  29. * true globals. We therefore reach the singletons via their static ::instance()
  30. * (the same object pvtfw registered the actions with). The variant-table hook and
  31. * priority are derived from pvtfw's own pvtfw_variant_table_place option (default
  32. * woocommerce_after_single_product_summary_9) so admin-configured placements
  33. * remain supported.
  34. */
  35. public function maybe_suppress_pvtfw() {
  36. if (!function_exists('is_product') || !is_product()) {
  37. return;
  38. }
  39. $product_id = get_queried_object_id();
  40. if (!$product_id || !Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  41. return;
  42. }
  43. if (class_exists('PVTFW_PRINT_TABLE')) {
  44. $print_table = PVTFW_PRINT_TABLE::instance();
  45. $place = get_option('pvtfw_variant_table_place', 'woocommerce_after_single_product_summary_9');
  46. $tail = strrchr((string) $place, '_');
  47. if ($tail !== false && strlen($tail) > 1) {
  48. $priority = (int) ltrim($tail, '_');
  49. $hook = substr($place, 0, -strlen($tail));
  50. if ($hook) {
  51. remove_action($hook, array($print_table, 'print_table'), $priority);
  52. }
  53. }
  54. } elseif (defined('WP_DEBUG') && WP_DEBUG) {
  55. error_log('STUDIOU FPP: PVTFW_PRINT_TABLE class not found; cannot detach pvtfw variant table.');
  56. }
  57. // Note: pvtfw's class name has a typo ("AVAILABE" missing the L) — match it verbatim
  58. if (class_exists('PVTFW_AVAILABE_BTN')) {
  59. $available_btn = PVTFW_AVAILABE_BTN::instance();
  60. remove_action('woocommerce_single_product_summary', array($available_btn, 'available_options_btn'), 11);
  61. }
  62. // Hide WC's native price-range element (e.g. "10,00 Kč – 40,00 Kč") on FPP products.
  63. // The variant price table we render at priority 34 already communicates per-variant
  64. // pricing, and the range is visually noisy above it.
  65. remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
  66. }
  67. public function body_class($classes) {
  68. if (function_exists('is_product') && is_product()) {
  69. $product_id = get_queried_object_id();
  70. if ($product_id && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  71. $classes[] = 'studiou-fpp-product-page';
  72. }
  73. }
  74. return $classes;
  75. }
  76. public function render_upload_area() {
  77. global $product;
  78. if (!$product || !Studiou_WC_FPP_Product::is_fpp_product($product->get_id())) {
  79. return;
  80. }
  81. wp_enqueue_style('studiou-wcfpp-frontend');
  82. wp_enqueue_script('studiou-wcfpp-frontend');
  83. $product_id = $product->get_id();
  84. $max_file_size = Studiou_WC_FPP_Product::get_product_max_file_size($product_id);
  85. $max_uploads = Studiou_WC_FPP_Product::get_product_max_uploads($product_id);
  86. // Variant list (id, label, base_price, tiers) — injected into the files-cards JS
  87. $variants = $this->build_variant_list($product);
  88. // Existing batch files (rehydrate the card stack across reloads)
  89. $batch_files = self::resolve_batch_files($this->db, $product_id);
  90. $batch_cards = array();
  91. $hero_preview_url = '';
  92. foreach ($batch_files as $row) {
  93. $att_id = (int) $row->attachment_id;
  94. $thumb = wp_get_attachment_image_src($att_id, 'thumbnail');
  95. $preview = wp_get_attachment_image_src($att_id, 'woocommerce_single');
  96. if ($hero_preview_url === '') {
  97. $hero_preview_url = $preview ? $preview[0] : ($thumb ? $thumb[0] : '');
  98. }
  99. $batch_cards[] = array(
  100. 'file_record_id' => (int) $row->id,
  101. 'attachment_id' => $att_id,
  102. 'file_name' => (string) $row->file_name,
  103. 'thumb_url' => $thumb ? $thumb[0] : ($preview ? $preview[0] : ''),
  104. 'preview_url' => $preview ? $preview[0] : ($thumb ? $thumb[0] : ''),
  105. 'variation_id' => (int) $row->variation_id,
  106. );
  107. }
  108. wp_localize_script('studiou-wcfpp-frontend', 'studiouFppCardData', array(
  109. 'productId' => $product_id,
  110. 'variants' => $variants,
  111. 'maxUploads' => $max_uploads,
  112. 'batchFiles' => $batch_cards,
  113. 'heroPreviewUrl' => $hero_preview_url,
  114. ));
  115. // Keep studiouWcfppSession populated for legacy JS code paths that still read it
  116. wp_localize_script('studiou-wcfpp-frontend', 'studiouWcfppSession', array());
  117. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-upload.php';
  118. if (is_product() && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  119. // Render the order-overview panel below the cards (see views/single-product-order-overview.php)
  120. $cart = function_exists('WC') ? WC()->cart : null;
  121. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-order-overview.php';
  122. }
  123. }
  124. /**
  125. * Read-only variant price/discount table rendered above the dropzone (1.5.12+).
  126. * Customers see all variant prices and the tiered quantity discounts before uploading.
  127. * Purely informational — no radio/select/qty/add-to-cart.
  128. */
  129. public function render_variant_price_table() {
  130. global $product;
  131. if (!$product || !Studiou_WC_FPP_Product::is_fpp_product($product->get_id())) {
  132. return;
  133. }
  134. $variants = $this->build_variant_list($product);
  135. if (empty($variants)) {
  136. return;
  137. }
  138. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-price-table.php';
  139. }
  140. /**
  141. * Produce the array of variation descriptors consumed by the upload-card JS.
  142. * One entry per in-stock, purchasable variation: id, label, base_price, tiers.
  143. */
  144. private function build_variant_list($product) {
  145. if (!$product || !$product->is_type('variable')) {
  146. return array();
  147. }
  148. $variants = array();
  149. foreach ($product->get_children() as $variation_id) {
  150. $variation = wc_get_product($variation_id);
  151. if (!$variation || !$variation->is_purchasable() || !$variation->variation_is_visible()) {
  152. continue;
  153. }
  154. $base_price = get_post_meta($variation_id, '_price', true);
  155. $label_parts = array();
  156. foreach ($variation->get_attributes() as $attr_name => $attr_value) {
  157. if ($attr_value === '') {
  158. continue;
  159. }
  160. $taxonomy = str_replace('attribute_', '', $attr_name);
  161. $term = taxonomy_exists($taxonomy) ? get_term_by('slug', $attr_value, $taxonomy) : null;
  162. // Term names or non-tax values may carry HTML entities (&nbsp;, &#75;,
  163. // &aacute;, …) pasted in by admins. <option> text is literal, so entities
  164. // would render as-is. Decode before handing to JS.
  165. $raw = $term ? $term->name : urldecode((string) $attr_value);
  166. $label_parts[] = html_entity_decode($raw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  167. }
  168. $tiers = class_exists('Studiou_WC_FPP_Pricing')
  169. ? Studiou_WC_FPP_Pricing::get_tiers($variation_id)
  170. : array();
  171. $variants[] = array(
  172. 'id' => (int) $variation_id,
  173. 'label' => implode(' / ', $label_parts),
  174. 'base_price' => ($base_price !== '' && $base_price !== false) ? (float) $base_price : 0.0,
  175. 'tiers' => $tiers,
  176. 'in_stock' => $variation->is_in_stock(),
  177. );
  178. }
  179. return $variants;
  180. }
  181. /**
  182. * Resolve whether a product_id or its parent is FPP-enabled.
  183. */
  184. private function resolve_fpp_product_id($product_id, $variation_id = 0) {
  185. // Check direct product
  186. if (Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  187. return $product_id;
  188. }
  189. // Check parent of the product (in case product_id is variation)
  190. $product = wc_get_product($product_id);
  191. if ($product && $product->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($product->get_parent_id())) {
  192. return $product->get_parent_id();
  193. }
  194. // Check variation_id's parent
  195. if ($variation_id && $variation_id !== $product_id) {
  196. $variation = wc_get_product($variation_id);
  197. if ($variation && $variation->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($variation->get_parent_id())) {
  198. return $variation->get_parent_id();
  199. }
  200. }
  201. return false;
  202. }
  203. /**
  204. * Validate before add-to-cart: block if FPP product and no photo reference resolvable.
  205. *
  206. * 1.5.0: the per-card Add-to-Cart path pre-stamps $cart_item_data['studiou_fpp_file_record_id']
  207. * via our ajax_add_file_to_cart handler — accept that as the primary signal. Fall back to the
  208. * legacy visitor-level resolver for the shortcode path.
  209. */
  210. public function validate_add_to_cart($passed, $product_id, $quantity, $variation_id = 0, $variations = array(), $cart_item_data = array()) {
  211. $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
  212. if (!$fpp_id) {
  213. return $passed;
  214. }
  215. if (!empty($cart_item_data['studiou_fpp_file_record_id'])) {
  216. $record = $this->db->get_file_record((int) $cart_item_data['studiou_fpp_file_record_id']);
  217. if ($record && (int) $record->order_id === 0) {
  218. return $passed;
  219. }
  220. }
  221. if (self::resolve_uploaded_file($this->db)) {
  222. return $passed;
  223. }
  224. wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
  225. return false;
  226. }
  227. /**
  228. * Return all upload records belonging to the current visitor's batch
  229. * that are not yet attached to an order, optionally scoped to a product.
  230. *
  231. * @return array<int,object> list of DB rows, oldest first (ascending id)
  232. */
  233. public static function resolve_batch_files(Studiou_WC_FPP_DB $db, $product_id = 0) {
  234. $token = Studiou_WC_FPP_Upload::get_batch_token();
  235. if (empty($token)) {
  236. return array();
  237. }
  238. return $db->get_batch_files($token, (int) $product_id);
  239. }
  240. /**
  241. * Resolve the single "current" upload for callers that still think in single-file
  242. * terms (shortcode fallback, the validate_add_to_cart fallback branch). Returns the
  243. * oldest unbound file in the visitor's batch, or null if none.
  244. *
  245. * Since 1.5.3 this is just a thin wrapper on the batch transport — the legacy
  246. * WC-session and legacy `studiou_fpp_att_id` / `studiou_fpp_rec_id` cookies are gone.
  247. *
  248. * @return array{attachment_id:int,file_record_id:int,file_name:string,thumb_url:string}|null
  249. */
  250. public static function resolve_uploaded_file(Studiou_WC_FPP_DB $db) {
  251. $files = self::resolve_batch_files($db);
  252. if (empty($files)) {
  253. return null;
  254. }
  255. $first = $files[0];
  256. $att_id = (int) $first->attachment_id;
  257. $thumb = wp_get_attachment_image_src($att_id, 'thumbnail');
  258. return array(
  259. 'attachment_id' => $att_id,
  260. 'file_record_id' => (int) $first->id,
  261. 'file_name' => (string) $first->file_name,
  262. 'thumb_url' => $thumb ? $thumb[0] : (string) wp_get_attachment_url($att_id),
  263. );
  264. }
  265. /**
  266. * Safety net: if an FPP item was added without photo data, remove it.
  267. * This catches cases where validation was somehow bypassed.
  268. */
  269. public function check_after_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
  270. $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
  271. if (!$fpp_id) {
  272. return;
  273. }
  274. // If the cart item has no FPP attachment, remove it
  275. if (empty($cart_item_data['studiou_fpp_attachment_id'])) {
  276. WC()->cart->remove_cart_item($cart_item_key);
  277. wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
  278. }
  279. }
  280. }