/* Prevent horizontal viewport overflow & eliminate mobile/tablet white side margin */
html, body {
    overflow-x: hidden !important;
    max-width: 100% !important;
    width: 100% !important;
    position: relative !important;
}

/* Centering and layout block isolation */
.flip-showcase-center-wrapper {
    display: block;
    width: 100%;
    margin: 40px auto;
    padding-bottom: 40px;
    clear: both;
    box-sizing: border-box;
}

/* Base slider container spacing */
.flip-showcase-slider-container {
    width: 100%;
    max-width: 100%;
    margin: 0 auto;
    padding: 20px 0;
    overflow: hidden;
    position: relative;
    box-sizing: border-box;
    
    /* 
     * ==========================================
     * ADJUST LANDING PAGE CONTAINER HEIGHT (DESKTOP)
     * ==========================================
     * Force a minimum height on your home page slider to prevent footer overlaps.
     * Configured for a 528px card height (528 x 1.5 = 792px height + padding).
     */
    min-height: 820px !important; 
}

.flip-showcase-single-product-container {
    width: 100%;
    max-width: 100%;
    margin: 0 auto;
    padding: 20px 0;
    overflow: hidden;
    position: relative;
    box-sizing: border-box;
    min-height: 560px; 
}

/* Responsive slide dimensions */
.flip-showcase-slider-container .swiper-slide {
    width: 100% !important;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 15px;
    box-sizing: border-box;

    /* 
     * ==========================================
     * ADJUST LANDING PAGE CARD SIZE (DESKTOP)
     * ==========================================
     * Change this max-width value to adjust the card size on your home page.
     * Increased to 528px (exactly 10% larger than 480px).
     */
    max-width: 528px !important; 
}

.flip-showcase-single-product-container {
    padding: 0 15px 30px 15px;
    box-sizing: border-box;
    max-width: 340px; 
}

/* Force standard WooCommerce product images to scale natively inside the theme column */
.woocommerce div.product div.images .flip-showcase-single-product-container {
    max-width: 100%;
    width: 100%;
    margin: 0 auto;
    padding: 0;
}

/* Mobile screen size scaling overrides */
@media (max-width: 768px) {
    .flip-showcase-center-wrapper {
        margin: 20px auto;
        padding-bottom: 60px;
    }

    .flip-showcase-slider-container,
    .flip-showcase-single-product-container {
        /* 
         * ==========================================
         * ADJUST CONTAINER HEIGHT - MOBILE SCREEN
         * ==========================================
         * Force a minimum height on mobile screens to push the footer down.
         */
        min-height: 480px !important; 
    }

    .flip-showcase-slider-container .swiper-slide {
        padding: 10px;

        /* 
         * ==========================================
         * ADJUST CARD SIZE - MOBILE SCREEN (SLIDER)
         * ==========================================
         * Set to 100% to let the card expand and fill the mobile screen width.
         */
        max-width: 100% !important; 
    }
    
    .flip-showcase-single-product-container {
        padding: 0 10px 20px 10px;
        max-width: 100% !important; 
    }

    /* Edge-to-edge white container layout for mobile product page */
    body.single-product #content,
    body.single-product .site-content,
    body.single-product .site-main,
    body.single-product .ast-woocommerce-container,
    body.single-product div.product {
        margin-left: 0 !important;
        margin-right: 0 !important;
        display: block !important;
    }

    /* Specifically reset padding on all except content wrapper to enable top breathing space */
    body.single-product .site-main,
    body.single-product .ast-woocommerce-container,
    body.single-product div.product {
        padding: 0 !important;
    }

    /* Safe edge-to-edge product featured image container for mobile */
    .woocommerce div.product div.images,
    .woocommerce div.product div.images .woocommerce-product-gallery {
        width: 100% !important;
        max-width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
        float: none !important;
    }

    /* Allow the main image wrapper to scale while preserving dynamic transition dimensions */
    .woocommerce div.product div.images .woocommerce-product-gallery__image img {
        width: 100% !important;
        height: auto !important;
        display: block !important;
    }
    
    /* Comfortable padding for the text column details */
    .woocommerce div.product div.summary {
        width: 100% !important;
        max-width: 100% !important;
        flex: none !important;
        flex-basis: auto !important;
        float: none !important;
        padding: 20px !important;
        box-sizing: border-box !important;
        margin: 0 !important;
    }

    /* Comfortable padding for tabs */
    .woocommerce div.product .woocommerce-tabs,
    .woocommerce div.product .related.products,
    .woocommerce div.product .up-sells.products {
        padding: 20px !important;
        box-sizing: border-box !important;
    }

    /* Mobile-only style for swipe helper text */
    .flip-showcase-swipe-hint {
        display: block !important;
        color: #ffffff !important;
        font-size: 13px !important;
        text-align: center !important;
        
        /* Change this to a negative margin to pull the text up closer to the card */
        margin-top: -20px !important; 
        
        position: relative !important;
        z-index: 10 !important;
        opacity: 0.75 !important;
        font-weight: normal !important;
        letter-spacing: 0.5px !important;
    }
}


/* Card perspective wrapper */
.flip-card-wrapper {
    width: 100%;
    max-width: 100%;
    aspect-ratio: 850 / 1275;
    margin: 0 auto;
    perspective: 1200px;
    cursor: pointer;
    box-sizing: border-box;
}

.flip-card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
    transform-style: preserve-3d;
}

.flip-card-wrapper[data-current-panel="1"] .flip-card-inner {
    transform: rotateY(0deg);
}

.flip-card-wrapper[data-current-panel="2"] .flip-card-inner {
    transform: rotateY(180deg);
}

.flip-side {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    box-shadow: 0 8px 24px rgba(0,0,0,0.15);
}

.side-front {
    z-index: 2;
    transform: rotateY(0deg);
}

.side-back {
    z-index: 1;
    transform: rotateY(180deg);
    overflow: hidden;
    transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
}

.panel-info {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
    transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
}

.flip-hotspot-button {
    display: block;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 9999 !important;
    background: rgba(0, 0, 0, 0.01) !important;
    cursor: pointer !important;
    
    transform: none !important;
    -webkit-transform: none !important;

    /* 
     * ==========================================
     * ADJUST HOTSPOT BUTTON HEIGHT
     * ==========================================
     * Gold banner (85px) + 100px buffer = 185px.
     * 185px / 1275px card height = 14.51%.
     */
    height: 14.51%;
}

.flip-panel,
.flip-panel-img,
.flip-card-wrapper,
.flip-side,
.flip-card-inner {
    border-radius: 0 !important;
}

/* 
 * ==========================================
 * SINGLE PRODUCT PAGE WHITE THEME OVERRIDE
 * ==========================================
 * Forces the WooCommerce sales card and details container to be white,
 * while completely preserving your global header and body dark background.
 */

/* Force container backgrounds to be white across both desktop and mobile */
body.single-product #content,
body.single-product .site-content,
body.single-product div.product,
body.single-product .site-main,
body.single-product .ast-woocommerce-container {
    background-color: #ffffff !important;
    background: #ffffff !important;
}

/* Force all text inside the white product details container to be dark */
body.single-product .woocommerce-breadcrumb,
body.single-product .woocommerce-breadcrumb *,
body.single-product .entry-summary,
body.single-product .entry-summary *,
body.single-product div.summary,
body.single-product div.summary *,
body.single-product .product_title,
body.single-product .price,
body.single-product .price * {
    color: #222222 !important;
}

/* Ensure metadata, tags, and category links are dark and readable */
body.single-product .product_meta,
body.single-product .product_meta *,
body.single-product .posted_in,
body.single-product .posted_in a,
body.single-product .tagged_as,
body.single-product .tagged_as a {
    color: #555555 !important;
}

/* Ensure form labels and product metadata are visible */
body.single-product .quantity input.qty,
body.single-product .variations select,
body.single-product .variations label {
    color: #222222 !important;
    border-color: #cccccc !important;
}

/* Add a subtle dark border around quantity input fields for readability */
body.single-product .quantity input.qty {
    background: #ffffff !important;
    border: 1px solid #cccccc !important;
}

/* Force breadcrumbs to be small, dark, readable, and perfectly aligned */
body.single-product .woocommerce-breadcrumb {
    font-size: 10pt !important;
    line-height: 14pt !important;
    padding: 15px 20px !important;
    margin: 0 !important;
    text-align: left !important;
    display: block !important;
}

body.single-product .woocommerce-breadcrumb *,
body.single-product .woocommerce-breadcrumb a {
    font-size: 10pt !important;
    line-height: 14pt !important;
    margin: 0 !important;
    padding: 0 !important;
    text-align: left !important;
    display: inline !important;
}

/* Add a white padding-top to the main content container globally for top breathing space */
body.single-product #content,
body.single-product .site-content {
    padding-top: 25px !important;
}

/* Desktop-only single product page layout overrides */
@media (min-width: 769px) {
    /* 
     * ==========================================
     * ADJUST TOP GAP BETWEEN HEADER AND CONTENT
     * ==========================================
     * Removes the gap below your dark red menu bar and pulls the white container
     * up to touch the bottom edge of the header.
     * Changed to -65px to pull it completely flush (with the global 25px top padding).
     */
    body.single-product #content,
    body.single-product .site-content {
        margin-top: -65px !important; /* Pulls the white container completely flush with the header */
    }

    body.single-product div.product {
        margin-top: 0 !important;
    }

    /* Target only the actual product details block, keeping the header completely dark */
    body.single-product div.product,
    body.single-product .site-main,
    body.single-product .ast-woocommerce-container {
        padding: 30px !important;
        box-sizing: border-box;

        /* 
         * ==========================================
         * FIX PARENT HEIGHT COLLAPSE (FLOAT CLEARANCE)
         * ==========================================
         * Since .images and .summary are floated columns, the parent container
         * collapses to 0 height. Using flow-root forces the white background
         * to stretch completely to the bottom to enclose both columns.
         */
        display: flow-root !important;
        clear: both !important;
    }

    /* 
     * ==========================================
     * ADJUST IMAGE - SIZE
     * ==========================================
     * Increased to 462px (exactly 10% larger than 420px).
     */
    .woocommerce div.product div.images {
        width: 462px !important; 
        max-width: 462px !important; 
        flex: 0 0 462px !important; 
        flex-basis: 462px !important; 
        float: left !important;
        margin: 0 !important;
    }

    /* 
     * ==========================================
     * ADJUST IMAGE - DETAILS CONTAINER
     * ==========================================
     * Formula: calc(100% - (Image Width + 40px))
     * Configured for 462px: calc(100% - 502px)
     */
    .woocommerce div.product div.summary {
        width: calc(100% - 502px) !important; 
        max-width: calc(100% - 502px) !important; 
        flex: 1 1 auto !important;
        float: right !important;
        margin: 0 !important;
    }
}

/* Dynamic stacking and pointer behavior for active panels */
.flip-card-wrapper[data-current-panel="1"] .side-front {
    z-index: 2 !important;
    pointer-events: auto !important;
}

.flip-card-wrapper[data-current-panel="1"] .side-back {
    z-index: 1 !important;
    pointer-events: none !important;
}

.flip-card-wrapper[data-current-panel="2"] .side-front {
    z-index: 1 !important;
    pointer-events: none !important;
}

.flip-card-wrapper[data-current-panel="2"] .side-back {
    z-index: 2 !important;
    pointer-events: auto !important;
}

/* Mobile product-page typography and alignment */
@media (max-width: 768px) {
    body.single-product .woocommerce-breadcrumb {
        width: 100% !important;
        box-sizing: border-box !important;
        margin: 0 !important;
        padding: 10px 0 8px !important;
        font-size: 9pt !important;
        line-height: 12pt !important;
        text-align: left !important;
    }

    body.single-product .woocommerce-breadcrumb *,
    body.single-product .woocommerce-breadcrumb a {
        font-size: 9pt !important;
        line-height: 12pt !important;
    }

    .woocommerce div.product div.summary {
        padding: 20px 0 !important;
    }

    .woocommerce div.product .woocommerce-tabs,
    .woocommerce div.product .related.products,
    .woocommerce div.product .up-sells.products {
        padding-left: 0 !important;
        padding-right: 0 !important;
    }

    body.single-product .woocommerce-product-details__short-description,
    body.single-product .woocommerce-product-details__short-description p,
    body.single-product .woocommerce-Tabs-panel--description,
    body.single-product .woocommerce-Tabs-panel--description p,
    body.single-product #tab-description,
    body.single-product #tab-description p {
        font-size: 13pt !important;
        line-height: 19pt !important;
    }

    body.single-product .entry-summary .product-category,
    body.single-product div.summary .product-category,
    body.single-product .entry-summary .ast-woo-product-category,
    body.single-product div.summary .ast-woo-product-category {
        display: none !important;
    }
}

/* Product titles and description headings use the site's gold accent. */
body.single-product .product_title,
body.single-product .woocommerce-product-details__short-description h1,
body.single-product .woocommerce-product-details__short-description h2,
body.single-product .woocommerce-product-details__short-description h3,
body.single-product .woocommerce-product-details__short-description h4,
body.single-product .woocommerce-product-details__short-description h5,
body.single-product .woocommerce-product-details__short-description h6,
body.single-product .woocommerce-Tabs-panel--description h1,
body.single-product .woocommerce-Tabs-panel--description h2,
body.single-product .woocommerce-Tabs-panel--description h3,
body.single-product .woocommerce-Tabs-panel--description h4,
body.single-product .woocommerce-Tabs-panel--description h5,
body.single-product .woocommerce-Tabs-panel--description h6,
body.single-product #tab-description h1,
body.single-product #tab-description h2,
body.single-product #tab-description h3,
body.single-product #tab-description h4,
body.single-product #tab-description h5,
body.single-product #tab-description h6 {
    color: #b08c00 !important;
}

body.single-product .woocommerce-breadcrumb {
    padding-left: 0 !important;
    padding-right: 0 !important;
}

body.single-product .entry-title,
body.single-product #tab-description > p:first-of-type strong,
body.single-product #tab-description > p:first-of-type b {
    color: #b08c00 !important;
}

body.single-product .product_title.entry-title {
    line-height: 1.45 !important;
    color: #a57c01 !important;
}

/* 
 * ==========================================
 * CHECKOUT PAGE DISPLAY REPAIRS (UPDATED)
 * ==========================================
 */

/* 1. Remove Surrounding Grey Container & Expand Fields */
.woocommerce-checkout [class*="payment_method_square"] {
    background: transparent !important;
    border: none !important;
    padding: 0 !important;
    box-shadow: none !important;
    width: 100% !important;
    max-width: 100% !important;
}

.woocommerce-checkout [class*="payment_method_square"] .wc-square-credit-card-container {
    background: transparent !important;
    border: none !important;
    padding: 0 !important;
    margin: 0 !important;
    width: 100% !important;
    max-width: 100% !important;
    min-height: 90px !important;
}

.woocommerce-checkout [class*="payment_method_square"] iframe {
    width: 100% !important;
    max-width: 100% !important;
    min-width: 100% !important;
    display: block !important;
}

/* 2. Inviting Brand-Gold Button Style */
#add_payment_method #place_order, 
.woocommerce-cart #place_order, 
.woocommerce-checkout #place_order {
    background-color: #a57c01 !important; /* Brand Gold */
    color: #ffffff !important;            /* White text */
    opacity: 1 !important;                 /* Force visibility */
    border: 1px solid #a57c01 !important;
    font-size: 16px !important;
    font-weight: bold !important;
    text-transform: uppercase !important;
}

#add_payment_method #place_order:hover, 
.woocommerce-cart #place_order:hover, 
.woocommerce-checkout #place_order:hover {
    background-color: #b08c00 !important; /* Slightly brighter gold on hover */
    border-color: #b08c00 !important;
    color: #ffffff !important;
}

/* 3. Hide "Credit Card" Text and Keep Payment Logos Visible */
.woocommerce-checkout label[for*="payment_method_square"],
.woocommerce-checkout .payment_method_square label,
.woocommerce-checkout .payment_method_square_credit_card label {
    display: inline-block !important;
    font-size: 0 !important;
    line-height: normal !important;
    vertical-align: middle !important;
}

.woocommerce-checkout label[for*="payment_method_square"] img,
.woocommerce-checkout label[for*="payment_method_square"] .woocommerce-PaymentMethod-icons img,
.woocommerce-checkout label[for*="payment_method_square"] .wc-square-credit-card-icon,
.woocommerce-checkout .payment_method_square label img,
.woocommerce-checkout .payment_method_square_credit_card label img {
    display: inline-block !important;
    visibility: visible !important;
    opacity: 1 !important;
    width: 38px !important;
    min-width: 38px !important;
    max-width: 38px !important;
    height: 24px !important;
    max-height: 24px !important;
    vertical-align: middle !important;
    margin: 0 3px !important;
}

/* 
 * ==========================================
 * CART PAGE WHITE THEME OVERRIDE
 * ==========================================
 */

body.woocommerce-cart #content,
body.woocommerce-cart .site-content,
body.woocommerce-cart .site-main,
body.woocommerce-cart .ast-woocommerce-container,
body.woocommerce-cart .woocommerce,
body.woocommerce-cart form.woocommerce-cart-form,
body.woocommerce-cart .cart-collaterals,
body.woocommerce-cart .cart_totals {
    background-color: #ffffff !important;
    background: #ffffff !important;
}

body.woocommerce-cart h1.entry-title {
    color: #222222 !important;
}

body.woocommerce-cart table.cart td,
body.woocommerce-cart table.cart td *,
body.woocommerce-cart table.cart th,
body.woocommerce-cart table.cart th *,
body.woocommerce-cart table.cart a {
    color: #222222 !important;
}

body.woocommerce-cart table.cart td.product-remove a.remove {
    color: #cc0000 !important;
    border-color: #cc0000 !important;
}

body.woocommerce-cart .cart_totals h2,
body.woocommerce-cart .cart_totals th,
body.woocommerce-cart .cart_totals td,
body.woocommerce-cart .cart_totals td *,
body.woocommerce-cart .cart_totals a {
    color: #222222 !important;
}

body.woocommerce-cart .coupon input[type="text"] {
    background-color: #ffffff !important;
    color: #222222 !important;
    border: 1px solid #cccccc !important;
}

body.woocommerce-cart .wc-proceed-to-checkout a.checkout-button {
    background-color: #a57c01 !important; 
    color: #ffffff !important;            
    border: 1px solid #a57c01 !important;
    font-size: 16px !important;
    font-weight: bold !important;
    text-transform: uppercase !important;
    transition: background-color 0.3s ease;
}

body.woocommerce-cart .wc-proceed-to-checkout a.checkout-button:hover {
    background-color: #b08c00 !important; 
    border-color: #b08c00 !important; 
    color: #ffffff !important;
}

/* 
 * ==========================================
 * SHOP / ARCHIVE PAGES: 4-COLUMN COMPACT GRID
 * ==========================================
 */

body.archive #content,
body.archive .site-content,
body.archive .site-main,
body.archive .ast-woocommerce-container,
body.archive .woocommerce {
    background-color: #ffffff !important;
    background: #ffffff !important;
}

body.archive h1.page-title,
body.archive .woocommerce-breadcrumb,
body.archive .woocommerce-breadcrumb *,
body.archive .woocommerce-result-count,
body.archive .woocommerce-ordering select {
    color: #222222 !important;
}

body.archive .woocommerce-ordering select {
    background-color: #ffffff !important;
    border: 1px solid #cccccc !important;
    padding: 5px !important;
}

/* Desktop: 4-Column Compact Grid */
.woocommerce ul.products,
body.archive ul.products,
body.woocommerce-page ul.products {
    display: grid !important;
    grid-template-columns: repeat(4, 1fr) !important;
    gap: 16px !important;
    max-width: 1120px !important;
    list-style: none !important;
    margin: 20px auto 40px auto !important;
    padding: 0 !important;
    clear: both !important;
}

.woocommerce ul.products li.product,
body.archive ul.products li.product,
body.woocommerce-page ul.products li.product {
    width: 100% !important;
    max-width: 100% !important;
    float: none !important;
    margin: 0 !important;
    display: flex !important;
    flex-direction: column !important;
    align-items: center !important;
    text-align: center !important;
}

/* Preserve Portrait Poster Proportions with Zero Distortion */
.woocommerce ul.products li.product img,
body.archive ul.products li.product img,
body.woocommerce-page ul.products li.product img {
    width: 100% !important;
    max-width: 100% !important;
    height: auto !important;
    aspect-ratio: 850 / 1275 !important;
    object-fit: cover !important;
    display: block !important;
    margin: 0 auto 12px auto !important;
    border-radius: 4px !important;
}

body.archive ul.products li.product .woocommerce-loop-product__title,
body.archive ul.products li.product .ast-woo-product-category,
body.archive ul.products li.product .price,
body.archive ul.products li.product .price span,
body.archive ul.products li.product .price del,
body.archive ul.products li.product .price ins {
    color: #222222 !important;
}

/* Tablet (2 columns) */
@media (max-width: 992px) {
    .woocommerce ul.products,
    body.archive ul.products,
    body.woocommerce-page ul.products {
        grid-template-columns: repeat(2, 1fr) !important;
        gap: 16px !important;
        max-width: 680px !important;
        margin: 20px auto 40px auto !important;
    }
}

/* Mobile (Single Column Stacked Layout) */
@media (max-width: 768px) {
    .woocommerce ul.products,
    body.archive ul.products,
    body.woocommerce-page ul.products {
        grid-template-columns: 1fr !important;
        gap: 30px !important;
        max-width: 360px !important;
        margin: 20px auto 40px auto !important;
    }
}

body.archive ul.products li.product .button {
    background-color: #a57c01 !important; 
    color: #ffffff !important;            
    border: 1px solid #a57c01 !important;
    font-size: 14px !important;
    font-weight: bold !important;
    text-transform: uppercase !important;
    transition: background-color 0.3s ease;
    padding: 10px 20px !important;
    display: inline-block !important;
}

body.archive ul.products li.product .button:hover {
    background-color: #b08c00 !important; 
    border-color: #b08c00 !important; 
    color: #ffffff !important;
}

/* 
 * ==========================================
 * CLEANUP: HIDE BREADCRUMBS & SORTING
 * ==========================================
 */

body.archive .woocommerce-breadcrumb,
body.archive .woocommerce-ordering {
    display: none !important;
}

body.archive .woocommerce-result-count {
    display: none !important;
}

.flip-showcase-swipe-hint {
    display: none;
}

/* 
 * ==========================================
 * CHECKOUT CLEANUP: HIDE SHIPPING & NOTES
 * ==========================================
 */

body.woocommerce-checkout .woocommerce-shipping-fields {
    display: none !important;
}

body.woocommerce-checkout .woocommerce-additional-fields {
    display: none !important;
}

/* 
 * ==========================================
 * GLOBAL LOOP BUTTONS (GOLD ACTIVE STYLE)
 * ==========================================
 */
ul.products li.product .button,
.woocommerce ul.products li.product .button {
    background-color: #a57c01 !important; 
    color: #ffffff !important;            
    border: 1px solid #a57c01 !important;
    font-size: 14px !important;
    font-weight: bold !important;
    text-transform: uppercase !important;
    padding: 10px 20px !important;
    display: inline-block !important;
}

ul.products li.product .button:hover,
.woocommerce ul.products li.product .button:hover {
    background-color: #0056b3 !important; 
    border-color: #0056b3 !important;     
    color: #ffffff !important;            
}
File 2: /wp-content/plugins/flip-showcase-custom-receipts/flip-showcase-custom-receipts.php
code
PHP
<?php
/**
 * Plugin Name: Flip Showcase - Custom Email Receipts & Event Manager
 * Description: Confirmed ticket greetings, single-column receipts, FluentCRM event sync, admin door rosters, checkout quantity adjusters, external link routing, instant click-lock speed optimizations, dynamic variation (Sold Out) labeling, and instant Square checkout field mounting.
 * Version: 5.3.0
 * Author: Elephant in the Room
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/* =========================================================================
   1. CUSTOM TICKET RECEIPT GREETING (ALL CUSTOMER RECEIPT TYPES)
   ========================================================================= */

add_filter( 'gettext', 'fitr_customize_ticket_receipt_greeting', 20, 3 );
function fitr_customize_ticket_receipt_greeting( $translated_text, $text, $domain ) {
    if ( 'woocommerce' === $domain ) {
        if ( false !== strpos( $text, 'Just to let you know' ) && false !== strpos( $text, 'received your order' ) ) {
            return 'Your ticket purchase is confirmed! Present this receipt at the door for entry.';
        }
        if ( false !== strpos( $text, 'Here are the details of your order' ) ) {
            return 'Your ticket purchase is confirmed! Present this receipt at the door for entry.';
        }
        if ( false !== strpos( $text, 'An order has been created for you' ) ) {
            return 'Your ticket purchase is confirmed! Present this receipt at the door for entry.';
        }
        if ( false !== strpos( $text, 'Your order is complete' ) || false !== strpos( $text, 'we have finished processing your order' ) ) {
            return 'Your ticket purchase is confirmed! Present this receipt at the door for entry.';
        }
    }
    return $translated_text;
}

/* =========================================================================
   2. WOOCOMMERCE CUSTOM EMAIL RECEIPT RESTYLING
   ========================================================================= */

add_action( 'init', 'fitr_replace_email_order_details_hook' );
function fitr_replace_email_order_details_hook() {
    if ( class_exists( 'WC_Emails' ) ) {
        $wc_emails = WC_Emails::instance();
        remove_action( 'woocommerce_email_order_details', array( $wc_emails, 'order_details' ), 10 );
        add_action( 'woocommerce_email_order_details', 'fitr_custom_email_order_details_output', 10, 4 );
    }
}

add_action( 'woocommerce_email_order_details', 'fitr_ensure_default_unhooked', 1, 4 );
function fitr_ensure_default_unhooked( $order, $sent_to_admin, $plain_text, $email ) {
    if ( class_exists( 'WC_Emails' ) ) {
        remove_action( 'woocommerce_email_order_details', array( WC_Emails::instance(), 'order_details' ), 10 );
    }
}

add_filter( 'woocommerce_email_styles', 'fitr_custom_email_safe_styles', 99 );
function fitr_custom_email_safe_styles( $css ) {
    $custom_css = "
        .fitr-flyer-img {
            width: 100% !important;
            max-width: 100% !important;
            height: auto !important;
            display: block !important;
            margin: 0 auto !important;
        }
    ";
    return $css . $custom_css;
}

function fitr_custom_email_order_details_output( $order, $sent_to_admin, $plain_text, $email ) {
    if ( ! is_a( $order, 'WC_Order' ) ) {
        return;
    }

    $items = $order->get_items();
    $order_date = wc_format_datetime( $order->get_date_created() );
    ?>

    <div style="margin-bottom: 25px; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif; width: 100%;">
        <h2 style="color: #111111; font-size: 20px; font-weight: 700; margin: 0 0 6px 0; text-align: left;">
            Order summary
        </h2>
        <p style="color: #777777; font-size: 13px; margin: 0 0 22px 0; text-align: left;">
            Order #<?php echo esc_html( $order->get_order_number() ); ?> (<?php echo esc_html( $order_date ); ?>)
        </p>

        <!-- SINGLE COLUMN TICKETS -->
        <?php foreach ( $items as $item_id => $item ) : 
            $product = $item->get_product();
            $parent_id = ( $product && $product->is_type( 'variation' ) ) ? $product->get_parent_id() : ( $product ? $product->get_id() : 0 );
            $parent_product = $parent_id ? wc_get_product( $parent_id ) : $product;

            $image_id = $product ? $product->get_image_id() : 0;
            if ( ! $image_id && $parent_product ) {
                $image_id = $parent_product->get_image_id();
            }
            $img_url = $image_id ? wp_get_attachment_image_url( $image_id, 'full' ) : '';

            $event_title = $parent_product ? $parent_product->get_name() : $item->get_name();

            $ticket_type = '';
            $formatted_meta = array();
            foreach ( $item->get_formatted_meta_data() as $meta_id => $meta ) {
                $formatted_meta[] = wp_strip_all_tags( $meta->display_value );
            }
            
            if ( ! empty( $formatted_meta ) ) {
                $ticket_type = implode( ' - ', $formatted_meta );
            } elseif ( $product && $product->is_type( 'variation' ) ) {
                $attributes = $product->get_variation_attributes();
                $attr_vals = array();
                foreach ( $attributes as $val ) {
                    if ( ! empty( $val ) ) {
                        $attr_vals[] = ucwords( str_replace( array( '-', '_' ), ' ', $val ) );
                    }
                }
                $ticket_type = implode( ' - ', $attr_vals );
            }

            if ( ! empty( $ticket_type ) ) {
                $ticket_type = trim( str_ireplace( $event_title, '', $ticket_type ) );
                $ticket_type = ltrim( $ticket_type, " -:\t\n\r\0\x0B" );
            }

            if ( empty( $ticket_type ) ) {
                $item_raw_name = $item->get_name();
                $clean_name = trim( str_ireplace( $event_title, '', $item_raw_name ) );
                $clean_name = ltrim( $clean_name, " -:\t\n\r\0\x0B" );
                $ticket_type = ! empty( $clean_name ) ? $clean_name : 'General Admission';
            }

            $quantity = $item->get_quantity();
            $line_total = $order->get_formatted_line_subtotal( $item );
        ?>

        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="width: 100% !important; margin-bottom: 25px; background: transparent; border: none;">
            <tr>
                <td align="center" style="padding: 0; border: none; width: 100%;">
                    
                    <?php if ( ! empty( $img_url ) ) : ?>
                        <div style="text-align: center; margin-bottom: 18px; width: 100%;">
                            <img class="fitr-flyer-img" width="100%" src="<?php echo esc_url( $img_url ); ?>" alt="<?php echo esc_attr( $event_title ); ?>" style="width: 100%; max-width: 100%; height: auto; display: block; margin: 0 auto; border: 0;" />
                        </div>
                    <?php endif; ?>

                    <!-- Line 1: Event Title & Date -->
                    <div style="font-size: 19px; font-weight: 700; line-height: 1.35; color: #111111; margin-bottom: 16px; text-align: center;">
                        <?php echo esc_html( $event_title ); ?>
                    </div>

                    <!-- Line 2: Ticket Type -->
                    <div style="font-size: 15px; font-weight: 500; color: #555555; line-height: 1.4; text-align: center; margin-bottom: 6px;">
                        Ticket: <strong style="color: #111111;"><?php echo esc_html( $ticket_type ); ?></strong>
                    </div>

                    <!-- Line 3: Quantity & Total on Separate Line -->
                    <div style="font-size: 14px; font-weight: 500; color: #555555; line-height: 1.4; text-align: center; margin-bottom: 12px;">
                        Qty: <strong style="color: #111111;"><?php echo esc_html( $quantity ); ?></strong> &nbsp;&bull;&nbsp; <strong style="color: #111111;"><?php echo wp_kses_post( $line_total ); ?></strong>
                    </div>

                </td>
            </tr>
        </table>

        <?php endforeach; ?>

        <!-- ORDER TOTALS SUMMARY -->
        <table width="100%" cellpadding="6" cellspacing="0" border="0" style="width: 100% !important; margin-top: 15px; border-top: 2px solid #222222; font-size: 14px;">
            <?php 
            $totals = $order->get_order_item_totals();
            if ( $totals ) :
                foreach ( $totals as $total_key => $total ) : ?>
                    <tr>
                        <th scope="row" style="text-align: left; padding: 8px 0; color: #555555; font-weight: 600; border-bottom: 1px solid #eeeeee;">
                            <?php echo esc_html( $total['label'] ); ?>
                        </th>
                        <td style="text-align: right; padding: 8px 0; color: #111111; font-weight: 700; border-bottom: 1px solid #eeeeee;">
                            <?php echo wp_kses_post( $total['value'] ); ?>
                        </td>
                    </tr>
                <?php endforeach;
            endif; ?>
        </table>
    </div>

    <?php
}

/* =========================================================================
   3. FLUENTCRM BACKGROUND CONTACT SYNC & PARENT EVENT TAGGING
   ========================================================================= */

add_action( 'woocommerce_order_status_completed', 'fitr_sync_order_to_fluentcrm', 20, 1 );
add_action( 'woocommerce_payment_complete', 'fitr_sync_order_to_fluentcrm', 20, 1 );

function fitr_sync_order_to_fluentcrm( $order_id ) {
    if ( ! function_exists( 'FluentCrmApi' ) ) {
        return;
    }

    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }

    $email = $order->get_billing_email();
    if ( empty( $email ) ) {
        return;
    }

    $tag_ids = array();
    $ticket_details = array();

    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        if ( ! $product ) {
            continue;
        }

        $parent_id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();
        $parent_product = wc_get_product( $parent_id );
        $event_name = $parent_product ? $parent_product->get_name() : $item->get_name();

        $tag_slug = 'event-' . $parent_id;
        $tag_title = $event_name . ' (' . $tag_slug . ')';

        $tag_id = fitr_get_or_create_fluentcrm_tag( $tag_slug, $tag_title );
        if ( $tag_id && ! in_array( $tag_id, $tag_ids ) ) {
            $tag_ids[] = $tag_id;
        }

        $variation_info = $product->is_type( 'variation' ) ? $product->get_name() : 'General';
        $sku = $product->get_sku() ? ' | SKU: ' . $product->get_sku() : '';
        $ticket_details[] = sprintf( '%dx %s%s', $item->get_quantity(), $variation_info, $sku );
    }

    try {
        $contact_api = FluentCrmApi( 'contacts' );
        $contact_data = array(
            'email'      => $email,
            'first_name' => $order->get_billing_first_name(),
            'last_name'  => $order->get_billing_last_name(),
            'phone'      => $order->get_billing_phone(),
            'status'     => 'subscribed',
            'tags'       => $tag_ids,
        );

        $contact = $contact_api->createOrUpdate( $contact_data );

        if ( $contact && ! empty( $ticket_details ) ) {
            $note_body = sprintf(
                "WooCommerce Order #%s (%s)\nTickets: %s\nTotal: %s",
                $order->get_order_number(),
                date( 'M j, Y g:i A' ),
                implode( ', ', $ticket_details ),
                $order->get_formatted_order_total()
            );

            if ( class_exists( '\FluentCrm\App\Models\SubscriberNote' ) ) {
                \FluentCrm\App\Models\SubscriberNote::create( array(
                    'subscriber_id' => $contact->id,
                    'type'          => 'custom_note',
                    'description'   => $note_body,
                ) );
            }
        }
    } catch ( Exception $e ) {
        // Silent fail
    }
}

function fitr_get_or_create_fluentcrm_tag( $slug, $title ) {
    if ( ! class_exists( '\FluentCrm\App\Models\Tag' ) ) {
        return 0;
    }

    $tag = \FluentCrm\App\Models\Tag::where( 'slug', $slug )->first();
    if ( $tag ) {
        return (int) $tag->id;
    }

    $new_tag = \FluentCrm\App\Models\Tag::create( array(
        'title' => $title,
        'slug'  => $slug,
    ) );

    return $new_tag ? (int) $new_tag->id : 0;
}

/* =========================================================================
   4. WORDPRESS ADMIN EVENT ATTENDEE LIST & PRINT / PDF ROSTER
   ========================================================================= */

add_action( 'admin_menu', 'fitr_register_event_attendees_admin_menu' );
function fitr_register_event_attendees_admin_menu() {
    add_submenu_page(
        'woocommerce',
        'Event Attendees',
        'Event Attendees',
        'manage_woocommerce',
        'fitr-event-attendees',
        'fitr_render_event_attendees_admin_page'
    );
}

function fitr_render_event_attendees_admin_page() {
    if ( ! current_user_can( 'manage_woocommerce' ) ) {
        wp_die( 'Access denied.' );
    }

    $events = wc_get_products( array(
        'limit'   => -1,
        'status'  => 'publish',
        'orderby' => 'title',
        'order'   => 'ASC',
    ) );

    $selected_event_id = isset( $_GET['event_id'] ) ? absint( $_GET['event_id'] ) : 0;
    if ( empty( $selected_event_id ) && ! empty( $events ) ) {
        $selected_event_id = $events[0]->get_id();
    }

    $selected_event = $selected_event_id ? wc_get_product( $selected_event_id ) : null;
    $attendees = array();
    $total_tickets_sold = 0;

    if ( $selected_event_id ) {
        $orders = wc_get_orders( array(
            'limit'  => -1,
            'status' => array( 'wc-completed', 'wc-processing' ),
        ) );

        foreach ( $orders as $order ) {
            foreach ( $order->get_items() as $item ) {
                $product = $item->get_product();
                if ( ! $product ) {
                    continue;
                }

                $parent_id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();

                if ( (int) $parent_id === (int) $selected_event_id ) {
                    $qty = $item->get_quantity();
                    $total_tickets_sold += $qty;

                    $ticket_label = '';
                    $meta_arr = array();
                    foreach ( $item->get_formatted_meta_data() as $m ) {
                        $meta_arr[] = wp_strip_all_tags( $m->display_value );
                    }
                    if ( ! empty( $meta_arr ) ) {
                        $ticket_label = implode( ' - ', $meta_arr );
                    } else {
                        $ticket_label = $product->is_type( 'variation' ) ? $product->get_name() : 'General Admission';
                    }

                    $attendees[] = array(
                        'order_id'   => $order->get_order_number(),
                        'name'       => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
                        'email'      => $order->get_billing_email(),
                        'phone'      => $order->get_billing_phone(),
                        'ticket'     => $ticket_label,
                        'sku'        => $product->get_sku() ? $product->get_sku() : 'N/A',
                        'qty'        => $qty,
                        'order_date' => wc_format_datetime( $order->get_date_created() ),
                    );
                }
            }
        }
    }
    ?>

    <div class="wrap" id="fitr-attendee-roster-wrap">
        <style>
            @media print {
                #adminmenumain, #wpadminbar, #wpfooter, .fitr-no-print, .notice {
                    display: none !important;
                }
                #wpcontent, #wpbody-content, .wrap {
                    margin: 0 !important;
                    padding: 0 !important;
                }
                .fitr-print-header {
                    display: block !important;
                    margin-bottom: 20px;
                }
                table.widefat {
                    border: 1px solid #000 !important;
                }
                table.widefat th, table.widefat td {
                    border-bottom: 1px solid #ddd !important;
                    color: #000 !important;
                    padding: 8px 10px !important;
                }
            }
            .fitr-print-header {
                display: none;
            }
            .fitr-controls-bar {
                display: flex;
                align-items: center;
                gap: 15px;
                background: #ffffff;
                padding: 15px 20px;
                border: 1px solid #ccd0d4;
                border-radius: 4px;
                margin: 20px 0;
            }
        </style>

        <h1 class="wp-heading-inline fitr-no-print">Event Attendee Lists</h1>

        <div class="fitr-controls-bar fitr-no-print">
            <form method="get" action="">
                <input type="hidden" name="page" value="fitr-event-attendees" />
                <label for="event_id" style="font-weight: 600; margin-right: 8px;">Select Event:</label>
                <select name="event_id" id="event_id" onchange="this.form.submit()" style="min-width: 280px; height: 36px;">
                    <?php foreach ( $events as $event ) : ?>
                        <option value="<?php echo esc_attr( $event->get_id() ); ?>" <?php selected( $selected_event_id, $event->get_id() ); ?>>
                            <?php echo esc_html( $event->get_name() ); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </form>

            <button type="button" onclick="window.print()" class="button button-primary" style="height: 36px; padding: 0 16px;">
                🖨️ Print / Download PDF Roster
            </button>

            <span style="margin-left: auto; font-weight: 600; font-size: 14px;">
                Total Confirmed Tickets: <span style="color: #2271b1;"><?php echo esc_html( $total_tickets_sold ); ?></span>
            </span>
        </div>

        <div class="fitr-print-header">
            <h2 style="margin: 0 0 5px 0; font-size: 24px;"><?php echo esc_html( $selected_event ? $selected_event->get_name() : 'Event Attendees' ); ?></h2>
            <p style="margin: 0; color: #555; font-size: 13px;">
                Roster Generated: <?php echo esc_html( date( 'F j, Y g:i A' ) ); ?> &nbsp;&bull;&nbsp; Total Paid Guests / Tickets: <strong><?php echo esc_html( $total_tickets_sold ); ?></strong>
            </p>
            <hr style="margin: 15px 0; border: 0; border-top: 1px solid #333;" />
        </div>

        <table class="wp-list-table widefat fixed striped" style="margin-top: 10px;">
            <thead>
                <tr>
                    <th style="width: 60px; font-weight: bold;">Order</th>
                    <th style="font-weight: bold;">Buyer Name</th>
                    <th style="font-weight: bold;">Email</th>
                    <th style="font-weight: bold;">Phone</th>
                    <th style="font-weight: bold;">Ticket Type</th>
                    <th style="width: 100px; font-weight: bold;">SKU</th>
                    <th style="width: 60px; text-align: center; font-weight: bold;">Qty</th>
                    <th style="font-weight: bold;">Order Date</th>
                </tr>
            </thead>
            <tbody>
                <?php if ( ! empty( $attendees ) ) : ?>
                    <?php foreach ( $attendees as $guest ) : ?>
                        <tr>
                            <td><strong>#<?php echo esc_html( $guest['order_id'] ); ?></strong></td>
                            <td style="font-weight: 600;"><?php echo esc_html( $guest['name'] ); ?></td>
                            <td><?php echo esc_html( $guest['email'] ); ?></td>
                            <td><?php echo esc_html( $guest['phone'] ); ?></td>
                            <td><?php echo esc_html( $guest['ticket'] ); ?></td>
                            <td><code><?php echo esc_html( $guest['sku'] ); ?></code></td>
                            <td style="text-align: center; font-weight: bold;"><?php echo esc_html( $guest['qty'] ); ?></td>
                            <td><?php echo esc_html( $guest['order_date'] ); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 25px; color: #777;">
                            No paid attendees found for this event yet.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
}

/* =========================================================================
   5. INTERACTIVE CHECKOUT QUANTITY ADJUSTER (STABILIZED FOR SQUARE SDK)
   ========================================================================= */

add_filter( 'woocommerce_checkout_cart_item_quantity', 'fitr_interactive_checkout_quantity_selector', 99, 3 );
function fitr_interactive_checkout_quantity_selector( $quantity_html, $cart_item, $cart_item_key ) {
    $qty = isset( $cart_item['quantity'] ) ? $cart_item['quantity'] : 1;

    ob_start();
    ?>
    <span class="fitr-checkout-qty-wrapper" data-cart-key="<?php echo esc_attr( $cart_item_key ); ?>" style="display: inline-flex; align-items: center; gap: 6px; margin: 4px 0;">
        <button type="button" class="fitr-qty-btn fitr-qty-minus" style="width: 26px; height: 26px; line-height: 24px; padding: 0; text-align: center; font-size: 15px; font-weight: bold; background: #f0f0f0; border: 1px solid #ccc; border-radius: 3px; cursor: pointer;">&minus;</button>
        <span class="fitr-qty-display" style="font-weight: 700; font-size: 14px; min-width: 18px; text-align: center; color: #222;"><?php echo esc_html( $qty ); ?></span>
        <button type="button" class="fitr-qty-btn fitr-qty-plus" style="width: 26px; height: 26px; line-height: 24px; padding: 0; text-align: center; font-size: 15px; font-weight: bold; background: #f0f0f0; border: 1px solid #ccc; border-radius: 3px; cursor: pointer;">&#43;</button>
    </span>
    <?php
    return ob_get_clean();
}

add_action( 'wp_footer', 'fitr_checkout_quantity_ajax_script' );
function fitr_checkout_quantity_ajax_script() {
    if ( ! is_checkout() ) {
        return;
    }
    ?>
    <script type="text/javascript">
    jQuery(function($) {
        var qtyDebounceTimer = null;

        $(document).on('click', '.fitr-qty-btn', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $wrap = $btn.closest('.fitr-checkout-qty-wrapper');
            var cartKey = $wrap.data('cart-key');
            var currentVal = parseInt($wrap.find('.fitr-qty-display').text(), 10) || 1;
            var newVal = currentVal;

            if ($btn.hasClass('fitr-qty-plus')) {
                newVal = currentVal + 1;
            } else if ($btn.hasClass('fitr-qty-minus')) {
                newVal = currentVal - 1;
            }

            if (newVal < 1) {
                newVal = 0;
            }

            $wrap.find('.fitr-qty-display').text(newVal);
            $wrap.find('.fitr-qty-btn').prop('disabled', true);

            clearTimeout(qtyDebounceTimer);
            qtyDebounceTimer = setTimeout(function() {
                $.ajax({
                    type: 'POST',
                    url: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
                    data: {
                        action: 'fitr_update_checkout_quantity',
                        cart_key: cartKey,
                        quantity: newVal,
                        nonce: '<?php echo wp_create_nonce( "fitr_qty_nonce" ); ?>'
                    },
                    success: function(response) {
                        $('body').trigger('update_checkout');
                    }
                });
            }, 150);
        });
    });
    </script>
    <?php
}

add_action( 'wp_ajax_fitr_update_checkout_quantity', 'fitr_ajax_handle_update_checkout_quantity' );
add_action( 'wp_ajax_nopriv_fitr_update_checkout_quantity', 'fitr_ajax_handle_update_checkout_quantity' );
function fitr_ajax_handle_update_checkout_quantity() {
    check_ajax_referer( 'fitr_qty_nonce', 'nonce' );

    $cart_key = isset( $_POST['cart_key'] ) ? sanitize_text_field( $_POST['cart_key'] ) : '';
    $quantity = isset( $_POST['quantity'] ) ? absint( $_POST['quantity'] ) : 1;

    if ( ! empty( $cart_key ) && isset( WC()->cart->get_cart()[ $cart_key ] ) ) {
        if ( $quantity === 0 ) {
            WC()->cart->remove_cart_item( $cart_key );
        } else {
            WC()->cart->set_quantity( $cart_key, $quantity, true );
        }
        WC()->cart->calculate_totals();
        wp_send_json_success();
    }

    wp_send_json_error();
}

/* =========================================================================
   6. EXTERNAL TICKET FORMS & LINKS NEW-TAB ROUTER (target="_blank")
   ========================================================================= */

add_action( 'wp_footer', 'fitr_external_ticket_new_tab_script', 999 );
function fitr_external_ticket_new_tab_script() {
    ?>
    <script type="text/javascript">
    (function() {
        var currentHost = window.location.hostname;

        function applyExternalTargets() {
            var forms = document.querySelectorAll('form.cart');
            forms.forEach(function(form) {
                var action = form.getAttribute('action');
                if (action && action.indexOf('http') === 0 && action.indexOf(currentHost) === -1) {
                    form.setAttribute('target', '_blank');
                    form.setAttribute('rel', 'noopener noreferrer');
                }
            });

            var links = document.querySelectorAll('.flip-hotspot-button, .product_type_external, a.button');
            links.forEach(function(link) {
                var href = link.getAttribute('href');
                if (href && href.indexOf('http') === 0 && href.indexOf(currentHost) === -1) {
                    link.setAttribute('target', '_blank');
                    link.setAttribute('rel', 'noopener noreferrer');
                }
            });
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', applyExternalTargets);
        } else {
            applyExternalTargets();
        }

        document.addEventListener('submit', function(e) {
            var form = e.target;
            if (form && form.matches('form.cart')) {
                var action = form.getAttribute('action');
                if (action && action.indexOf('http') === 0 && action.indexOf(currentHost) === -1) {
                    form.setAttribute('target', '_blank');
                }
            }
        }, true);
    })();
    </script>
    <?php
}

/* =========================================================================
   7. INSTANT BUTTON LOCK & SPEED OPTIMIZATION (PREVENTS DUPLICATE CLICKS)
   ========================================================================= */

add_filter( 'woocommerce_add_to_cart_redirect', 'fitr_fast_direct_checkout_redirect', 99 );
function fitr_fast_direct_checkout_redirect( $url ) {
    return wc_get_checkout_url();
}

add_action( 'wp_enqueue_scripts', 'fitr_speedup_cart_fragments', 99 );
function fitr_speedup_cart_fragments() {
    if ( is_front_page() || is_home() || ( ! is_cart() && ! is_checkout() && ! is_product() ) ) {
        wp_dequeue_script( 'wc-cart-fragments' );
    }
}

add_action( 'wp_footer', 'fitr_instant_button_lock_script', 999 );
function fitr_instant_button_lock_script() {
    if ( is_product() || is_shop() || is_archive() || is_front_page() ) :
    ?>
    <script type="text/javascript">
    jQuery(function($) {
        $('form.cart').on('submit', function() {
            var $form = $(this);
            var $btn = $form.find('button[type="submit"].single_add_to_cart_button');

            var formAction = $form.attr('action') || '';
            if (formAction.indexOf('http') === 0 && formAction.indexOf(window.location.hostname) === -1) {
                return true;
            }

            if ($btn.length && !$btn.hasClass('fitr-locked')) {
                if ($form.find('.variations').length) {
                    var variationId = parseInt($form.find('input[name="variation_id"]').val(), 10);
                    if (!variationId || variationId === 0) {
                        return true;
                    }
                }

                $btn.addClass('fitr-locked');
                $btn.prop('disabled', true);
                $btn.css({
                    'opacity': '0.85',
                    'cursor': 'wait',
                    'pointer-events': 'none'
                });
                $btn.html('&#9203;&nbsp; Preparing Ticket Order... Please Wait');
            }
        });
    });
    </script>
    <?php
    endif;
}

/* =========================================================================
   8. DYNAMIC (SOLD OUT) LABEL FOR OUT-OF-STOCK VARIATIONS IN DROPDOWNS
   ========================================================================= */

add_filter( 'woocommerce_variation_option_name', 'fitr_append_sold_out_to_variation_dropdown', 20, 4 );
function fitr_append_sold_out_to_variation_dropdown( $term_name, $term, $attribute, $product ) {
    if ( ! $product || ! $product->is_type( 'variable' ) ) {
        return $term_name;
    }

    $attribute_key = 'attribute_' . sanitize_title( $attribute );
    $target_val = is_object( $term ) ? $term->slug : sanitize_title( $term_name );

    foreach ( $product->get_children() as $child_id ) {
        $variation = wc_get_product( $child_id );
        if ( ! $variation ) {
            continue;
        }

        $var_attributes = $variation->get_variation_attributes();
        foreach ( $var_attributes as $key => $val ) {
            if ( ( $key === $attribute_key || sanitize_title( $key ) === sanitize_title( $attribute_key ) ) && ( sanitize_title( $val ) === $target_val || $val === $term_name ) ) {
                if ( ! $variation->is_in_stock() ) {
                    return $term_name . ' (Sold Out)';
                }
            }
        }
    }

    return $term_name;
}

/* =========================================================================
   9. INSTANT SQUARE CHECKOUT FIELD MOUNT WATCHER
   ========================================================================= */

add_action( 'wp_footer', 'fitr_ensure_square_fields_mount_script', 999 );
function fitr_ensure_square_fields_mount_script() {
    if ( ! is_checkout() ) {
        return;
    }
    ?>
    <script type="text/javascript">
    jQuery(function($) {
        function triggerSquareInit() {
            var $squareContainer = $('#wc-square-credit-card-container');
            if ($squareContainer.length && !$squareContainer.find('iframe').length) {
                $('.payment_box.payment_method_square_credit_card').show();
                $('input[name="payment_method"][value="square_credit_card"]').prop('checked', true);
                $(document.body).trigger('payment_method_selected');
            }
        }

        triggerSquareInit();
        setTimeout(triggerSquareInit, 150);
        setTimeout(triggerSquareInit, 400);

        $(document.body).on('updated_checkout', function() {
            setTimeout(triggerSquareInit, 100);
        });
    });
    </script>
    <?php
}