/*
Theme Name: Hello Elementor Child
Theme URI: https://elementor.com/hello-theme/
Description: Child theme for Hello Elementor
Author: De:strukt Studio
Template: hello-elementor
Version: 1.0.0
Text Domain: hello-elementor-child
*/

<?php
/**
 * The Chilled Kitchen — Custom Functionality
 * ============================================
 * Add this entire block at the END of your Hello Child Theme functions.php.
 *
 * Requires: WooCommerce (active)
 * Features: Loyalty/Rewards · Bundle Builder · Group Ordering
 *           Click & Collect · Subscription Meal Plans
 *
 * Shortcodes to use in pages:
 *   [bundle_builder]      → Meal Bundle Builder page
 *   [rewards_page]        → Rewards programme overview
 *   [group_ordering]      → Group ordering / shareable basket
 *   [subscription_plans]  → Subscription meal plans
 *
 * CSS: enqueue chilled-kitchen-custom.css from your child theme folder.
 */

if ( ! defined( 'ABSPATH' ) ) exit;





// ================================================================
// 0. CONSTANTS
// ================================================================

define( 'CKC_POINTS_PER_POUND',       1   ); // Base points earned per £1 spent (Bronze tier)
define( 'CKC_TIER_SILVER_SPEND',      250 ); // Annual spend (£) required for Silver tier
define( 'CKC_TIER_GOLD_SPEND',        750 ); // Annual spend (£) required for Gold tier
define( 'CKC_POINTS_REDEMPTION_RATE', 100 ); // Points needed for £1 discount
define( 'CKC_ACCENT',                 '#c0392b' );


// ================================================================
// 1. DATABASE SETUP
// ================================================================

function ckc_create_tables() {
    global $wpdb;
    $c = $wpdb->get_charset_collate();

    $loyalty = $wpdb->prefix . 'ckc_loyalty_log';
    $groups  = $wpdb->prefix . 'ckc_group_orders';
    $gitems  = $wpdb->prefix . 'ckc_group_order_items';

    $sql = "
        CREATE TABLE IF NOT EXISTS $loyalty (
            id          BIGINT(20)   NOT NULL AUTO_INCREMENT,
            user_id     BIGINT(20)   NOT NULL,
            points      INT(11)      NOT NULL,
            type        VARCHAR(50)  NOT NULL,
            description TEXT,
            order_id    BIGINT(20)   DEFAULT NULL,
            created_at  DATETIME     DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY user_id (user_id)
        ) $c;

        CREATE TABLE IF NOT EXISTS $groups (
            id           BIGINT(20)   NOT NULL AUTO_INCREMENT,
            token        VARCHAR(64)  NOT NULL,
            host_user_id BIGINT(20)   NOT NULL,
            name         VARCHAR(255) NOT NULL,
            status       VARCHAR(20)  DEFAULT 'open',
            deadline     DATETIME     DEFAULT NULL,
            created_at   DATETIME     DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY token (token)
        ) $c;

        CREATE TABLE IF NOT EXISTS $gitems (
            id               BIGINT(20)   NOT NULL AUTO_INCREMENT,
            group_order_id   BIGINT(20)   NOT NULL,
            participant_name VARCHAR(255) NOT NULL,
            participant_email VARCHAR(255) DEFAULT NULL,
            product_id       BIGINT(20)   NOT NULL,
            variation_id     BIGINT(20)   DEFAULT 0,
            quantity         INT(11)      DEFAULT 1,
            notes            TEXT,
            added_at         DATETIME     DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY group_order_id (group_order_id)
        ) $c;
    ";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
}

add_action( 'after_switch_theme', 'ckc_create_tables' );

add_action( 'init', function () {
    if ( get_option( 'ckc_db_version' ) !== '1.2' ) {
        ckc_create_tables();
        update_option( 'ckc_db_version', '1.2' );
    }
} );


// ================================================================
// 2. SHARED SCRIPTS & STYLES
// ================================================================

add_action( 'wp_enqueue_scripts', 'ckc_enqueue_ajax_data' );
function ckc_enqueue_ajax_data() {
    if ( ! function_exists( 'WC' ) ) return;
    wp_localize_script( 'jquery', 'ckc_ajax', [
        'url'      => admin_url( 'admin-ajax.php' ),
        'nonce'    => wp_create_nonce( 'ckc_nonce' ),
        'cart_url' => wc_get_cart_url(),
    ] );
}

// Enqueue the separate CSS file (place chilled-kitchen-custom.css in your child theme folder)
add_action( 'wp_enqueue_scripts', 'ckc_enqueue_styles' );
function ckc_enqueue_styles() {
    // Load child theme stylesheet (contains all CKC custom CSS)
    wp_enqueue_style( 'hello-child-style', get_stylesheet_uri(), [], '1.2' );
    // Also load chilled-kitchen-custom.css if it has content
    $css = get_stylesheet_directory_uri() . '/chilled-kitchen-custom.css';
    wp_enqueue_style( 'ckc-custom', $css, [], '1.2' );
}


// ================================================================
// 3. LOYALTY & REWARDS SYSTEM
// ================================================================

// --- Helpers ---------------------------------------------------

function ckc_get_user_points( $user_id ) {
    return (int) get_user_meta( $user_id, 'ckc_loyalty_points', true );
}

function ckc_add_points( $user_id, $points, $type, $desc = '', $order_id = null ) {
    global $wpdb;
    $new = ckc_get_user_points( $user_id ) + $points;
    update_user_meta( $user_id, 'ckc_loyalty_points', $new );
    $wpdb->insert(
        $wpdb->prefix . 'ckc_loyalty_log',
        [ 'user_id' => $user_id, 'points' => $points, 'type' => $type, 'description' => $desc, 'order_id' => $order_id ],
        [ '%d', '%d', '%s', '%s', '%d' ]
    );
    return $new;
}

function ckc_deduct_points( $user_id, $points, $type, $desc = '', $order_id = null ) {
    global $wpdb;
    $new = max( 0, ckc_get_user_points( $user_id ) - $points );
    update_user_meta( $user_id, 'ckc_loyalty_points', $new );
    $wpdb->insert(
        $wpdb->prefix . 'ckc_loyalty_log',
        [ 'user_id' => $user_id, 'points' => -$points, 'type' => $type, 'description' => $desc, 'order_id' => $order_id ],
        [ '%d', '%d', '%s', '%s', '%d' ]
    );
    return $new;
}

function ckc_get_annual_spend( $user_id ) {
    static $cache = [];
    if ( isset( $cache[ $user_id ] ) ) return $cache[ $user_id ];
    if ( ! $user_id || ! function_exists( 'wc_get_orders' ) ) return 0;
    $orders = wc_get_orders( [
        'customer_id'  => $user_id,
        'status'       => [ 'completed', 'processing' ],
        'date_created' => '>' . gmdate( 'Y-m-d', time() - YEAR_IN_SECONDS ),
        'limit'        => -1,
    ] );
    $total = 0;
    foreach ( $orders as $o ) { $total += (float) $o->get_total(); }
    return $cache[ $user_id ] = $total;
}

function ckc_get_customer_id( $user_id ) {
    $cid = get_user_meta( $user_id, 'ckc_customer_id', true );
    if ( ! $cid ) {
        $cid = 'TCK-' . str_pad( (string) $user_id, 6, '0', STR_PAD_LEFT );
        update_user_meta( $user_id, 'ckc_customer_id', $cid );
    }
    return $cid;
}

// Tier is based on ANNUAL SPEND across all channels (one TCK account):
// Bronze = free, Silver = £250/yr, Gold = £750/yr.
function ckc_get_tier( $user_id ) {
    $spend = ckc_get_annual_spend( $user_id );
    if ( $spend >= CKC_TIER_GOLD_SPEND ) {
        return [ 'name' => 'Gold',   'color' => '#D4AF37', 'multiplier' => 3, 'next' => null,     'spend_to_next' => 0,                               'spend' => $spend ];
    }
    if ( $spend >= CKC_TIER_SILVER_SPEND ) {
        return [ 'name' => 'Silver', 'color' => '#A8A9AD', 'multiplier' => 2, 'next' => 'Gold',   'spend_to_next' => CKC_TIER_GOLD_SPEND - $spend,   'spend' => $spend ];
    }
    return     [ 'name' => 'Bronze', 'color' => '#CD7F32', 'multiplier' => 1, 'next' => 'Silver', 'spend_to_next' => CKC_TIER_SILVER_SPEND - $spend, 'spend' => $spend ];
}

function ckc_get_points_history( $user_id, $limit = 20 ) {
    global $wpdb;
    return $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}ckc_loyalty_log WHERE user_id = %d ORDER BY created_at DESC LIMIT %d",
        $user_id, $limit
    ) );
}

// --- Award points on order completion --------------------------

add_action( 'woocommerce_order_status_completed', 'ckc_award_points_on_order' );
function ckc_award_points_on_order( $order_id ) {
    $order   = wc_get_order( $order_id );
    if ( ! $order ) return;
    $user_id = $order->get_user_id();
    if ( ! $user_id ) return;
    if ( get_post_meta( $order_id, '_ckc_points_awarded', true ) ) return;

    $tier   = ckc_get_tier( $user_id );
    $points = (int) floor( $order->get_subtotal() * CKC_POINTS_PER_POUND * $tier['multiplier'] );
    if ( $points > 0 ) {
        ckc_add_points( $user_id, $points, 'purchase', "Points earned on order #{$order_id}", $order_id );
        update_post_meta( $order_id, '_ckc_points_awarded', $points );
        $order->add_order_note( "Awarded {$points} loyalty points to customer." );
    }
}

// --- Redeem points at checkout --------------------------------

add_action( 'woocommerce_before_order_notes', 'ckc_checkout_redeem_points_ui' );
function ckc_checkout_redeem_points_ui( $checkout ) {
    if ( ! is_user_logged_in() ) return;
    $points = ckc_get_user_points( get_current_user_id() );
    if ( $points < CKC_POINTS_REDEMPTION_RATE ) return;

    $max_discount = floor( $points / CKC_POINTS_REDEMPTION_RATE );
    echo '<div class="ckc-redeem-wrap">';
    echo '<h3>🎁 Use Your Loyalty Points</h3>';
    echo "<p>You have <strong>" . number_format( $points ) . " points</strong> — worth up to <strong>£{$max_discount}</strong> off this order.</p>";
    woocommerce_form_field( 'ckc_redeem_points', [
        'type'              => 'number',
        'label'             => 'Points to redeem (100 points = £1 off)',
        'placeholder'       => '0',
        'custom_attributes' => [ 'min' => 0, 'max' => $points, 'step' => CKC_POINTS_REDEMPTION_RATE ],
    ], 0 );
    echo '</div>';
}

add_action( 'woocommerce_checkout_process', function () {
    $r = isset( $_POST['ckc_redeem_points'] ) ? (int) $_POST['ckc_redeem_points'] : 0;
    WC()->session->set( 'ckc_redeem_points', $r );
} );

add_action( 'woocommerce_cart_calculate_fees', 'ckc_apply_points_discount' );
function ckc_apply_points_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    $pts = (int) WC()->session->get( 'ckc_redeem_points', 0 );
    if ( $pts > 0 ) {
        $discount = floor( $pts / CKC_POINTS_REDEMPTION_RATE );
        $cart->add_fee( 'Loyalty Points Discount', -$discount );
    }
}

add_action( 'woocommerce_checkout_order_processed', 'ckc_process_points_redemption', 10, 3 );
function ckc_process_points_redemption( $order_id, $posted_data, $order ) {
    $pts = (int) WC()->session->get( 'ckc_redeem_points', 0 );
    if ( $pts > 0 && is_user_logged_in() ) {
        ckc_deduct_points( get_current_user_id(), $pts, 'redemption', "Points redeemed on order #{$order_id}", $order_id );
        update_post_meta( $order_id, '_ckc_points_redeemed', $pts );
        WC()->session->set( 'ckc_redeem_points', 0 );
    }
}

// --- My Account loyalty tab -----------------------------------

add_filter( 'woocommerce_account_menu_items', function ( $items ) {
    $items['loyalty-rewards'] = '🎁 My Rewards';
    return $items;
} );

add_action( 'init', function () {
    add_rewrite_endpoint( 'loyalty-rewards', EP_ROOT | EP_PAGES );
} );

add_action( 'woocommerce_account_loyalty-rewards_endpoint', function () {
    if ( ! is_user_logged_in() ) return;
    $user_id = get_current_user_id();
    $points  = ckc_get_user_points( $user_id );
    $tier    = ckc_get_tier( $user_id );
    $cid     = ckc_get_customer_id( $user_id );
    $value   = floor( $points / CKC_POINTS_REDEMPTION_RATE );
    $history = ckc_get_points_history( $user_id );
    ?>
    <div class="ckc-loyalty-account">
        <h2>My Rewards</h2>
        <div class="ckc-points-card" style="border-color:<?= esc_attr( $tier['color'] ) ?>">
            <span class="la-cid">Customer ID: <?= esc_html( $cid ) ?></span>
            <span class="la-tier" style="color:<?= esc_attr( $tier['color'] ) ?>"><?= esc_html( $tier['name'] ) ?> Member</span>
            <span class="la-pts"><?= number_format( $points ) ?> points</span>
            <span class="la-val">Worth £<?= $value ?> off your next order</span>
        </div>
        <?php if ( $tier['next'] ) :
            $prog = $tier['name'] === 'Bronze' ? ( $tier['spend'] / CKC_TIER_SILVER_SPEND ) * 100 : ( $tier['spend'] / CKC_TIER_GOLD_SPEND ) * 100;
        ?>
        <div class="ckc-tier-progress">
            <p>Spend £<?= number_format( $tier['spend_to_next'], 2 ) ?> more this year to reach <?= esc_html( $tier['next'] ) ?></p>
            <div class="ckc-prog-bar"><div style="width:<?= min( 100, round( $prog ) ) ?>%"></div></div>
        </div>
        <?php endif; ?>
        <h3 style="margin-top:30px">Points History</h3>
        <?php if ( $history ) : ?>
        <table class="ckc-pts-table">
            <thead><tr><th>Date</th><th>Description</th><th>Points</th></tr></thead>
            <tbody>
            <?php foreach ( $history as $row ) :
                $sign  = $row->points > 0 ? '+' : '';
                $class = $row->points > 0 ? 'pos' : 'neg';
            ?>
            <tr>
                <td><?= date( 'd M Y', strtotime( $row->created_at ) ) ?></td>
                <td><?= esc_html( $row->description ) ?></td>
                <td class="<?= $class ?>"><?= $sign . number_format( $row->points ) ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php else : ?>
        <p>No points history yet — start shopping to earn rewards!</p>
        <?php endif; ?>
    </div>
    <?php
} );


// --- Admin: manual points adjustment --------------------------

add_filter( 'manage_users_columns', function ( $cols ) {
    $cols['ckc_points'] = 'Loyalty Points';
    return $cols;
} );
add_filter( 'manage_users_custom_column', function ( $val, $col, $uid ) {
    return $col === 'ckc_points' ? number_format( ckc_get_user_points( $uid ) ) : $val;
}, 10, 3 );

add_action( 'show_user_profile',   'ckc_admin_points_field' );
add_action( 'edit_user_profile',   'ckc_admin_points_field' );
function ckc_admin_points_field( $user ) {
    if ( ! current_user_can( 'manage_woocommerce' ) ) return;
    $pts = ckc_get_user_points( $user->ID );
    wp_nonce_field( 'ckc_adjust_points', 'ckc_pts_nonce' );
    ?>
    <h2>Loyalty Points</h2>
    <table class="form-table">
        <tr><th>Current Balance</th><td><strong><?= number_format( $pts ) ?> pts</strong> (£<?= floor( $pts / CKC_POINTS_REDEMPTION_RATE ) ?> value)</td></tr>
        <tr>
            <th><label for="ckc_adj_pts">Adjust Points</label></th>
            <td>
                <input type="number" id="ckc_adj_pts" name="ckc_adj_pts" value="0" style="width:100px">
                &nbsp;
                <input type="text" name="ckc_adj_reason" placeholder="Reason (e.g. goodwill gesture)" style="width:300px">
                <p class="description">Positive = add, negative = deduct.</p>
            </td>
        </tr>
    </table>
    <?php
}

add_action( 'personal_options_update', 'ckc_save_admin_points_field' );
add_action( 'edit_user_profile_update', 'ckc_save_admin_points_field' );
function ckc_save_admin_points_field( $uid ) {
    if ( ! check_admin_referer( 'ckc_adjust_points', 'ckc_pts_nonce' ) ) return;
    if ( ! current_user_can( 'manage_woocommerce' ) ) return;
    $adj    = (int) $_POST['ckc_adj_pts'];
    $reason = sanitize_text_field( $_POST['ckc_adj_reason'] );
    if ( $adj > 0 ) ckc_add_points( $uid, $adj, 'manual', $reason ?: 'Admin adjustment' );
    if ( $adj < 0 ) ckc_deduct_points( $uid, abs( $adj ), 'manual', $reason ?: 'Admin adjustment' );
}


// ================================================================
// 4. BUNDLE BUILDER
// ================================================================

// Bundle size definitions — edit freely
// Structure confirmed by client (Offers & Benefits spec, Aug 2026): bundles mix
// the three top-level catalogue categories — Finger Foods, Main Meals and
// Meal Essentials — rather than the old curries/rice/sides breakdown.
function ckc_bundle_sizes() {
    return [
        'couple' => [ 'name' => 'Couple Bundle',  'emoji' => '👫',         'finger' => 2, 'main' => 1, 'essential' => 1, 'saving' => 10 ],
        'family' => [ 'name' => 'Family Bundle',  'emoji' => '👨‍👩‍👧‍👦', 'finger' => 4, 'main' => 2, 'essential' => 2, 'saving' => 15 ],
        'party'  => [ 'name' => 'Party Bundle',   'emoji' => '🎉',         'finger' => 8, 'main' => 4, 'essential' => 4, 'saving' => 20 ],
    ];
}

// Fetch WooCommerce products by category slug(s).
// Accepts a single slug (e.g. 'finger-foods') or an array of slugs matched
// with OR logic, for cases where multiple categories should be combined.
function ckc_products_by_cat( $slugs ) {
    if ( ! function_exists( 'wc_get_products' ) ) return [];
    $slugs = is_array( $slugs ) ? $slugs : [ $slugs ];
    return wc_get_products( [ 'status' => 'publish', 'category' => $slugs, 'limit' => -1, 'orderby' => 'title', 'order' => 'ASC' ] );
}

// Render a product grid for the builder
function ckc_builder_product_grid( $products, $data_category ) {
    ob_start();
    foreach ( $products as $p ) :
        $price = $p->get_price();
        $img   = get_the_post_thumbnail_url( $p->get_id(), 'thumbnail' ) ?: wc_placeholder_img_src();
    ?>
    <div class="ckc-pcard"
         data-id="<?= esc_attr( $p->get_id() ) ?>"
         data-name="<?= esc_attr( $p->get_name() ) ?>"
         data-price="<?= esc_attr( $price ) ?>"
         data-cat="<?= esc_attr( $data_category ) ?>">
        <img src="<?= esc_url( $img ) ?>" alt="<?= esc_attr( $p->get_name() ) ?>">
        <h4><?= esc_html( $p->get_name() ) ?></h4>
        <p class="ckc-price">£<?= number_format( (float)$price, 2 ) ?></p>
        <div class="ckc-qty-ctrl">
            <button class="ckc-minus" type="button">−</button>
            <span class="ckc-qty">0</span>
            <button class="ckc-plus"  type="button">+</button>
        </div>
    </div>
    <?php endforeach;
    if ( empty( $products ) ) {
        echo '<p class="ckc-no-products">No products found in this category yet. Add products with the WooCommerce category slug shown above.</p>';
    }
    return ob_get_clean();
}

// AJAX: add bundle to cart
add_action( 'wp_ajax_ckc_add_bundle',        'ckc_ajax_add_bundle' );
add_action( 'wp_ajax_nopriv_ckc_add_bundle', 'ckc_ajax_add_bundle' );
function ckc_ajax_add_bundle() {
    check_ajax_referer( 'ckc_nonce', 'nonce' );
    $items   = json_decode( stripslashes( $_POST['items'] ), true );
    $bundle  = sanitize_text_field( $_POST['bundle'] );
    $saving  = (int) $_POST['saving'];

    if ( empty( $items ) ) wp_send_json_error( 'No items selected.' );

    WC()->cart->empty_cart();
    foreach ( $items as $item ) {
        WC()->cart->add_to_cart( (int) $item['id'], (int) $item['qty'], 0, [], [
            'ckc_bundle' => $bundle, 'ckc_saving' => $saving,
        ] );
    }
    WC()->session->set( 'ckc_bundle_saving', $saving );
    wp_send_json_success( 'Bundle added!' );
}

// Apply bundle discount at cart
add_action( 'woocommerce_cart_calculate_fees', 'ckc_apply_bundle_discount' );
function ckc_apply_bundle_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    $saving = WC()->session ? (int) WC()->session->get( 'ckc_bundle_saving', 0 ) : 0;
    if ( $saving > 0 ) {
        $discount = $cart->subtotal * ( $saving / 100 );
        $cart->add_fee( "Bundle Saving ({$saving}% off)", -$discount );
    }
}

// Shortcode: [bundle_builder]
add_shortcode( 'bundle_builder', 'ckc_shortcode_bundle_builder' );
function ckc_shortcode_bundle_builder() {
    $sizes     = ckc_bundle_sizes();
    // Bundle & Benefit spec (Offers & Benefits doc, Aug 2026): bundles mix
    // the three top-level catalogue categories directly.
    $finger    = ckc_products_by_cat( 'finger-foods' );
    $main      = ckc_products_by_cat( 'main-meals' );
    $essential = ckc_products_by_cat( 'meal-essentials' );
    ob_start();
    ?>
    <div id="ckc-builder" class="ckc-builder">

        <!-- Step 0: Choose size -->
        <div class="ckc-step active" data-step="0">
            <h2>🍛 Bundle &amp; Benefit</h2>
            <p class="ckc-subs-sub">Bring your favourites together, save more and make mealtimes easier.</p>
            <p>Mix Finger Foods, Main Meals and Meal Essentials into a bundle designed for the way you eat.</p>
            <div class="ckc-size-grid">
                <?php foreach ( $sizes as $key => $s ) : ?>
                <div class="ckc-size-card" data-bundle="<?= esc_attr( $key ) ?>"
                     data-finger="<?= $s['finger'] ?>" data-main="<?= $s['main'] ?>"
                     data-essential="<?= $s['essential'] ?>" data-saving="<?= $s['saving'] ?>">
                    <div class="sz-emoji"><?= $s['emoji'] ?></div>
                    <h3><?= esc_html( $s['name'] ) ?></h3>
                    <ul>
                        <li><?= $s['finger'] ?> Finger Foods</li>
                        <li><?= $s['main'] ?> Main Meal<?= $s['main'] > 1 ? 's' : '' ?></li>
                        <li><?= $s['essential'] ?> Essential<?= $s['essential'] > 1 ? 's' : '' ?></li>
                    </ul>
                    <span class="sz-saving">Save <?= $s['saving'] ?>%</span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Progress bar (hidden until size chosen) -->
        <div class="ckc-progress" style="display:none">
            <div class="ckc-prog-step active" data-target="1">🥗 Finger Foods</div>
            <div class="ckc-prog-step"        data-target="2">🍛 Main Meals</div>
            <div class="ckc-prog-step"        data-target="3">🍚 Meal Essentials</div>
            <div class="ckc-prog-step"        data-target="4">✅ Review</div>
        </div>

        <!-- Running total (hidden until size chosen) -->
        <div class="ckc-running-total" style="display:none">
            <span>Your bundle:</span>
            <del>£<span id="ckc-was">0.00</span></del>
            <strong>£<span id="ckc-now">0.00</span></strong>
            <em>Saving £<span id="ckc-save">0.00</span></em>
        </div>

        <!-- Step 1: Finger Foods -->
        <div class="ckc-step" data-step="1">
            <h2>Step 1 — Choose Your Finger Foods</h2>
            <p class="ckc-hint">Select <strong id="need-finger">?</strong> finger food(s).</p>
            <div class="ckc-pgrid"><?= ckc_builder_product_grid( $finger, 'finger' ) ?></div>
            <div class="ckc-nav">
                <button class="ckc-back" type="button">← Back</button>
                <button class="ckc-fwd" id="fwd-1" type="button" disabled>Next: Main Meals →</button>
            </div>
        </div>

        <!-- Step 2: Main Meals -->
        <div class="ckc-step" data-step="2">
            <h2>Step 2 — Choose Your Main Meals</h2>
            <p class="ckc-hint">Select <strong id="need-main">?</strong> main meal(s).</p>
            <div class="ckc-pgrid"><?= ckc_builder_product_grid( $main, 'main' ) ?></div>
            <div class="ckc-nav">
                <button class="ckc-back" type="button">← Back</button>
                <button class="ckc-fwd" id="fwd-2" type="button" disabled>Next: Meal Essentials →</button>
            </div>
        </div>

        <!-- Step 3: Meal Essentials -->
        <div class="ckc-step" data-step="3">
            <h2>Step 3 — Choose Your Meal Essentials</h2>
            <p class="ckc-hint">Select <strong id="need-essential">?</strong> essential(s).</p>
            <div class="ckc-pgrid"><?= ckc_builder_product_grid( $essential, 'essential' ) ?></div>
            <div class="ckc-nav">
                <button class="ckc-back" type="button">← Back</button>
                <button class="ckc-fwd" id="fwd-3" type="button" disabled>Review Bundle →</button>
            </div>
        </div>

        <!-- Step 4: Review -->
        <div class="ckc-step" data-step="4">
            <h2>✅ Your Bundle — Ready to Order</h2>
            <div id="ckc-review"></div>
            <div class="ckc-final-total">
                <span>Bundle price: <strong>£<span id="ckc-final-now">0.00</span></strong></span>
                <span class="ckc-saved-tag">You save: £<span id="ckc-final-save">0.00</span></span>
            </div>
            <div class="ckc-nav">
                <button class="ckc-back" type="button">← Edit</button>
                <button class="ckc-primary" id="ckc-add-cart" type="button">Add to Cart 🛒</button>
            </div>
        </div>

        <div id="ckc-msg" style="display:none"></div>
    </div>
<script>
    (function(){
        var step = 0, cfg = {}, sel = { finger:[], main:[], essential:[] };
        var cartUrl = (typeof ckc_ajax !== 'undefined') ? ckc_ajax.cart_url : '/cart';
        var ajaxUrl = (typeof ckc_ajax !== 'undefined') ? ckc_ajax.url    : '';
        var nonce   = (typeof ckc_ajax !== 'undefined') ? ckc_ajax.nonce  : '';
        function showStep(n) {
            document.querySelectorAll('.ckc-step').forEach(function(s){ s.classList.remove('active'); });
            document.querySelector('[data-step="'+n+'"]').classList.add('active');
            step = n;
            if (n > 0) {
                document.querySelector('.ckc-progress').style.display = 'flex';
                document.querySelector('.ckc-running-total').style.display = 'flex';
                document.querySelectorAll('.ckc-prog-step').forEach(function(s,i){
                    s.classList.toggle('active', i+1===n);
                    s.classList.toggle('done',   i+1<n);
                });
            } else {
                document.querySelector('.ckc-progress').style.display = 'none';
                document.querySelector('.ckc-running-total').style.display = 'none';
            }
            updateTotal();
            if (n===4) buildReview();
        }
        function getQty(cat){ return sel[cat].reduce(function(a,b){return a+b.qty;},0); }
        function updateTotal(){
            var was=0;
            ['finger','main','essential'].forEach(function(c){ sel[c].forEach(function(i){ was+=i.price*i.qty; }); });
            var save = was*(cfg.saving/100)||0, now = was-save;
            document.getElementById('ckc-was').textContent  = was.toFixed(2);
            document.getElementById('ckc-now').textContent  = now.toFixed(2);
            document.getElementById('ckc-save').textContent = save.toFixed(2);
            var fn=document.getElementById('ckc-final-now'), fs=document.getElementById('ckc-final-save');
            if(fn){ fn.textContent=now.toFixed(2); fs.textContent=save.toFixed(2); }
        }
        function checkFwd(stepNum){
            var map={1:{cat:'finger',btn:'fwd-1',need:cfg.finger},2:{cat:'main',btn:'fwd-2',need:cfg.main},3:{cat:'essential',btn:'fwd-3',need:cfg.essential}};
            var c=map[stepNum]; if(!c)return;
            var btn=document.getElementById(c.btn); if(btn) btn.disabled = getQty(c.cat)!==c.need;
        }
        function buildReview(){
            // Built with DOM methods (not an HTML string) so that content
            // filters which auto-wrap perceived block tags (e.g. wpautop,
            // triggered when this widget is embedded in a Text Editor block)
            // cannot mangle this script by matching literal tag text.
            function el(tag, text){ var e=document.createElement(tag); if(text!==undefined) e.textContent=text; return e; }
            var table=el('table'), thead=el('thead'), tbody=el('tbody'), hrow=el('tr');
            ['Item','Qty','Price'].forEach(function(h){ hrow.appendChild(el('th',h)); });
            thead.appendChild(hrow);
            ['finger','main','essential'].forEach(function(cat){
                sel[cat].forEach(function(i){
                    var row=el('tr');
                    row.appendChild(el('td',i.name));
                    row.appendChild(el('td',String(i.qty)));
                    row.appendChild(el('td','£'+(i.price*i.qty).toFixed(2)));
                    tbody.appendChild(row);
                });
            });
            table.appendChild(thead); table.appendChild(tbody);
            var reviewEl=document.getElementById('ckc-review');
            reviewEl.innerHTML='';
            reviewEl.appendChild(table);
        }
        // Size card click
        document.querySelectorAll('.ckc-size-card').forEach(function(card){
            card.addEventListener('click',function(){
                document.querySelectorAll('.ckc-size-card').forEach(function(c){c.classList.remove('selected');});
                card.classList.add('selected');
                cfg={ key:card.dataset.bundle, finger:+card.dataset.finger, main:+card.dataset.main, essential:+card.dataset.essential, saving:+card.dataset.saving };
                // Update hints
                ['finger','main','essential'].forEach(function(k){
                    var el=document.getElementById('need-'+k); if(el) el.textContent=cfg[k];
                });
                // Reset qty UI and selections
                sel={finger:[],main:[],essential:[]};
                document.querySelectorAll('.ckc-qty').forEach(function(e){e.textContent='0';});
                ['fwd-1','fwd-2','fwd-3'].forEach(function(id){ var b=document.getElementById(id); if(b)b.disabled=true; });
                setTimeout(function(){showStep(1);},180);
            });
        });
        // Qty controls
        document.querySelectorAll('.ckc-pcard').forEach(function(card){
            var cat   = card.dataset.cat;
            var catK  = cat; // finger / main / essential
            var qtyEl = card.querySelector('.ckc-qty');
            function getN(){ return parseInt(qtyEl.textContent)||0; }
            function needed(){ return cfg[catK]||1; }
            function stepNum(){ return catK==='finger'?1:(catK==='main'?2:3); }
            function pushSel(){
                var n=getN(), id=card.dataset.id, idx=sel[catK].findIndex(function(i){return i.id==id;});
                if(idx>-1){
                    if(n===0) sel[catK].splice(idx,1); else sel[catK][idx].qty=n;
                } else if(n>0){
                    sel[catK].push({id:id,name:card.dataset.name,price:+card.dataset.price,qty:n});
                }
                checkFwd(stepNum());
                updateTotal();
            }
            card.querySelector('.ckc-plus').addEventListener('click',function(){
                if(getQty(catK)>=needed()) return;
                qtyEl.textContent=getN()+1; pushSel();
            });
            card.querySelector('.ckc-minus').addEventListener('click',function(){
                if(getN()<=0) return;
                qtyEl.textContent=getN()-1; pushSel();
            });
        });
        // Forward / back
        document.querySelectorAll('.ckc-fwd').forEach(function(btn){
            btn.addEventListener('click',function(){ if(step<4) showStep(step+1); });
        });
        document.querySelectorAll('.ckc-back').forEach(function(btn){
            btn.addEventListener('click',function(){ if(step>0) showStep(step-1); });
        });
        // Add to cart
        document.getElementById('ckc-add-cart').addEventListener('click',function(){
            var items=[];
            ['finger','main','essential'].forEach(function(c){ sel[c].forEach(function(i){items.push(i);}); });
            if(!items.length) return;
            var btn=this; btn.disabled=true; btn.textContent='Adding…';
            fetch(ajaxUrl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                body:new URLSearchParams({action:'ckc_add_bundle',nonce:nonce,items:JSON.stringify(items),bundle:cfg.key,saving:cfg.saving})
            }).then(function(r){return r.json();}).then(function(d){
                var msg=document.getElementById('ckc-msg');
                msg.style.display='block';
                if(d.success){
                    msg.className='ok';
                    msg.innerHTML='✅ Bundle added to cart! <a href="'+cartUrl+'">View Cart →</a>';
                } else {
                    msg.className='err'; msg.textContent=d.data||'Something went wrong.';
                }
                btn.disabled=false; btn.textContent='Add to Cart 🛒';
            });
        });
    })();
    </script>
    <?php
    return ob_get_clean();
}


// ================================================================
// 5. GROUP ORDERING
// ================================================================

function ckc_group_order_page_url( $token = '' ) {
    $page = get_page_by_path( 'group-ordering' );
    $base = $page ? get_permalink( $page ) : home_url( '/group-ordering/' );
    return $token ? add_query_arg( 'go', $token, $base ) : $base;
}

add_action( 'wp_ajax_ckc_create_group_order', 'ckc_ajax_create_group_order' );
function ckc_ajax_create_group_order() {
    check_ajax_referer( 'ckc_nonce', 'nonce' );
    if ( ! is_user_logged_in() ) wp_send_json_error( 'Please log in to create a group order.' );

    global $wpdb;
    $name     = sanitize_text_field( $_POST['name'] );
    $deadline = sanitize_text_field( $_POST['deadline'] );
    if ( ! $name ) wp_send_json_error( 'Please enter a name for the group order.' );

    $token = bin2hex( random_bytes( 16 ) );
    $wpdb->insert(
        $wpdb->prefix . 'ckc_group_orders',
        [ 'token' => $token, 'host_user_id' => get_current_user_id(), 'name' => $name, 'deadline' => $deadline ?: null, 'status' => 'open' ],
        [ '%s', '%d', '%s', '%s', '%s' ]
    );
    wp_send_json_success( [ 'token' => $token, 'url' => ckc_group_order_page_url( $token ) ] );
}

add_action( 'wp_ajax_ckc_group_add_item',        'ckc_ajax_group_add_item' );
add_action( 'wp_ajax_nopriv_ckc_group_add_item', 'ckc_ajax_group_add_item' );
function ckc_ajax_group_add_item() {
    check_ajax_referer( 'ckc_nonce', 'nonce' );
    global $wpdb;

    $token = sanitize_text_field( $_POST['token'] );
    $group = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ckc_group_orders WHERE token=%s", $token ) );
    if ( ! $group ) wp_send_json_error( 'Group order not found.' );
    if ( $group->status !== 'open' ) wp_send_json_error( 'This group order is now closed.' );
    if ( $group->deadline && strtotime( $group->deadline ) < time() ) wp_send_json_error( 'The deadline has passed.' );

    $wpdb->insert(
        $wpdb->prefix . 'ckc_group_order_items',
        [
            'group_order_id'    => $group->id,
            'participant_name'  => sanitize_text_field( $_POST['participant_name'] ),
            'participant_email' => sanitize_email( $_POST['participant_email'] ),
            'product_id'        => (int) $_POST['product_id'],
            'quantity'          => max( 1, (int) $_POST['quantity'] ),
            'notes'             => sanitize_textarea_field( $_POST['notes'] ),
        ],
        [ '%d', '%s', '%s', '%d', '%d', '%s' ]
    );
    wp_send_json_success( 'Item added!' );
}

add_action( 'wp_ajax_ckc_group_checkout', 'ckc_ajax_group_checkout' );
function ckc_ajax_group_checkout() {
    check_ajax_referer( 'ckc_nonce', 'nonce' );
    if ( ! is_user_logged_in() ) wp_send_json_error( 'Please log in.' );
    global $wpdb;

    $token = sanitize_text_field( $_POST['token'] );
    $group = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ckc_group_orders WHERE token=%s", $token ) );
    if ( ! $group || $group->host_user_id != get_current_user_id() ) wp_send_json_error( 'Access denied.' );

    $items = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ckc_group_order_items WHERE group_order_id=%d", $group->id ) );
    WC()->cart->empty_cart();
    foreach ( $items as $item ) WC()->cart->add_to_cart( $item->product_id, $item->quantity );

    $wpdb->update( $wpdb->prefix . 'ckc_group_orders', [ 'status' => 'closed' ], [ 'id' => $group->id ], [ '%s' ], [ '%d' ] );
    wp_send_json_success( [ 'redirect' => wc_get_checkout_url() ] );
}

// Shortcode: [group_ordering]
add_shortcode( 'group_ordering', 'ckc_shortcode_group_ordering' );
function ckc_shortcode_group_ordering() {
    global $wpdb;
    $token = isset( $_GET['go'] ) ? sanitize_text_field( $_GET['go'] ) : '';
    $group = $token ? $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ckc_group_orders WHERE token=%s", $token ) ) : null;

    ob_start();
    ?>
    <div id="ckc-group" class="ckc-group">
    <?php if ( $group ) :
        $is_host  = is_user_logged_in() && $group->host_user_id == get_current_user_id();
        $items    = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}ckc_group_order_items WHERE group_order_id=%d ORDER BY added_at ASC", $group->id ) );
        $is_open  = $group->status === 'open' && ( ! $group->deadline || strtotime( $group->deadline ) > time() );
        $share_url = esc_attr( ckc_group_order_page_url( $token ) );
    ?>
        <div class="ckc-go-header">
            <h2>🛒 <?= esc_html( $group->name ) ?>
                <?php if ( $is_host ) echo ' <span class="ckc-host-badge">Host</span>'; ?>
            </h2>
            <?php if ( $group->deadline ) : ?>
            <p>Order closes: <strong><?= date( 'D j M, g:ia', strtotime( $group->deadline ) ) ?></strong></p>
            <div id="ckc-countdown" data-dl="<?= esc_attr( $group->deadline ) ?>"></div>
            <?php endif; ?>
            <div class="ckc-share-row">
                <label>Share this link:</label>
                <input type="text" id="ckc-share-url" value="<?= $share_url ?>" readonly>
                <button onclick="navigator.clipboard.writeText(document.getElementById('ckc-share-url').value);this.textContent='Copied!';" class="ckc-copy-btn" type="button">Copy Link</button>
            </div>
        </div>

        <?php if ( $is_open ) : ?>
        <!-- Participant order form -->
        <div class="ckc-add-section">
            <h3>Add Your Order</h3>
            <div class="ckc-participant-row">
                <input type="text"  id="go-name"  placeholder="Your name *" required>
                <input type="email" id="go-email" placeholder="Your email (optional)">
            </div>
            <div class="ckc-pgrid" id="ckc-go-products">
            <?php
            // Exclude subscription products (Meal Plans) from the group-order catalogue —
            // group ordering is for one-off shared baskets, not weekly subscriptions.
            $all_products = wc_get_products( [ 'status' => 'publish', 'type' => [ 'simple', 'variable' ], 'limit' => -1 ] );
            foreach ( $all_products as $p ) :
                $img = get_the_post_thumbnail_url( $p->get_id(), 'thumbnail' ) ?: wc_placeholder_img_src();
            ?>
                <div class="ckc-pcard">
                    <img src="<?= esc_url( $img ) ?>" alt="">
                    <h4><?= esc_html( $p->get_name() ) ?></h4>
                    <p class="ckc-price">£<?= number_format( (float)$p->get_price(), 2 ) ?></p>
                    <button class="ckc-primary go-add" type="button"
                            data-pid="<?= $p->get_id() ?>"
                            data-token="<?= esc_attr( $token ) ?>">Add</button>
                </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php else : ?>
        <div class="ckc-closed-notice">⏰ This group order is now closed.</div>
        <?php endif; ?>

        <!-- Summary -->
        <div class="ckc-go-summary">
            <h3>Current Order — <?= count( $items ) ?> item(s)</h3>
            <?php if ( $items ) : ?>
            <table class="ckc-go-table">
                <thead><tr><th>Who</th><th>Item</th><th>Qty</th></tr></thead>
                <tbody>
                <?php foreach ( $items as $row ) :
                    $pname = ( $prod = wc_get_product( $row->product_id ) ) ? $prod->get_name() : 'Unknown product';
                ?>
                <tr>
                    <td><?= esc_html( $row->participant_name ) ?></td>
                    <td><?= esc_html( $pname ) ?></td>
                    <td><?= (int) $row->quantity ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else : ?>
            <p>No items added yet. Be the first!</p>
            <?php endif; ?>
        </div>

        <?php if ( $is_host && $items ) : ?>
        <div class="ckc-host-controls">
            <h3>Host Controls</h3>
            <p>When everyone has added their items, click below to proceed to checkout for the whole group.</p>
            <button class="ckc-primary" id="ckc-go-checkout" data-token="<?= esc_attr( $token ) ?>" type="button">Checkout for Everyone 🛒</button>
        </div>
        <?php endif; ?>

    <?php elseif ( is_user_logged_in() ) : ?>
        <!-- Create new group order -->
        <h2>🍛 Start a Group Order</h2>
        <p>Create a shareable link, send it to your team, family, or friends — everyone adds their own items, and you check out together. Perfect for office lunches and gatherings.</p>
        <div class="ckc-create-form">
            <label>Order name (e.g. "Office Friday Curry")</label>
            <input type="text" id="go-order-name" placeholder="Office Friday Curry">
            <label>Order deadline (optional)</label>
            <input type="datetime-local" id="go-deadline">
            <button class="ckc-primary" id="ckc-create-go" type="button">Create Group Order</button>
        </div>
        <div id="ckc-go-created" style="display:none">
            <h3>✅ Group order created!</h3>
            <p>Share this link:</p>
            <div class="ckc-share-row">
                <input type="text" id="ckc-new-link" readonly>
                <button onclick="navigator.clipboard.writeText(document.getElementById('ckc-new-link').value);this.textContent='Copied!';" class="ckc-copy-btn" type="button">Copy Link</button>
            </div>
        </div>

    <?php else : ?>
        <div class="ckc-login-prompt">
            <h2>Group Ordering</h2>
            <p>Please <a href="<?= wp_login_url( get_permalink() ) ?>">log in</a> to create a group order, or <a href="<?= wc_get_page_permalink( 'myaccount' ) ?>">register here</a>.</p>
            <p>If you have a group order link, just open it directly — no login needed to add your items.</p>
        </div>
    <?php endif; ?>
    </div>
<script>
    (function(){
        var ajaxUrl = (typeof ckc_ajax!=='undefined') ? ckc_ajax.url   : '';
        var nonce   = (typeof ckc_ajax!=='undefined') ? ckc_ajax.nonce : '';
        // Countdown
        var cd = document.getElementById('ckc-countdown');
        if (cd && cd.dataset.dl) {
            var dl = new Date(cd.dataset.dl).getTime();
            var tick = setInterval(function(){
                var diff = dl - Date.now();
                if (diff<=0){ cd.textContent='Order Closed'; clearInterval(tick); return; }
                var h=Math.floor(diff/3600000), m=Math.floor((diff%3600000)/60000), s=Math.floor((diff%60000)/1000);
                cd.textContent = h+'h '+m+'m '+s+'s remaining';
            }, 1000);
        }
        // Create group order
        var createBtn = document.getElementById('ckc-create-go');
        if (createBtn) {
            createBtn.addEventListener('click', function(){
                var name = document.getElementById('go-order-name').value.trim();
                var dl   = document.getElementById('go-deadline').value;
                if (!name){ alert('Please enter a name for the group order.'); return; }
                createBtn.disabled = true; createBtn.textContent = 'Creating…';
                fetch(ajaxUrl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    body:new URLSearchParams({action:'ckc_create_group_order',nonce:nonce,name:name,deadline:dl})
                }).then(function(r){return r.json();}).then(function(d){
                    if (d.success){
                        document.getElementById('ckc-go-created').style.display='block';
                        document.getElementById('ckc-new-link').value=d.data.url;
                    } else { alert(d.data); }
                    createBtn.disabled=false; createBtn.textContent='Create Group Order';
                });
            });
        }
        // Add item to group order
        document.querySelectorAll('.go-add').forEach(function(btn){
            btn.addEventListener('click', function(){
                var nameEl = document.getElementById('go-name');
                var name   = nameEl ? nameEl.value.trim() : '';
                if (!name){ alert('Please enter your name above.'); return; }
                var email  = (document.getElementById('go-email')||{}).value||'';
                var pid    = btn.dataset.pid;
                var token  = btn.dataset.token;
                btn.disabled=true; btn.textContent='Adding…';
                fetch(ajaxUrl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    body:new URLSearchParams({action:'ckc_group_add_item',nonce:nonce,token:token,
                        participant_name:name,participant_email:email,product_id:pid,quantity:1,notes:''})
                }).then(function(r){return r.json();}).then(function(d){
                    if (d.success){ btn.textContent='✅ Added!'; setTimeout(function(){ location.reload(); },700); }
                    else { alert(d.data); btn.disabled=false; btn.textContent='Add'; }
                });
            });
        });
        // Host checkout
        var coBtn = document.getElementById('ckc-go-checkout');
        if (coBtn) {
            coBtn.addEventListener('click', function(){
                if (!confirm('Add all items to cart and proceed to checkout for the whole group?')) return;
                coBtn.disabled=true; coBtn.textContent='Loading cart…';
                fetch(ajaxUrl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    body:new URLSearchParams({action:'ckc_group_checkout',nonce:nonce,token:coBtn.dataset.token})
                }).then(function(r){return r.json();}).then(function(d){
                    if (d.success){ window.location=d.data.redirect; }
                    else { alert(d.data); coBtn.disabled=false; coBtn.textContent='Checkout for Everyone 🛒'; }
                });
            });
        }
    })();
    </script>
    <?php
    return ob_get_clean();
}


// ================================================================
// 6. CLICK & COLLECT — CUSTOM WOOCOMMERCE SHIPPING METHOD
// ================================================================

add_action( 'woocommerce_shipping_init', function () {

    class CKC_Click_Collect extends WC_Shipping_Method {

        public function __construct( $instance_id = 0 ) {
            $this->id                 = 'ckc_click_collect';
            $this->instance_id        = absint( $instance_id );
            $this->method_title       = 'Click & Collect';
            $this->method_description = 'Free collection from our kitchen';
            $this->supports           = [ 'shipping-zones', 'instance-settings' ];
            $this->init();
        }

        public function init() {
            $this->init_form_fields();
            $this->init_settings();
            $this->title              = $this->get_option( 'title', 'Click & Collect' );
            $this->cost               = $this->get_option( 'cost', '0' );
            add_action( 'woocommerce_update_options_shipping_' . $this->id, [ $this, 'process_admin_options' ] );
        }

        public function init_form_fields() {
            $this->instance_form_fields = [
                'title'              => [ 'title' => 'Title',              'type' => 'text',     'default' => 'Click & Collect' ],
                'cost'               => [ 'title' => 'Cost (£)',           'type' => 'text',     'default' => '0', 'description' => 'Enter 0 for free collection.' ],
                'collection_address' => [ 'title' => 'Collection Address', 'type' => 'textarea', 'default' => '' ],
                'collection_days'    => [ 'title' => 'Collection Days',    'type' => 'text',     'default' => 'Friday, Saturday, Sunday' ],
                'collection_slots'   => [ 'title' => 'Time Slots',         'type' => 'textarea', 'default' => "10:00\n12:00\n14:00\n16:00\n18:00", 'description' => 'One slot per line (24h format).' ],
            ];
        }

        public function calculate_shipping( $package = [] ) {
            $this->add_rate( [ 'id' => $this->get_rate_id(), 'label' => $this->title, 'cost' => $this->cost ] );
        }
    }

} );

add_filter( 'woocommerce_shipping_methods', function ( $methods ) {
    $methods['ckc_click_collect'] = 'CKC_Click_Collect';
    return $methods;
} );

// Helper: get instance settings
function ckc_get_collect_setting( $key, $fallback = '' ) {
    global $wpdb;
    $row = $wpdb->get_row( "SELECT instance_id FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE method_id='ckc_click_collect' LIMIT 1" );
    if ( ! $row ) return $fallback;
    $settings = get_option( 'woocommerce_ckc_click_collect_' . $row->instance_id . '_settings', [] );
    return $settings[ $key ] ?? $fallback;
}

// Show time/date slot selector at checkout when Click & Collect is selected
add_action( 'woocommerce_review_order_before_payment', 'ckc_collect_slot_ui' );
function ckc_collect_slot_ui() {
    $chosen = WC()->session->get( 'chosen_shipping_methods', [] );
    $using  = array_filter( $chosen, fn( $m ) => str_starts_with( $m, 'ckc_click_collect' ) );
    if ( empty( $using ) ) return;

    $slots_raw = ckc_get_collect_setting( 'collection_slots', "10:00\n12:00\n14:00\n16:00\n18:00" );
    $days_raw  = ckc_get_collect_setting( 'collection_days',  'Friday, Saturday, Sunday' );
    $address   = ckc_get_collect_setting( 'collection_address', '' );
    $slots     = array_filter( array_map( 'trim', explode( "\n", $slots_raw ) ) );
    $valid_days = array_map( 'trim', explode( ',', $days_raw ) );
    $day_names  = [ 'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday' ];

    echo '<div class="ckc-collect-ui">';
    echo '<h3>📍 Collection Details</h3>';
    if ( $address ) echo '<p><strong>Collection from:</strong><br>' . nl2br( esc_html( $address ) ) . '</p>';
    echo '<p><strong>Available days:</strong> ' . esc_html( $days_raw ) . '</p>';

    echo '<p><label for="ckc_collect_date"><strong>Preferred Collection Date:</strong></label></p>';
    echo '<select name="ckc_collect_date" id="ckc_collect_date"><option value="">Select a date…</option>';
    for ( $i = 1; $i <= 21; $i++ ) {
        $ts  = strtotime( "+{$i} days" );
        $dn  = $day_names[ date( 'w', $ts ) ];
        if ( in_array( $dn, $valid_days ) ) {
            echo '<option value="' . date( 'Y-m-d', $ts ) . '">' . date( 'l, j F', $ts ) . '</option>';
        }
    }
    echo '</select>';

    echo '<p style="margin-top:14px"><label for="ckc_collect_slot"><strong>Preferred Collection Time:</strong></label></p>';
    echo '<select name="ckc_collect_slot" id="ckc_collect_slot"><option value="">Select a time…</option>';
    foreach ( $slots as $slot ) echo '<option value="' . esc_attr( $slot ) . '">' . esc_html( $slot ) . '</option>';
    echo '</select>';
    echo '</div>';
    echo '
';
}

add_action( 'woocommerce_checkout_process', function () {
    $chosen  = WC()->session->get( 'chosen_shipping_methods', [] );
    $using   = array_filter( $chosen, fn( $m ) => str_starts_with( $m, 'ckc_click_collect' ) );
    if ( empty( $using ) ) return;
    if ( empty( $_POST['ckc_collect_date'] ) ) wc_add_notice( 'Please choose a collection date.', 'error' );
    if ( empty( $_POST['ckc_collect_slot'] ) ) wc_add_notice( 'Please choose a collection time.',  'error' );
} );

// Save the customer's chosen pickup details directly to the order (HPOS-safe).
add_action( 'woocommerce_checkout_create_order', 'ckc_save_collect_order_details', 20, 2 );
function ckc_save_collect_order_details( $order, $data ) {
    if ( ! ckc_checkout_uses_collect() ) return;

    $date = isset( $_POST['ckc_collect_date'] ) && is_string( $_POST['ckc_collect_date'] )
        ? sanitize_text_field( wp_unslash( $_POST['ckc_collect_date'] ) ) : '';
    $slot = isset( $_POST['ckc_collect_slot'] ) && is_string( $_POST['ckc_collect_slot'] )
        ? sanitize_text_field( wp_unslash( $_POST['ckc_collect_slot'] ) ) : '';

    if ( $date ) $order->update_meta_data( '_ckc_collect_date', $date );
    if ( $slot ) $order->update_meta_data( '_ckc_collect_slot', $slot );
}

function ckc_checkout_uses_collect() {
    if ( ! function_exists( 'WC' ) || ! WC()->session ) return false;
    foreach ( (array) WC()->session->get( 'chosen_shipping_methods', [] ) as $method ) {
        if ( strpos( (string) $method, 'ckc_click_collect' ) === 0 ) return true;
    }
    return false;
}

function ckc_order_uses_collect( $order ) {
    if ( ! $order instanceof WC_Order ) return false;
    foreach ( $order->get_items( 'shipping' ) as $shipping_item ) {
        if ( 'ckc_click_collect' === $shipping_item->get_method_id() ) return true;
    }
    return false;
}

// Show pickup details in WooCommerce > Orders, without depending on wp_postmeta.
add_action( 'woocommerce_admin_order_data_after_shipping_address', function ( $order ) {
    if ( ! ckc_order_uses_collect( $order ) ) return;
    $date = $order->get_meta( '_ckc_collect_date' );
    $slot = $order->get_meta( '_ckc_collect_slot' );
    echo '<p><strong>Click &amp; Collect</strong></p>';
    echo '<p><strong>Pickup address:</strong><br>269 Park Road<br>Oldham<br>OL4 1RT</p>';
    if ( $date ) {
        $timestamp = strtotime( $date );
        echo '<p><strong>Collection date:</strong> ' . esc_html( $timestamp ? wp_date( 'l, j F Y', $timestamp ) : $date ) . '</p>';
    }
    if ( $slot ) echo '<p><strong>Collection time:</strong> ' . esc_html( $slot ) . '</p>';
} );

// WooCommerce customer and store New Order emails: collection address, date and time.
// Delivery orders retain their normal shipping address.
add_action( 'woocommerce_email_after_order_table', 'ckc_email_collection_information', 15, 4 );
function ckc_email_collection_information( $order, $sent_to_admin, $plain_text, $email ) {
    if ( ! ckc_order_uses_collect( $order ) ) return;

    $date = $order->get_meta( '_ckc_collect_date' );
    $slot = $order->get_meta( '_ckc_collect_slot' );
    if ( $date ) {
        $timestamp = strtotime( $date );
        if ( $timestamp ) $date = wp_date( 'l, j F Y', $timestamp );
    }

    if ( $plain_text ) {
        echo "\nCLICK & COLLECT\n";
        echo "Collection address: 269 Park Road, Oldham, OL4 1RT\n";
        if ( $date ) echo 'Collection date: ' . $date . "\n";
        if ( $slot ) echo 'Collection time: ' . $slot . "\n";
        echo "\n";
        return;
    }

    echo '<div style="margin:24px 0">';
    echo '<h2>Click &amp; Collect details</h2>';
    echo '<p><strong>Collection address:</strong><br>269 Park Road<br>Oldham<br>OL4 1RT</p>';
    if ( $date ) echo '<p><strong>Collection date:</strong> ' . esc_html( $date ) . '</p>';
    if ( $slot ) echo '<p><strong>Collection time:</strong> ' . esc_html( $slot ) . '</p>';
    echo '</div>';
}

// Hide the *customer shipping address* in the standard WooCommerce email address
// section for collection orders. Do not change stored addresses or delivery orders.
add_filter( 'woocommerce_order_get_formatted_shipping_address', function ( $address, $raw_address, $order ) {
    if ( doing_action( 'woocommerce_email_customer_details' ) && ckc_order_uses_collect( $order ) ) {
        return '';
    }
    return $address;
}, 10, 3 );


// ================================================================
// 7. SUBSCRIPTION MEAL PLANS (WooCommerce Subscriptions)
// ================================================================
//
// The three confirmed plans (client sign-off, July 2026):
//   Essential (Daily Driver)      - 5 meals  - £7.99/meal - £39.95
//   Elevated  (Performance Boost) - 10 meals - £6.99/meal - £69.90
//   Extensive (Conscious Premium) - 15 meals - £5.99/meal - £89.85
//
// Checkout links come from the WooCommerce products in the
// "meal-plans" category (matched by plan name). Card copy below
// is the confirmed client content.
// ----------------------------------------------------------------

function ckc_confirmed_plans() {
    return [
        [
            'name'     => 'Essential',
            'tag'      => 'Daily Driver',
            'meals'    => 5,
            'audience' => 'Perfect for one person or sharing.',
            'per_meal' => 7.99,
            'total'    => 39.95,
            'lead'     => 'Includes:',
            'features' => [
                '5 freshly prepared chef-made meals each week',
                'Choice of meals from the weekly rotating menu',
                'Collection from The Chilled Kitchen flagship store',
                'Ability to pause, skip, or cancel at any time',
                'Earn TCK Rewards Points on every order',
            ],
            'featured' => false,
        ],
        [
            'name'     => 'Elevated',
            'tag'      => 'Performance Boost',
            'meals'    => 10,
            'audience' => 'Perfect for couples and small families.',
            'per_meal' => 6.99,
            'total'    => 69.90,
            'lead'     => 'Includes everything in Essential, plus:',
            'features' => [
                'Full meal customisation with mix-and-match options',
                'Discounted local delivery (where available)',
                'Priority access to newly released weekly meals',
                'Bonus TCK Rewards Points on subscription orders',
                'Exclusive subscriber offers and seasonal promotions',
            ],
            'featured' => true,
        ],
        [
            'name'     => 'Extensive',
            'tag'      => 'Conscious Premium',
            'meals'    => 15,
            'audience' => 'Perfect for larger families and regular meal requirements.',
            'per_meal' => 5.99,
            'total'    => 89.85,
            'lead'     => 'Includes everything in Elevated, plus:',
            'features' => [
                'Complimentary local delivery (within eligible areas)',
                'Early access to limited-edition and chef-special meals',
                'One complimentary premium side or drink each week',
                'Priority customer support',
                'Access to Premium Member rewards and exclusive menu items',
            ],
            'featured' => false,
        ],
    ];
}

add_shortcode( 'subscription_plans', 'ckc_shortcode_subscriptions' );
function ckc_shortcode_subscriptions() {
    $plans    = ckc_confirmed_plans();
    $products = function_exists( 'wc_get_products' ) ? wc_get_products( [
        'status'   => 'publish',
        'category' => [ 'meal-plans' ],
        'limit'    => -1,
    ] ) : [];
    ob_start();
    ?>
    <div class="ckc-subs">
        <h2>Subscription Meal Plans</h2>
        <p class="ckc-subs-intro">Freshly prepared, chef-made meals every week. Collect from our flagship store or choose local delivery where available. Pause, skip or cancel at any time.</p>
        <div class="ckc-plans-grid">
        <?php foreach ( $plans as $plan ) :
            $product = null;
            foreach ( $products as $p ) {
                if ( stripos( $p->get_name(), $plan['name'] ) !== false ) { $product = $p; break; }
            }
            $cart_url = $product ? $product->add_to_cart_url() : wc_get_page_permalink( 'shop' );
        ?>
            <div class="ckc-plan<?= $plan['featured'] ? ' ckc-plan-featured' : '' ?>">
                <?php if ( $plan['featured'] ) : ?><span class="ckc-plan-flag">Most Popular</span><?php endif; ?>
                <span class="ckc-plan-tag"><?= esc_html( $plan['tag'] ) ?></span>
                <h3><?= esc_html( $plan['name'] ) ?></h3>
                <span class="ckc-plan-meals"><?= (int) $plan['meals'] ?> meals per week</span>
                <p class="plan-desc"><?= esc_html( $plan['audience'] ) ?></p>
                <div class="plan-price">
                    <span class="plan-price-main">£<?= number_format( $plan['per_meal'], 2 ) ?> <small>per meal</small></span>
                    <span class="plan-price-total">£<?= number_format( $plan['total'], 2 ) ?> per week</span>
                </div>
                <p class="plan-lead"><?= esc_html( $plan['lead'] ) ?></p>
                <ul class="plan-perks">
                    <?php foreach ( $plan['features'] as $f ) : ?>
                    <li>✅ <?= esc_html( $f ) ?></li>
                    <?php endforeach; ?>
                </ul>
                <a class="ckc-btn plan-btn" href="<?= esc_url( $cart_url ) ?>">Subscribe Now</a>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
    <style>
        .ckc-plan{position:relative}
        .ckc-plan-featured{border:2px solid <?= CKC_ACCENT ?>;box-shadow:0 8px 24px rgba(0,0,0,.08)}
        .ckc-plan-flag{position:absolute;top:-12px;left:50%;transform:translateX(-50%);background:<?= CKC_ACCENT ?>;color:#fff;padding:2px 14px;border-radius:999px;font-size:12px;font-weight:700;white-space:nowrap}
        .ckc-plan-tag{display:block;text-transform:uppercase;letter-spacing:1px;font-size:12px;opacity:.7;margin-top:6px}
        .ckc-plan-meals{display:inline-block;background:#f4ede4;border-radius:999px;padding:2px 12px;font-size:13px;font-weight:600;margin:4px 0 8px}
        .plan-price-main{display:block;font-size:26px;font-weight:800}
        .plan-price-main small{font-size:13px;font-weight:500}
        .plan-price-total{display:block;font-size:14px;opacity:.75}
        .plan-lead{font-weight:600;margin:10px 0 4px}
    </style>
    <?php
    return ob_get_clean();
}


// ================================================================
// 8. REWARDS PAGE SHORTCODE — TCK Rewards (loyalty landing page)
// ================================================================
//
// Tiers are based on annual spend across ALL channels (flagship
// store, takeaway and subscriptions) under one TCK Customer ID:
//   Bronze - free              - 1 point per £1
//   Silver - £250 annual spend - 2 points per £1
//   Gold   - £750 annual spend - 3 points per £1
// 100 points = £1 Rewards Credit, redeemable at checkout.
// ----------------------------------------------------------------

add_shortcode( 'rewards_page', 'ckc_shortcode_rewards_page' );
function ckc_shortcode_rewards_page() {
    $uid      = get_current_user_id();
    $loggedin = is_user_logged_in();
    $points   = $loggedin ? ckc_get_user_points( $uid ) : 0;
    $tier     = $loggedin ? ckc_get_tier( $uid ) : null;
    $value    = $loggedin ? floor( $points / CKC_POINTS_REDEMPTION_RATE ) : 0;
    $cid      = $loggedin ? ckc_get_customer_id( $uid ) : '';
    $history  = $loggedin ? ckc_get_points_history( $uid, 10 ) : [];

    $tiers = [
        [ 'name' => 'Bronze', 'color' => '#CD7F32', 'req' => 'Free', 'perks' => [
            'Earn 1 point per £1 spent',
            '100 points = £1 Rewards Credit',
            'Birthday reward',
            'Exclusive member offers',
        ] ],
        [ 'name' => 'Silver', 'color' => '#A8A9AD', 'req' => '£250 annual spend', 'perks' => [
            'Everything included in Bronze',
            'Double points (2 points per £1 spent)',
            'Early access to new menu items',
            'Monthly exclusive offers',
        ] ],
        [ 'name' => 'Gold', 'color' => '#D4AF37', 'req' => '£750 annual spend', 'perks' => [
            'Everything included in Silver',
            'Triple points (3 points per £1 spent)',
            'Priority ordering',
            'Complimentary side or drink each month',
            'Secret menu items',
            'VIP event invitations',
            'Surprise rewards',
        ] ],
    ];
    ob_start();
    ?>
    <div class="ckc-rewards-pg">

        <!-- Hero balance -->
        <div class="ckc-rh">
            <h1>🎁 TCK Rewards</h1>
            <p>One account. One Customer ID. Earn points on every purchase — in our flagship store, on takeaway and on subscriptions.</p>
            <?php if ( $loggedin ) : ?>
            <div class="ckc-balance-card" style="border-color:<?= esc_attr( $tier['color'] ) ?>">
                <span class="bc-cid">Customer ID: <?= esc_html( $cid ) ?></span>
                <span class="bc-tier" style="color:<?= esc_attr( $tier['color'] ) ?>"><?= esc_html( $tier['name'] ) ?> Member</span>
                <span class="bc-pts"><?= number_format( $points ) ?> points</span>
                <span class="bc-val">Worth £<?= $value ?> off your next order</span>
                <?php if ( $tier['next'] ) :
                    $target = $tier['name'] === 'Bronze' ? CKC_TIER_SILVER_SPEND : CKC_TIER_GOLD_SPEND;
                    $prog   = min( 100, round( ( $tier['spend'] / $target ) * 100 ) );
                ?>
                <div class="bc-progress">
                    <p>You have spent £<?= number_format( $tier['spend'], 2 ) ?> this year — £<?= number_format( $tier['spend_to_next'], 2 ) ?> more to reach <?= esc_html( $tier['next'] ) ?></p>
                    <div class="ckc-prog-bar"><div style="width:<?= $prog ?>%"></div></div>
                </div>
                <?php endif; ?>
                <a class="ckc-btn" href="<?= esc_url( wc_get_page_permalink( 'myaccount' ) ) ?>loyalty-rewards/">View my rewards history</a>
            </div>
            <?php else : ?>
            <a class="ckc-btn" href="<?= esc_url( wp_login_url( get_permalink() ) ) ?>">Log in to see your points</a>
            <?php endif; ?>
        </div>

        <!-- How it works -->
        <div class="ckc-how-sec">
            <h2>How It Works</h2>
            <div class="ckc-how-grid">
                <div class="ckc-how"><div class="how-i">🛒</div><h3>Shop anywhere</h3><p>Earn points for every £1 you spend in-store, on takeaway or on your subscription — all on one TCK account.</p></div>
                <div class="ckc-how"><div class="how-i">⬆️</div><h3>Level up</h3><p>Spend £250 a year to reach Silver and earn double points. Spend £750 to reach Gold and earn triple points.</p></div>
                <div class="ckc-how"><div class="how-i">💰</div><h3>Redeem</h3><p><?= CKC_POINTS_REDEMPTION_RATE ?> points = £1 Rewards Credit at checkout. Use as many or as few as you like.</p></div>
                <div class="ckc-how"><div class="how-i">🎉</div><h3>Enjoy the perks</h3><p>Birthday rewards, early access, secret menu items, VIP events and surprise treats as you move up the tiers.</p></div>
            </div>
        </div>

        <!-- Tier breakdown -->
        <div class="ckc-tiers-sec">
            <h2>Member Tiers</h2>
            <div class="ckc-tiers-grid">
                <?php foreach ( $tiers as $t ) : $active = $tier && $tier['name'] === $t['name']; ?>
                <div class="ckc-tier-card<?= $active ? ' tier-active' : '' ?>" style="border-top:4px solid <?= esc_attr( $t['color'] ) ?>">
                    <h3 style="color:<?= esc_attr( $t['color'] ) ?>"><?= esc_html( $t['name'] ) ?></h3>
                    <span class="tier-req"><?= esc_html( $t['req'] ) ?></span>
                    <?php if ( $active ) : ?><span class="tier-you">Your tier</span><?php endif; ?>
                    <ul>
                        <?php foreach ( $t['perks'] as $perk ) : ?><li><?= esc_html( $perk ) ?></li><?php endforeach; ?>
                    </ul>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if ( $loggedin && $history ) : ?>
        <div class="ckc-recent-sec">
            <h2>Recent Activity</h2>
            <table class="ckc-pts-table">
                <thead><tr><th>Date</th><th>Description</th><th>Points</th></tr></thead>
                <tbody>
                <?php foreach ( $history as $row ) : ?>
                <tr>
                    <td><?= date( 'd M Y', strtotime( $row->created_at ) ) ?></td>
                    <td><?= esc_html( $row->description ) ?></td>
                    <td><?= ( $row->points > 0 ? '+' : '' ) . (int) $row->points ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
    <style>
        .bc-cid{display:block;font-size:12px;letter-spacing:1px;opacity:.7;text-transform:uppercase}
        .bc-progress{margin-top:10px}
        .ckc-tier-card .tier-req{display:inline-block;font-size:13px;font-weight:600;opacity:.75;margin-bottom:8px}
        .ckc-tier-card .tier-you{display:inline-block;margin-left:8px;background:#2e7d32;color:#fff;font-size:11px;padding:1px 8px;border-radius:999px}
        .ckc-tier-card.tier-active{outline:2px solid #2e7d32}
    </style>
    <?php
    return ob_get_clean();
}


// ================================================================
// 8B. FAQ PAGE — [tck_faq]
// ================================================================
//
// Renders the 30 client-approved FAQs as an accessible accordion
// and outputs FAQPage JSON-LD schema for SEO.
// ----------------------------------------------------------------

function ckc_faq_items() {
    return [
        [ "What is The Chilled Kitchen?", "The Chilled Kitchen (TCK) is a premium fresh food brand by AI Catering Services, offering chef-prepared meals through our flagship store, takeaway service and flexible meal subscriptions. Our meals are freshly prepared, chilled and ready to enjoy at your convenience." ],
        [ "How do the meal subscriptions work?", "Choose a meal plan that suits your lifestyle, select your meals each week and we'll prepare them fresh for collection or delivery (where available). You can pause, skip or cancel your subscription at any time." ],
        [ "Can I choose my own meals?", "Yes. Our weekly menu offers a variety of dishes, allowing you to mix and match meals based on your preferences. Menu selections may vary depending on your subscription plan." ],
        [ "How long do the meals stay fresh?", "Our meals are freshly prepared and chilled to maintain quality and freshness. Storage instructions and use-by dates are clearly displayed on every meal." ],
        [ "Do you offer vegetarian, vegan or healthier options?", "Yes. We aim to provide a wide variety of meals, including healthier choices as well as vegetarian and other dietary options. Our menu continues to expand based on customer feedback." ],
        [ "Can I collect my order or do you offer delivery?", "Customers can collect orders from The Chilled Kitchen flagship store, and local delivery is available in selected areas. Delivery options will be displayed during checkout." ],
        [ "Can I pause or cancel my subscription?", "Absolutely. We understand that plans change. You can pause, skip or cancel your subscription easily through your account before your next billing cycle." ],
        [ "Do I earn rewards when I purchase meals?", "Yes. Every eligible purchase made in-store, through takeaway or via a subscription earns TCK Rewards Points. Your points can be redeemed for discounts, exclusive offers and other member benefits." ],
        [ "How do I heat my meals?", "Each meal includes simple heating instructions on the packaging. Most meals can be heated in either a microwave or oven while maintaining their quality and flavour." ],
        [ "Do you cater for allergies and dietary requirements?", "We clearly label ingredients and common allergens on all meals. While we take great care during preparation, our kitchen handles a variety of ingredients, so customers with severe allergies should contact us before placing an order." ],
        [ "Do I need to order in advance?", "Walk-in customers are always welcome, subject to availability. Pre-ordering is recommended to guarantee your preferred meals." ],
        [ "Can I order for someone else?", "Yes. You can place an order on behalf of friends, family or colleagues for collection or delivery." ],
        [ "Can I place large or corporate orders?", "Yes. We offer catering trays, meal packages and corporate food solutions. Please contact us for larger orders and business enquiries." ],
        [ "When will I be charged for my subscription?", "Your subscription is billed automatically according to your selected billing cycle. You'll receive a reminder before each renewal." ],
        [ "Can I change my subscription plan?", "Yes. You can upgrade or downgrade your meal plan at any time before your next billing cycle." ],
        [ "What happens if I forget to choose my meals?", "If a menu selection isn't made before the weekly cut-off, we'll prepare a selection of our most popular meals for your plan." ],
        [ "Are your meals cooked fresh?", "Yes. Every meal is freshly prepared by our chefs using quality ingredients before being chilled to preserve freshness and flavour." ],
        [ "Where do you source your ingredients?", "We aim to source high-quality ingredients from trusted suppliers, with a focus on freshness and consistency." ],
        [ "Are nutritional details available?", "Yes. Nutritional information and allergen guidance are available for each meal where applicable." ],
        [ "Which areas do you deliver to?", "Delivery is available within selected local areas. Enter your postcode during checkout to confirm availability." ],
        [ "Can I choose my collection or delivery time?", "Yes. Available collection and delivery time slots are displayed during checkout." ],
        [ "How do TCK Rewards Points work?", "Earn points every time you make an eligible purchase in-store, through takeaway or with your subscription. Points can be redeemed for future rewards and exclusive member benefits." ],
        [ "Do my Rewards Points expire?", "Rewards Points remain active provided your account remains active. Full details can be found in the TCK Rewards Terms and Conditions." ],
        [ "Can I use Rewards Points together with promotional offers?", "In most cases, yes. Certain promotions may have specific conditions, explained at checkout." ],
        [ "Which payment methods do you accept?", "We accept all major debit and credit cards, along with selected digital payment methods. Accepted payment options will be displayed during checkout." ],
        [ "Is there a minimum order value?", "Some delivery services may require a minimum order value. Collection orders have no minimum spend." ],
        [ "Do you offer gift cards?", "Yes. Digital gift cards are available and can be redeemed online or in-store." ],
        [ "Can I provide feedback on my meals?", "Absolutely. Customer feedback helps us improve our menu and service. You can leave a review through your account or contact our team directly." ],
        [ "What makes The Chilled Kitchen different?", "The Chilled Kitchen combines restaurant-quality meals with the convenience of takeaway and flexible subscriptions. Our focus is on fresh ingredients, premium quality, flexible plans and rewarding loyal customers." ],
        [ "Will you be adding more meals and services in the future?", "Yes. We regularly introduce new dishes, seasonal specials and additional services based on customer feedback and demand." ],
    ];
}

add_shortcode( 'tck_faq', 'ckc_shortcode_faq' );
function ckc_shortcode_faq() {
    $faqs   = ckc_faq_items();
    $schema = [ '@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => [] ];
    foreach ( $faqs as $f ) {
        $schema['mainEntity'][] = [
            '@type'          => 'Question',
            'name'           => $f[0],
            'acceptedAnswer' => [ '@type' => 'Answer', 'text' => $f[1] ],
        ];
    }
    ob_start();
    ?>
    <div class="ckc-faq-wrap">
        <div class="ckc-faq-hero">
            <span class="ckc-faq-kicker">Help &amp; Support</span>
            <h1>Frequently Asked Questions</h1>
            <p>Everything you need to know about The Chilled Kitchen — our meals, subscriptions, collection and delivery, and TCK Rewards.</p>
            <input type="text" id="ckc-faq-search" placeholder="Search questions — e.g. delivery, rewards, allergens" aria-label="Search FAQs">
        </div>
        <div class="ckc-faq">
            <?php foreach ( $faqs as $i => $f ) : ?>
            <details class="ckc-faq-item"<?= $i === 0 ? ' open' : '' ?>>
                <summary><span class="faq-q"><?= esc_html( $f[0] ) ?></span><span class="faq-toggle" aria-hidden="true"></span></summary>
                <div class="faq-a"><p><?= esc_html( $f[1] ) ?></p></div>
            </details>
            <?php endforeach; ?>
            <p class="ckc-faq-none" hidden>No results — try a different word, or get in touch below.</p>
        </div>
        <div class="ckc-faq-cta">
            <h2>Still have a question?</h2>
            <p>Our team is happy to help with anything not covered here.</p>
            <a class="ckc-faq-btn" href="<?= esc_url( home_url( '/contact/' ) ) ?>">Contact Us</a>
        </div>
    </div>
    <script type="application/ld+json"><?= wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ?></script>
    <script>
    (function(){
        var s = document.getElementById('ckc-faq-search'); if (!s) return;
        var items = [].slice.call(document.querySelectorAll('.ckc-faq-item'));
        var none  = document.querySelector('.ckc-faq-none');
        s.addEventListener('input', function(){
            var q = this.value.toLowerCase().trim(), shown = 0;
            items.forEach(function(it){
                var hit = !q || it.textContent.toLowerCase().indexOf(q) > -1;
                it.hidden = !hit; if (hit) shown++;
            });
            if (none) none.hidden = shown > 0;
        });
    })();
    </script>
    <style>
    .ckc-faq-wrap{max-width:840px;margin:0 auto;padding:24px 20px 72px;font-family:Inter,sans-serif}
    .ckc-faq-hero{text-align:center;margin-bottom:36px}
    .ckc-faq-kicker{display:inline-block;text-transform:uppercase;letter-spacing:2px;font-size:12px;font-weight:600;color:#c0392b;margin-bottom:10px}
    .ckc-faq-hero h1{font-family:'Hedvig Letters Serif',serif;font-weight:400;color:#1d2a23;font-size:44px;margin:0 0 12px}
    .ckc-faq-hero p{color:#5a5a52;max-width:560px;margin:0 auto 22px;line-height:1.6}
    #ckc-faq-search{width:100%;max-width:520px;padding:14px 20px;border:1px solid #d9cdb9;border-radius:999px;background:#fff;font-size:15px;font-family:inherit;color:#1d2a23;outline:none;transition:border-color .2s, box-shadow .2s}
    #ckc-faq-search:focus{border-color:#1d2a23;box-shadow:0 0 0 3px rgba(29,42,35,.08)}
    .ckc-faq-item{border:1px solid #e6dcc9;border-radius:12px;margin-bottom:12px;background:#fff;transition:box-shadow .2s,border-color .2s;overflow:hidden}
    .ckc-faq-item[open]{border-color:#1d2a23;box-shadow:0 6px 18px rgba(29,42,35,.08)}
    .ckc-faq-item summary{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:18px 22px;cursor:pointer;list-style:none}
    .ckc-faq-item summary::-webkit-details-marker{display:none}
    .faq-q{font-family:'Hedvig Letters Serif',serif;font-size:19px;color:#1d2a23;line-height:1.35}
    .faq-toggle{flex:0 0 28px;height:28px;border-radius:50%;background:#f4eee2;position:relative}
    .faq-toggle::before,.faq-toggle::after{content:'';position:absolute;background:#1d2a23;transition:transform .2s}
    .faq-toggle::before{width:12px;height:2px;top:13px;left:8px}
    .faq-toggle::after{width:2px;height:12px;top:8px;left:13px}
    .ckc-faq-item[open] .faq-toggle::after{transform:rotate(90deg)}
    .faq-a{padding:0 22px 20px;border-top:1px solid #f0e8d8}
    .faq-a p{margin:14px 0 0;color:#4a4a44;line-height:1.7;font-size:15.5px}
    .ckc-faq-none{text-align:center;color:#5a5a52;padding:24px 0}
    .ckc-faq-cta{margin-top:48px;text-align:center;background:#1d2a23;border-radius:16px;padding:40px 28px}
    .ckc-faq-cta h2{font-family:'Hedvig Letters Serif',serif;font-weight:400;color:#e4d7c5;font-size:28px;margin:0 0 8px}
    .ckc-faq-cta p{color:#bfb4a2;margin:0 0 20px}
    .ckc-faq-btn{display:inline-block;background:#e4d7c5;color:#1d2a23 !important;padding:12px 30px;border-radius:999px;font-weight:600;text-decoration:none;transition:opacity .2s}
    .ckc-faq-btn:hover{opacity:.85}
    @media (max-width:600px){.ckc-faq-hero h1{font-size:32px}.faq-q{font-size:17px}}
    </style>
    <?php
    return ob_get_clean();
}


// ================================================================
// 9. FLUSH REWRITE RULES (one-time on theme activation)
// ================================================================

add_action( 'after_switch_theme', 'flush_rewrite_rules' );


// ====================================================================
// 6. GIFT CARDS
// ====================================================================

function ckc_create_gift_card_table() {
    global $wpdb;
    $c  = $wpdb->get_charset_collate();
    $gc = $wpdb->prefix . 'ckc_gift_cards';
    $sql = "CREATE TABLE IF NOT EXISTS $gc (
        id              BIGINT(20)   NOT NULL AUTO_INCREMENT,
        code            VARCHAR(20)  NOT NULL,
        initial_amount  DECIMAL(10,2) NOT NULL,
        balance         DECIMAL(10,2) NOT NULL,
        buyer_user_id   BIGINT(20)   DEFAULT NULL,
        recipient_email VARCHAR(255) DEFAULT NULL,
        order_id        BIGINT(20)   DEFAULT NULL,
        created_at      DATETIME     DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY code (code)
    ) $c;";
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
}
add_action( 'init', function () {
    if ( get_option( 'ckc_giftcard_db_version' ) !== '1.0' ) {
        ckc_create_gift_card_table();
        update_option( 'ckc_giftcard_db_version', '1.0' );
    }
} );

function ckc_ensure_gift_card_products() {
    if ( get_option( 'ckc_giftcard_products_created' ) ) return;
    if ( ! function_exists( 'wp_insert_post' ) || ! taxonomy_exists( 'product_type' ) ) return;
    global $wpdb;
    $amounts = [ 25, 50, 100 ];
    foreach ( $amounts as $amount ) {
        $sku = 'tck-gift-card-' . $amount;
        $existing = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_sku' AND meta_value = %s LIMIT 1", $sku ) );
        if ( $existing ) continue;
        $post_id = wp_insert_post( [
            'post_title'  => 'TCK Digital Gift Card - £' . $amount,
            'post_status' => 'publish',
            'post_type'   => 'product',
        ] );
        if ( ! $post_id || is_wp_error( $post_id ) ) continue;
        update_post_meta( $post_id, '_sku', $sku );
        update_post_meta( $post_id, '_price', $amount );
        update_post_meta( $post_id, '_regular_price', $amount );
        update_post_meta( $post_id, '_virtual', 'yes' );
        update_post_meta( $post_id, '_stock_status', 'instock' );
        update_post_meta( $post_id, '_manage_stock', 'no' );
        update_post_meta( $post_id, 'ckc_gift_card_amount', $amount );
        wp_set_object_terms( $post_id, 'simple', 'product_type' );
        if ( taxonomy_exists( 'product_visibility' ) ) {
            wp_set_object_terms( $post_id, [ 'exclude-from-catalog', 'exclude-from-search' ], 'product_visibility' );
        }
    }
    update_option( 'ckc_giftcard_products_created', 1 );
}
add_action( 'init', 'ckc_ensure_gift_card_products', 20 );

function ckc_benefit_styles_once() {
    static $printed = false;
    if ( $printed ) return '';
    $printed = true;
    ob_start();
    ?>
    <style>
    .ckc-benefit-section{max-width:900px;margin:0 auto 56px;padding:0 20px}
    .ckc-benefit-head h2{font-family:'Hedvig Letters Serif',serif;font-weight:400;color:#1d2a23;font-size:30px;margin:0 0 10px}
    .ckc-benefit-sub{color:#4a4a44;font-size:16px;line-height:1.6;margin:0 0 20px;max-width:640px}
    .ckc-benefit-list{margin:0 0 24px;padding-left:20px;color:#4a4a44;line-height:1.9}
    .ckc-benefit-btn{display:inline-block;background:#1d2a23;color:#f4eee2 !important;padding:13px 30px;border-radius:30px;text-decoration:none;font-weight:600;letter-spacing:.02em}
    .ckc-benefit-btn:hover{background:#2b3c31}
    .ckc-giftcard-grid{display:flex;gap:16px;flex-wrap:wrap;margin-bottom:28px}
    .ckc-giftcard-card{background:#f4eee2;border-radius:14px;padding:24px;text-align:center;min-width:160px}
    .ckc-giftcard-amount{font-family:'Hedvig Letters Serif',serif;font-size:26px;color:#1d2a23;margin-bottom:12px}
    .ckc-giftcard-redeem{background:#f4eee2;border-radius:14px;padding:24px}
    .ckc-giftcard-redeem-row{display:flex;gap:10px;flex-wrap:wrap;margin:14px 0}
    .ckc-giftcard-redeem-row input{flex:1;min-width:220px;padding:12px 14px;border-radius:8px;border:1px solid #d8cdb8}
    #ckc-giftcard-msg{color:#1d2a23;font-size:14px}
    .ckc-refer-link-box{background:#f4eee2;border-radius:14px;padding:20px;margin-bottom:20px}
    .ckc-refer-link-row{display:flex;gap:10px;flex-wrap:wrap;margin-top:10px}
    .ckc-refer-link-row input{flex:1;min-width:220px;padding:12px 14px;border-radius:8px;border:1px solid #d8cdb8;background:#fff}
    .ckc-partner-section{background:#1d2a23;border-radius:20px;padding:44px 36px;max-width:900px}
    .ckc-benefit-head--dark h2{color:#e4d7c5}
    .ckc-partner-section .ckc-benefit-sub{color:#bfb4a2}
    .ckc-benefit-list--dark{color:#bfb4a2}
    .ckc-benefit-btn--light{background:#e4d7c5;color:#1d2a23 !important}
    .ckc-benefit-btn--light:hover{background:#d8c8ac}
    .ckc-benefit-section--wide{max-width:1100px}
    .ckc-benefit-head--center{text-align:center;margin:0 auto 8px;max-width:760px}
    .ckc-benefit-head--center h2{font-size:34px}
    .ckc-benefit-sub--center{margin-left:auto;margin-right:auto;text-align:center;max-width:640px}
    .ckc-benefit-intro{color:#5a5a52;font-size:15.5px;text-align:center;max-width:600px;margin:0 auto 40px;font-style:italic}
    .ckc-step-grid{display:flex;flex-wrap:wrap;justify-content:center;gap:32px;margin-bottom:36px}
    .ckc-benefit-step{flex:1 1 200px;max-width:220px;text-align:center}
    .ckc-step-num{width:56px;height:56px;line-height:56px;border-radius:50%;background:#1d2a23;color:#e4d7c5;font-family:'Hedvig Letters Serif',serif;font-size:18px;margin:0 auto 14px}
    .ckc-step-title{font-weight:700;letter-spacing:.04em;color:#1d2a23;font-size:13.5px;text-transform:uppercase;margin-bottom:6px}
    .ckc-step-desc{color:#5a5a52;font-size:14.5px;line-height:1.6}
    .ckc-benefit-cta-wrap{text-align:center;margin-top:8px}
    .ckc-partner-section .ckc-step-num{background:#e4d7c5;color:#1d2a23}
    .ckc-partner-section .ckc-step-title{color:#e4d7c5}
    .ckc-partner-section .ckc-step-desc{color:#bfb4a2}
    .ckc-benefit-box{border-radius:20px;padding:44px 36px}
    .ckc-benefit-box--gold{background:#a78d54}
    .ckc-benefit-box--gold .ckc-benefit-head h2{color:#f4eee2}
    .ckc-benefit-box--gold .ckc-benefit-sub{color:#f4eee2}
    .ckc-benefit-box--gold .ckc-benefit-intro{color:#ece2cd}
    .ckc-benefit-box--gold .ckc-step-num{background:#f4eee2;color:#1d2a23}
    .ckc-benefit-box--gold .ckc-step-title{color:#f4eee2}
    .ckc-benefit-box--gold .ckc-step-desc{color:#ece2cd}
    .ckc-benefit-box--gold .ckc-benefit-list{color:#ece2cd}
    .ckc-benefit-box--gold .ckc-benefit-btn{background:#1d2a23;color:#f4eee2 !important}
    .ckc-benefit-box--gold .ckc-benefit-btn:hover{background:#2b3c31}
    .ckc-benefit-box--gold .ckc-giftcard-card,
    .ckc-benefit-box--gold .ckc-giftcard-redeem,
    .ckc-benefit-box--gold .ckc-refer-link-box{background:#f4eee2}
    .ckc-benefit-box--gold .ckc-giftcard-amount{color:#1d2a23}
    .ckc-step-grid--five{gap:20px}
    .ckc-step-grid--five .ckc-benefit-step{flex:1 1 160px;max-width:180px}
    .ckc-giftcard-grid{justify-content:center}
    </style>
    <?php
    return ob_get_clean();
}

add_shortcode( 'tck_gift_cards', 'ckc_shortcode_gift_cards' );
function ckc_shortcode_gift_cards() {
    $amounts = [ 25, 50, 100 ];
    ob_start();
    ?>
    <div class="ckc-benefit-section ckc-benefit-section--wide ckc-benefit-box ckc-benefit-box--gold ckc-giftcard-section" id="gift-cards">
      <div class="ckc-benefit-head ckc-benefit-head--center">
        <h2>Gift Cards & Benefit</h2>
        <p class="ckc-benefit-sub ckc-benefit-sub--center">Give someone the freedom to choose their favourites and enjoy extra value when you gift TCK.</p>
      </div>
      <p class="ckc-benefit-intro">Perfect for birthdays, celebrations, family, friends or simply sending someone a little something delicious.</p>
      <div class="ckc-step-grid">
        <?php foreach ( [ ['01','CHOOSE','Select the gift value you want.'], ['02','PERSONALISE','Add a message for your recipient.'], ['03','SEND','Send your gift digitally or purchase in-store.'], ['04','ENJOY','Receive 10% extra value when eligible (£50 Paid → £55 TCK Value).'] ] as $s ) : ?>
        <div class="ckc-benefit-step">
          <div class="ckc-step-num"><?php echo esc_html( $s[0] ); ?></div>
          <div class="ckc-step-title"><?php echo esc_html( $s[1] ); ?></div>
          <div class="ckc-step-desc"><?php echo esc_html( $s[2] ); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="ckc-giftcard-grid">
        <?php foreach ( $amounts as $amount ) :
            global $wpdb;
            $pid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '_sku' AND pm.meta_value = %s AND p.post_status = 'publish' LIMIT 1", 'tck-gift-card-' . $amount ) );
        ?>
        <div class="ckc-giftcard-card">
          <div class="ckc-giftcard-amount">£<?php echo esc_html( $amount ); ?></div>
          <?php if ( $pid ) : ?>
          <a class="ckc-benefit-btn" href="<?php echo esc_url( add_query_arg( 'add-to-cart', $pid, wc_get_cart_url() ) ); ?>">Buy a Gift Card</a>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="ckc-giftcard-redeem">
        <h3>Have a gift card code?</h3>
        <div class="ckc-giftcard-redeem-row">
          <input type="text" id="ckc-giftcard-code" placeholder="Enter code e.g. TCK-GIFT-XXXXXXXX" />
          <button type="button" id="ckc-giftcard-apply" class="ckc-benefit-btn">Apply to Basket</button>
        </div>
        <div id="ckc-giftcard-msg"></div>
      </div>
    </div>
    <script>
    (function(){
      var btn = document.getElementById('ckc-giftcard-apply');
      if(!btn) return;
      btn.addEventListener('click', function(){
        var code = document.getElementById('ckc-giftcard-code').value.trim();
        var msg = document.getElementById('ckc-giftcard-msg');
        if(!code){ msg.textContent = 'Please enter a code.'; return; }
        msg.textContent = 'Checking code...';
        var fd = new FormData();
        fd.append('action','ckc_redeem_giftcard');
        fd.append('nonce', ckc_ajax.nonce);
        fd.append('code', code);
        fetch(ckc_ajax.url, { method:'POST', body: fd, credentials:'same-origin' })
          .then(function(r){ return r.json(); })
          .then(function(res){
            if(res.success){
              msg.textContent = res.data.message;
              window.location.href = ckc_ajax.cart_url;
            } else {
              msg.textContent = res.data || 'That code could not be applied.';
            }
          })
          .catch(function(){ msg.textContent = 'Something went wrong, please try again.'; });
      });
    })();
    </script>
    <?php
    return ckc_benefit_styles_once() . ob_get_clean();
}

add_action( 'wp_ajax_ckc_redeem_giftcard', 'ckc_ajax_redeem_giftcard' );
add_action( 'wp_ajax_nopriv_ckc_redeem_giftcard', 'ckc_ajax_redeem_giftcard' );
function ckc_ajax_redeem_giftcard() {
    check_ajax_referer( 'ckc_nonce', 'nonce' );
    global $wpdb;
    $code  = sanitize_text_field( wp_unslash( $_POST['code'] ) );
    $table = $wpdb->prefix . 'ckc_gift_cards';
    $card  = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE code = %s", $code ) );
    if ( ! $card ) wp_send_json_error( 'We could not find that gift card code.' );
    if ( (float) $card->balance <= 0 ) wp_send_json_error( 'This gift card has no remaining balance.' );
    if ( ! WC()->session ) wp_send_json_error( 'Please try again.' );
    WC()->session->set( 'ckc_giftcard_code', $code );
    wp_send_json_success( [ 'message' => 'Gift card applied! Remaining balance: £' . number_format( (float) $card->balance, 2 ) ] );
}

add_action( 'woocommerce_cart_calculate_fees', 'ckc_apply_giftcard_discount' );
function ckc_apply_giftcard_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    if ( ! WC()->session ) return;
    $code = WC()->session->get( 'ckc_giftcard_code' );
    if ( ! $code ) return;
    global $wpdb;
    $table = $wpdb->prefix . 'ckc_gift_cards';
    $card = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE code = %s", $code ) );
    if ( ! $card || (float) $card->balance <= 0 ) return;
    $discount = min( (float) $card->balance, $cart->get_subtotal() );
    if ( $discount > 0 ) {
        $cart->add_fee( 'Gift Card (' . $code . ')', -$discount );
    }
}

add_action( 'woocommerce_order_status_completed', 'ckc_handle_giftcard_order' );
add_action( 'woocommerce_order_status_processing', 'ckc_handle_giftcard_order' );
function ckc_handle_giftcard_order( $order_id ) {
    if ( get_post_meta( $order_id, '_ckc_giftcards_processed', true ) ) return;
    $order = wc_get_order( $order_id );
    if ( ! $order ) return;
    global $wpdb;
    $table = $wpdb->prefix . 'ckc_gift_cards';

    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        if ( ! $product ) continue;
        $amount = get_post_meta( $product->get_id(), 'ckc_gift_card_amount', true );
        if ( ! $amount ) continue;
        for ( $i = 0; $i < $item->get_quantity(); $i++ ) {
            $code = 'TCK-GIFT-' . strtoupper( wp_generate_password( 8, false, false ) );
            $bonus_balance = round( $amount * 1.1, 2 ); // 10% extra TCK value on top of what was paid.
            $wpdb->insert( $table, [
                'code'            => $code,
                'initial_amount'  => $amount,
                'balance'         => $bonus_balance,
                'buyer_user_id'   => $order->get_customer_id(),
                'recipient_email' => $order->get_billing_email(),
                'order_id'        => $order_id,
            ], [ '%s', '%f', '%f', '%d', '%s', '%d' ] );
            wp_mail( $order->get_billing_email(), 'Your TCK Gift Card', 'Your TCK Digital Gift Card code is: ' . $code . "
You paid: £" . number_format( $amount, 2 ) . "
TCK Value (incl. 10% bonus): £" . number_format( $bonus_balance, 2 ) . "
Redeem it at checkout on thechilledkitchen.co.uk." );
        }
    }

    $code = WC()->session ? WC()->session->get( 'ckc_giftcard_code' ) : null;
    if ( $code ) {
        $card = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE code = %s", $code ) );
        if ( $card ) {
            $used = 0;
            foreach ( $order->get_fees() as $fee ) {
                if ( strpos( $fee->get_name(), $code ) !== false ) {
                    $used = abs( (float) $fee->get_total() );
                }
            }
            if ( $used > 0 ) {
                $new_balance = max( 0, (float) $card->balance - $used );
                $wpdb->update( $table, [ 'balance' => $new_balance ], [ 'code' => $code ] );
            }
        }
        if ( WC()->session ) WC()->session->__unset( 'ckc_giftcard_code' );
    }

    update_post_meta( $order_id, '_ckc_giftcards_processed', 1 );
}

// ====================================================================
// 7. REFER A FRIEND
// ====================================================================

function ckc_get_referral_code( $user_id ) {
    $code = get_user_meta( $user_id, 'ckc_referral_code', true );
    if ( ! $code ) {
        $code = 'FRIEND' . str_pad( (string) $user_id, 4, '0', STR_PAD_LEFT );
        update_user_meta( $user_id, 'ckc_referral_code', $code );
    }
    return $code;
}

add_action( 'template_redirect', function () {
    if ( ! empty( $_GET['ref'] ) && ! is_admin() ) {
        $ref = sanitize_text_field( wp_unslash( $_GET['ref'] ) );
        setcookie( 'ckc_ref', $ref, time() + 30 * DAY_IN_SECONDS, '/' );
    }
} );

add_action( 'user_register', function ( $user_id ) {
    if ( ! empty( $_COOKIE['ckc_ref'] ) ) {
        $ref_code = sanitize_text_field( wp_unslash( $_COOKIE['ckc_ref'] ) );
        $users = get_users( [ 'meta_key' => 'ckc_referral_code', 'meta_value' => $ref_code, 'number' => 1, 'fields' => 'ID' ] );
        if ( ! empty( $users ) && (int) $users[0] !== (int) $user_id ) {
            update_user_meta( $user_id, 'ckc_referred_by', (int) $users[0] );
            update_user_meta( $user_id, 'ckc_ref_welcome_available', 10 );
        }
    }
} );

add_action( 'woocommerce_cart_calculate_fees', 'ckc_apply_referral_discount' );
function ckc_apply_referral_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    if ( ! is_user_logged_in() ) return;
    $user_id = get_current_user_id();

    $welcome_pct = (int) get_user_meta( $user_id, 'ckc_ref_welcome_available', true );
    if ( $welcome_pct > 0 && ! get_user_meta( $user_id, 'ckc_ref_welcome_used', true ) && ! ckc_user_is_first_order_eligible( $user_id ) ) {
        $discount = round( $cart->get_subtotal() * ( $welcome_pct / 100 ), 2 );
        if ( $discount > 0 ) $cart->add_fee( 'Referral Welcome (' . $welcome_pct . '% off)', -$discount );
        return;
    }

    $reward_pct = (int) get_user_meta( $user_id, 'ckc_ref_reward_available', true );
    if ( $reward_pct > 0 && ! get_user_meta( $user_id, 'ckc_ref_reward_used', true ) ) {
        $discount = round( $cart->get_subtotal() * ( $reward_pct / 100 ), 2 );
        if ( $discount > 0 ) $cart->add_fee( 'Referral Reward (' . $reward_pct . '% off)', -$discount );
    }
}

add_action( 'woocommerce_order_status_completed', 'ckc_handle_referral_reward' );
function ckc_handle_referral_reward( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( ! $order ) return;
    $user_id = $order->get_customer_id();
    if ( ! $user_id ) return;

    $used_welcome = false;
    $used_reward  = false;
    foreach ( $order->get_fees() as $fee ) {
        if ( strpos( $fee->get_name(), 'Referral Welcome' ) !== false ) $used_welcome = true;
        if ( strpos( $fee->get_name(), 'First Order Welcome' ) !== false && (int) get_user_meta( $user_id, 'ckc_ref_welcome_available', true ) > 0 ) $used_welcome = true;
        if ( strpos( $fee->get_name(), 'Referral Reward' ) !== false )  $used_reward  = true;
    }

    if ( $used_welcome ) {
        update_user_meta( $user_id, 'ckc_ref_welcome_used', 1 );
        $referrer_id = get_user_meta( $user_id, 'ckc_referred_by', true );
        if ( $referrer_id && ! get_user_meta( (int) $referrer_id, 'ckc_ref_reward_available', true ) ) {
            update_user_meta( (int) $referrer_id, 'ckc_ref_reward_available', 10 );
        }
    }

    if ( $used_reward ) {
        update_user_meta( $user_id, 'ckc_ref_reward_used', 1 );
    }
}

add_shortcode( 'tck_refer_friend', 'ckc_shortcode_refer_friend' );
function ckc_shortcode_refer_friend() {
    $account_url = function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'myaccount' ) : home_url( '/my-account/' );
    $link = '';
    if ( is_user_logged_in() ) {
        $uid  = get_current_user_id();
        $code = ckc_get_referral_code( $uid );
        $link = add_query_arg( 'ref', $code, home_url( '/' ) );
    }
    $steps = [
        [ '01', 'SHARE', 'Send your unique referral code to a friend.' ],
        [ '02', 'THEY JOIN', 'Your friend uses your code when ordering.' ],
        [ '03', 'THEY SAVE', 'They receive 10% off their first order.' ],
        [ '04', 'YOU SAVE', 'You receive 10% off your next order.' ],
    ];
    ob_start();
    ?>
    <div class="ckc-benefit-section ckc-benefit-section--wide ckc-benefit-box ckc-benefit-box--gold ckc-refer-section" id="refer-a-friend">
      <div class="ckc-benefit-head ckc-benefit-head--center">
        <h2>Refer a Friend & Benefit</h2>
        <p class="ckc-benefit-sub ckc-benefit-sub--center">Share the food you love and you both get rewarded.</p>
      </div>
      <p class="ckc-benefit-intro">Give your friend 10% off their first order, then receive 10% off your next order when they join TCK.</p>
      <div class="ckc-step-grid">
        <?php foreach ( $steps as $s ) : ?>
        <div class="ckc-benefit-step">
          <div class="ckc-step-num"><?php echo esc_html( $s[0] ); ?></div>
          <div class="ckc-step-title"><?php echo esc_html( $s[1] ); ?></div>
          <div class="ckc-step-desc"><?php echo esc_html( $s[2] ); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php if ( is_user_logged_in() ) : ?>
      <div class="ckc-refer-link-box">
        <label for="ckc-refer-link">Your referral link</label>
        <div class="ckc-refer-link-row">
          <input type="text" id="ckc-refer-link" readonly value="<?php echo esc_url( $link ); ?>" />
          <button type="button" id="ckc-refer-copy" class="ckc-benefit-btn">Copy Link</button>
        </div>
      </div>
      <script>
      (function(){
        var btn = document.getElementById('ckc-refer-copy');
        if(!btn) return;
        btn.addEventListener('click', function(){
          var input = document.getElementById('ckc-refer-link');
          input.select();
          input.setSelectionRange(0, 99999);
          if (navigator.clipboard) { navigator.clipboard.writeText(input.value); }
          btn.textContent = 'Copied!';
          setTimeout(function(){ btn.textContent = 'Copy Link'; }, 2000);
        });
      })();
      </script>
      <?php else : ?>
      <div class="ckc-benefit-cta-wrap">
        <a href="<?php echo esc_url( $account_url ); ?>" class="ckc-benefit-btn">Refer a Friend</a>
      </div>
      <?php endif; ?>
    </div>
    <?php
    return ckc_benefit_styles_once() . ob_get_clean();
}

// 8. REGISTER & EARN, COMMUNITY BUY, PARTNER WITH US (content sections)
// ====================================================================

add_shortcode( 'tck_register_earn', 'ckc_shortcode_register_earn' );
function ckc_shortcode_register_earn() {
    $account_url = function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'myaccount' ) : home_url( '/my-account/' );
    $steps = [
        [ '01', '50% OFF', 'Get 50% off your first order.' ],
        [ '02', 'MEMBER ACCESS', 'Discover new products before everyone else.' ],
        [ '03', 'EXCLUSIVE PERKS', 'Enjoy birthday rewards and members-only offers.' ],
        [ '04', 'EARN REWARDS', 'Earn points every time you spend. Higher spending unlocks higher earning rates. £1 spent = 1 point. 100 points = £1 off.' ],
    ];
    ob_start();
    ?>
    <div class="ckc-benefit-section ckc-benefit-section--wide ckc-benefit-box ckc-benefit-box--gold ckc-register-section" id="register-earn">
      <div class="ckc-benefit-head ckc-benefit-head--center">
        <h2>Register & Benefit</h2>
        <p class="ckc-benefit-sub ckc-benefit-sub--center">Join our TCK family and enjoy exclusive savings, rewards and member benefits from your very first order.</p>
      </div>
      <p class="ckc-benefit-intro">Shop whenever you like as a guest, or join TCK Rewards and get more from every order.</p>
      <div class="ckc-step-grid">
        <?php foreach ( $steps as $s ) : ?>
        <div class="ckc-benefit-step">
          <div class="ckc-step-num"><?php echo esc_html( $s[0] ); ?></div>
          <div class="ckc-step-title"><?php echo esc_html( $s[1] ); ?></div>
          <div class="ckc-step-desc"><?php echo esc_html( $s[2] ); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="ckc-benefit-cta-wrap">
        <a href="<?php echo esc_url( $account_url ); ?>" class="ckc-benefit-btn">Register & Earn</a>
      </div>
    </div>
    <?php
    return ckc_benefit_styles_once() . ob_get_clean();
}

add_shortcode( 'tck_subscribe_benefit', 'ckc_shortcode_subscribe_benefit' );
function ckc_shortcode_subscribe_benefit() {
    $menu_url = home_url( '/menu/' );
    $steps = [
        [ '01', 'CHOOSE', 'Select your favourite meals and products.' ],
        [ '02', 'TELL US', 'Add a note at checkout with your preferred delivery frequency.' ],
        [ '03', 'SAVE', 'Enjoy 10% off your subsequent subscription orders.' ],
        [ '04', 'RELAX', 'Skip, pause or cancel whenever you need simply by contacting us.' ],
        [ '05', 'FREE DELIVERY', 'Get free delivery on orders over £50 or free click and collect.' ],
    ];
    ob_start();
    ?>
    <div class="ckc-benefit-section ckc-benefit-section--wide ckc-benefit-box ckc-benefit-box--gold ckc-subscribe-section" id="subscribe-benefit">
      <div class="ckc-benefit-head ckc-benefit-head--center">
        <h2>Subscribe & Benefit</h2>
        <p class="ckc-benefit-sub ckc-benefit-sub--center">Make your favourite TCK meals part of your routine and save every time they arrive.</p>
      </div>
      <p class="ckc-benefit-intro">Choose your meals, choose your schedule and let TCK take care of the rest.</p>
      <div class="ckc-step-grid ckc-step-grid--five">
        <?php foreach ( $steps as $s ) : ?>
        <div class="ckc-benefit-step">
          <div class="ckc-step-num"><?php echo esc_html( $s[0] ); ?></div>
          <div class="ckc-step-title"><?php echo esc_html( $s[1] ); ?></div>
          <div class="ckc-step-desc"><?php echo esc_html( $s[2] ); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="ckc-benefit-cta-wrap">
        <a href="<?php echo esc_url( $menu_url ); ?>" class="ckc-benefit-btn">Build Your Subscription</a>
      </div>
    </div>
    <?php
    return ckc_benefit_styles_once() . ob_get_clean();
}

add_shortcode( 'tck_community_buy', 'ckc_shortcode_community_buy' );
function ckc_shortcode_community_buy() {
    $contact_url = home_url( '/contact/' );
    $steps = [
        [ '01', 'TELL US', 'Share what you need and how much.' ],
        [ '02', 'BUILD', "We'll recommend products for your group." ],
        [ '03', 'SAVE', 'Receive a tailored volume-based quotation.' ],
        [ '04', 'COLLECT OR DELIVER', 'Choose the most convenient option.' ],
    ];
    ob_start();
    ?>
    <div class="ckc-benefit-section ckc-benefit-section--wide ckc-benefit-box ckc-benefit-box--gold ckc-community-section" id="community-buy">
      <div class="ckc-benefit-head ckc-benefit-head--center">
        <h2>Community Buy & Benefit</h2>
        <p class="ckc-benefit-sub ckc-benefit-sub--center">Buying more? Bring your group together and unlock better value with a tailored TCK order.</p>
      </div>
      <p class="ckc-benefit-intro">From family gatherings to community groups and workplace orders, we'll build a package around what you need.</p>
      <div class="ckc-step-grid">
        <?php foreach ( $steps as $s ) : ?>
        <div class="ckc-benefit-step">
          <div class="ckc-step-num"><?php echo esc_html( $s[0] ); ?></div>
          <div class="ckc-step-title"><?php echo esc_html( $s[1] ); ?></div>
          <div class="ckc-step-desc"><?php echo esc_html( $s[2] ); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="ckc-benefit-cta-wrap">
        <a href="<?php echo esc_url( $contact_url ); ?>" class="ckc-benefit-btn">Request a Community Quote</a>
      </div>
    </div>
    <?php
    return ckc_benefit_styles_once() . ob_get_clean();
}

add_shortcode( 'tck_partner_with_us', 'ckc_shortcode_partner_with_us' );
function ckc_shortcode_partner_with_us() {
    $steps = [
        [ '01', 'STOCK TCK', 'Add authentic South Asian food to your range.' ],
        [ '02', 'GET SUPPORT', 'Access commercial and merchandising support.' ],
        [ '03', 'REDUCE SET-UP', 'Freezer solutions available for selected partners.' ],
        [ '04', 'GROW TOGETHER', 'Build a mutually beneficial revenue partnership.' ],
    ];
    ob_start();
    ?>
    <div class="ckc-benefit-section ckc-benefit-section--wide ckc-partner-section" id="partner-with-us">
      <div class="ckc-benefit-head ckc-benefit-head--dark ckc-benefit-head--center">
        <h2>Partner With Us</h2>
        <p class="ckc-benefit-sub ckc-benefit-sub--center">Bring authentic TCK food to your customers and build a new revenue opportunity for your business.</p>
      </div>
      <p class="ckc-benefit-intro" style="color:#bfb4a2">We work with selected retailers and food businesses to bring TCK products to more customers through carefully managed stockist partnerships.</p>
      <div class="ckc-step-grid">
        <?php foreach ( $steps as $s ) : ?>
        <div class="ckc-benefit-step">
          <div class="ckc-step-num"><?php echo esc_html( $s[0] ); ?></div>
          <div class="ckc-step-title"><?php echo esc_html( $s[1] ); ?></div>
          <div class="ckc-step-desc"><?php echo esc_html( $s[2] ); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="ckc-benefit-cta-wrap">
        <a href="<?php echo esc_url( home_url( '/contact/' ) ); ?>" class="ckc-benefit-btn ckc-benefit-btn--light">Become a Stockist</a>
      </div>
    </div>
    <?php
    return ckc_benefit_styles_once() . ob_get_clean();
}





// ====================================================================
// 9. MY ACCOUNT — BRANDED STYLING
// ====================================================================

add_action( 'wp_head', 'ckc_my_account_styles' );
function ckc_my_account_styles() {
    if ( ! function_exists( 'is_account_page' ) || ! is_account_page() ) return;
    ?>
    <style>
    body.woocommerce-account .woocommerce {
        max-width: 1100px;
        margin: 60px auto;
        padding: 0 20px;
        display: flex;
        flex-wrap: wrap;
        gap: 40px;
        align-items: flex-start;
    }
    body.woocommerce-account .woocommerce-MyAccount-navigation {
        flex: 0 0 240px;
        background: #f4eee2;
        border-radius: 16px;
        padding: 24px 0;
    }
    body.woocommerce-account .woocommerce-MyAccount-navigation ul { list-style: none; margin: 0; padding: 0; }
    body.woocommerce-account .woocommerce-MyAccount-navigation li { margin: 0; }
    body.woocommerce-account .woocommerce-MyAccount-navigation li a {
        display: block;
        padding: 12px 24px;
        color: #1d2a23;
        text-decoration: none;
        font-weight: 600;
        font-size: 14.5px;
        letter-spacing: .01em;
        border-left: 3px solid transparent;
    }
    body.woocommerce-account .woocommerce-MyAccount-navigation li a:hover { background: #ece2cd; }
    body.woocommerce-account .woocommerce-MyAccount-navigation li.is-active a {
        border-left-color: #1d2a23;
        background: #ece2cd;
    }
    body.woocommerce-account .woocommerce-MyAccount-navigation li.woocommerce-MyAccount-navigation-link--customer-logout a {
        color: #a33;
    }
    body.woocommerce-account .woocommerce-MyAccount-content {
        flex: 1 1 500px;
        background: #fff;
        border-radius: 16px;
        padding: 36px;
        box-shadow: 0 1px 4px rgba(0,0,0,.05);
    }
    body.woocommerce-account .woocommerce-MyAccount-content h2,
    body.woocommerce-account .woocommerce-MyAccount-content h3 {
        font-family: 'Hedvig Letters Serif', serif;
        font-weight: 400;
        color: #1d2a23;
    }
    body.woocommerce-account .woocommerce-MyAccount-content mark { background: none; color: #1d2a23; font-weight: 700; }
    body.woocommerce-account .woocommerce-MyAccount-content table.shop_table {
        border-collapse: collapse;
        width: 100%;
        margin: 20px 0;
    }
    body.woocommerce-account .woocommerce-MyAccount-content table.shop_table th {
        background: #1d2a23;
        color: #f4eee2;
        text-align: left;
        padding: 12px 14px;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: .04em;
    }
    body.woocommerce-account .woocommerce-MyAccount-content table.shop_table td {
        padding: 12px 14px;
        border-bottom: 1px solid #ece2cd;
    }
    body.woocommerce-account .woocommerce-MyAccount-content .button,
    body.woocommerce-account .woocommerce-MyAccount-content input[type="submit"] {
        display: inline-block;
        background: #1d2a23 !important;
        color: #f4eee2 !important;
        padding: 12px 26px;
        border-radius: 30px;
        text-decoration: none;
        font-weight: 600;
        border: none;
        cursor: pointer;
    }
    body.woocommerce-account .woocommerce-MyAccount-content .button:hover,
    body.woocommerce-account .woocommerce-MyAccount-content input[type="submit"]:hover { background: #2b3c31 !important; }
    body.woocommerce-account .woocommerce-MyAccount-content .woocommerce-Address-title { display:flex; align-items:center; justify-content:space-between; }
    body.woocommerce-account .woocommerce-MyAccount-content .woocommerce-Addresses { display:flex; gap:24px; flex-wrap:wrap; }
    body.woocommerce-account .woocommerce-MyAccount-content .woocommerce-Address { flex:1 1 260px; background:#f4eee2; border-radius:12px; padding:20px; }
    body.woocommerce-account .woocommerce-MyAccount-content input[type="text"],
    body.woocommerce-account .woocommerce-MyAccount-content input[type="email"],
    body.woocommerce-account .woocommerce-MyAccount-content input[type="password"],
    body.woocommerce-account .woocommerce-MyAccount-content input[type="tel"],
    body.woocommerce-account .woocommerce-MyAccount-content select {
        border: 1px solid #d8cdb8;
        border-radius: 8px;
        padding: 10px 12px;
        width: 100%;
    }
    @media (max-width: 768px) {
        body.woocommerce-account .woocommerce { flex-direction: column; }
        body.woocommerce-account .woocommerce-MyAccount-navigation { width: 100%; }
    }
    </style>
    <?php
}

// ============================================================
// FIRST ORDER WELCOME: 50% off a registered customer's first order
// ============================================================
if ( ! defined( 'CKC_FIRST_ORDER_PCT' ) ) define( 'CKC_FIRST_ORDER_PCT', 50 );

function ckc_user_is_first_order_eligible( $user_id ) {
    if ( ! $user_id ) return false;
    $prior = wc_get_orders( [
        'customer_id' => $user_id,
        'status'      => [ 'wc-processing', 'wc-completed', 'wc-on-hold', 'wc-refunded' ],
        'limit'       => 1,
        'return'      => 'ids',
    ] );
    return empty( $prior );
}

add_action( 'woocommerce_cart_calculate_fees', 'ckc_apply_first_order_discount', 5 );
function ckc_apply_first_order_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    if ( ! is_user_logged_in() ) return;
    if ( ! ckc_user_is_first_order_eligible( get_current_user_id() ) ) return;

    $base = 0;
    foreach ( $cart->get_cart() as $item ) {
        $product = $item['data'];
        if ( $product && strpos( (string) $product->get_sku(), 'tck-gift-card' ) === 0 ) continue;
        $base += (float) $item['line_subtotal'];
    }
    $discount = round( $base * ( CKC_FIRST_ORDER_PCT / 100 ), 2 );
    if ( $discount > 0 ) $cart->add_fee( 'First Order Welcome (' . CKC_FIRST_ORDER_PCT . '% off)', -$discount );
}
