<?php
/**
 * GT BOGO Engine — Free Core Rule (Enterprise)
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) return;

$is_pro  = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;
$message = ''; $message_type = '';
$version = defined('GT_BOGO_VERSION') ? GT_BOGO_VERSION : '3.11.0';

// ── Save Free Rule ────────────────────────────────────────────────────────
if (isset($_POST['gtbogo_save_free_rule']) && check_admin_referer('gtbogo_free_rule')) {
    $data = [
        'enabled'          => isset($_POST['free_enabled']),
        'buy_quantity'     => max(1, intval($_POST['buy_qty']      ?? 1)),
        'get_quantity'     => max(1, intval($_POST['get_qty']      ?? 1)),
        'discount_type'    => sanitize_text_field($_POST['discount_type'] ?? 'percentage'),
        'discount_value'   => floatval($_POST['discount_value']    ?? 100),
        'apply_to'         => sanitize_text_field($_POST['apply_to']      ?? 'cheapest'),
        'min_cart_total'   => floatval($_POST['min_cart_total']    ?? 0),
        'max_uses_per_cart'=> intval($_POST['max_uses_per_cart']   ?? 1),
        'title'            => sanitize_text_field($_POST['rule_title']     ?? 'Buy One Get One'),
        'description'      => sanitize_textarea_field($_POST['rule_desc'] ?? ''),
        'exclude_sale'     => isset($_POST['exclude_sale']),
        'show_badge'       => isset($_POST['show_badge']),
        'badge_text'       => sanitize_text_field($_POST['badge_text']    ?? 'Deal'),
        'notify_cart'      => isset($_POST['notify_cart']),
        'cart_message'     => sanitize_text_field($_POST['cart_message']  ?? ''),
        'updated'          => current_time('mysql'),
    ];
    update_option('gtbogo_free_rule', $data);
    if (function_exists('gt_bogo_log')) gt_bogo_log('Free rule updated', ($data['enabled']?'Enabled':'Disabled').
        ' — Buy '.$data['buy_quantity'].' Get '.$data['get_quantity'].' '.$data['discount_value'].'%', 'success');
    delete_transient('gtbogo_active_rules');
    $message = 'Free rule saved.'; $message_type = 'success';
}

$r = get_option('gtbogo_free_rule', [
    'enabled'=>false,'buy_quantity'=>1,'get_quantity'=>1,'discount_type'=>'percentage',
    'discount_value'=>100,'apply_to'=>'cheapest','min_cart_total'=>0,'max_uses_per_cart'=>1,
    'title'=>'Buy One Get One','description'=>'','exclude_sale'=>false,'show_badge'=>false,
    'badge_text'=>'Deal','notify_cart'=>true,'cart_message'=>'Add another item to claim your free product.',
]);

// Stats from analytics
global $wpdb;
$atbl  = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_analytics'));
$stats = null;
if ($atbl) {
    $stats = $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue,
                COALESCE(SUM(discount_amount),0) AS discounts, COALESCE(AVG(order_total),0) AS aov
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s AND rule_name=%s",
        date('Y-m-d H:i:s', strtotime('-30 days')), $r['title']
    ), ARRAY_A);
}

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🎁 Free Core Rule</h1>
        <p class="gt-page-subtitle">Your always-available BOGO rule — no PRO license required. Full configuration, cart messaging, and badge control.</p>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <span class="gt-badge <?php echo !empty($r['enabled'])?'gt-badge-active':'gt-badge-free'; ?>">
            <?php echo !empty($r['enabled'])?'● Rule Active':'○ Rule Inactive'; ?>
        </span>
        <span class="gt-badge gt-badge-free">Free — v<?php echo esc_html($version); ?></span>
    </div>
</div>
<?php if ($message): ?><div class="gt-notice gt-notice-<?php echo esc_attr($message_type); ?> gt-animate-in">✓ <?php echo esc_html($message); ?></div><?php endif; ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
    <div class="gt-metric" style="--gt-metric-c:#e10000">
        <span class="gt-metric-icon">🎁</span>
        <div class="gt-metric-label">Rule Status</div>
        <div class="gt-metric-value" style="font-size:16px"><?php echo !empty($r['enabled'])?'Active':'Inactive'; ?></div>
        <div class="gt-metric-trend">Buy <?php echo $r['buy_quantity']; ?> Get <?php echo $r['get_quantity']; ?> — <?php echo $r['discount_value']; ?>% off</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#22c55e">
        <span class="gt-metric-icon">🛒</span>
        <div class="gt-metric-label">Orders (30d)</div>
        <div class="gt-metric-value"><?php echo number_format($stats['orders']??0); ?></div>
        <div class="gt-metric-trend">BOGO orders this month</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#3b82f6">
        <span class="gt-metric-icon">💰</span>
        <div class="gt-metric-label">Revenue (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo number_format($stats['revenue']??0,0); ?></div>
        <div class="gt-metric-trend">Influenced by this rule</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#f59e0b">
        <span class="gt-metric-icon">🏷️</span>
        <div class="gt-metric-label">Discounts (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo number_format($stats['discounts']??0,0); ?></div>
        <div class="gt-metric-trend">Total discount given</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#8b5cf6">
        <span class="gt-metric-icon">💵</span>
        <div class="gt-metric-label">Avg Order Value (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo number_format($stats['aov']??0,2); ?></div>
        <div class="gt-metric-trend">BOGO-influenced orders</div>
    </div>
</div>

<form method="post" action="">
<?php wp_nonce_field('gtbogo_free_rule'); ?>

<!-- RULE STATUS + IDENTITY -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">⚙️ Rule Configuration</h2></div>

    <div class="gt-setting-row">
        <div>
            <div class="gt-setting-label" style="font-size:16px">Enable Free Core Rule</div>
            <div class="gt-setting-desc">When enabled, this BOGO rule is active on your store immediately. No PRO license required.</div>
        </div>
        <label class="gt-toggle"><input type="checkbox" name="free_enabled" value="1" <?php checked(!empty($r['enabled'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:4px">
        <div class="gt-form-group">
            <label class="gt-form-label">Rule Display Name</label>
            <input type="text" name="rule_title" class="gt-input" value="<?php echo esc_attr($r['title']); ?>" placeholder="Buy One Get One">
            <div class="gt-form-hint">Shown in cart messages, deal page, and analytics</div>
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Rule Description (optional)</label>
            <input type="text" name="rule_desc" class="gt-input" value="<?php echo esc_attr($r['description']); ?>" placeholder="Add two items to claim a complimentary product">
            <div class="gt-form-hint">Used on the deal page if enabled</div>
        </div>
    </div>
</div>

<!-- DEAL STRUCTURE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🎯 Deal Structure</h2></div>

    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:20px">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Buy Quantity</label>
            <input type="number" name="buy_qty" class="gt-input" value="<?php echo esc_attr($r['buy_quantity']); ?>" min="1" max="99">
            <div class="gt-form-hint">Items customer must add</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Get Quantity</label>
            <input type="number" name="get_qty" class="gt-input" value="<?php echo esc_attr($r['get_quantity']); ?>" min="1" max="99">
            <div class="gt-form-hint">Items discounted or free</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Discount Type</label>
            <select name="discount_type" class="gt-select">
                <option value="percentage" <?php selected($r['discount_type'],'percentage'); ?>>Percentage Off</option>
                <option value="fixed"      <?php selected($r['discount_type'],'fixed'); ?>>Fixed Amount Off</option>
            </select>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Discount Value</label>
            <input type="number" name="discount_value" class="gt-input" value="<?php echo esc_attr($r['discount_value']); ?>" min="1" max="100" step="0.01">
            <div class="gt-form-hint">100 = fully free</div>
        </div>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px">
        <div class="gt-form-group">
            <label class="gt-form-label">Apply Discount To</label>
            <select name="apply_to" class="gt-select">
                <option value="cheapest"   <?php selected($r['apply_to'],'cheapest'); ?>>Cheapest eligible item</option>
                <option value="cheapest_n" <?php selected($r['apply_to'],'cheapest_n'); ?>>N cheapest items</option>
                <option value="most_exp"   <?php selected($r['apply_to'],'most_exp'); ?>>Most expensive item</option>
                <option value="specific"   <?php selected($r['apply_to'],'specific'); ?>>Specific product (PRO)</option>
            </select>
            <div class="gt-form-hint">Which cart item receives the discount</div>
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Minimum Cart Total ($)</label>
            <input type="number" name="min_cart_total" class="gt-input" value="<?php echo esc_attr($r['min_cart_total']); ?>" min="0" step="0.01" placeholder="0.00">
            <div class="gt-form-hint">Cart subtotal before this rule fires. 0 = no minimum.</div>
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Max Uses Per Cart</label>
            <input type="number" name="max_uses_per_cart" class="gt-input" value="<?php echo esc_attr($r['max_uses_per_cart']); ?>" min="1" max="99">
            <div class="gt-form-hint">How many times the deal can stack in a single order</div>
        </div>
    </div>

    <div class="gt-setting-row" style="border:none;padding-top:4px">
        <div><div class="gt-setting-label">Exclude Sale-Priced Items</div><div class="gt-setting-desc">Do not apply the BOGO discount to items already on sale. Prevents double-discounting and protects margin.</div></div>
        <label class="gt-toggle"><input type="checkbox" name="exclude_sale" value="1" <?php checked(!empty($r['exclude_sale'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
</div>

<!-- DEAL STRUCTURE PREVIEW -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">👁 Deal Preview</h2><span class="gt-text-soft gt-text-sm">Updates as you type</span></div>
    <div id="deal-preview" style="padding:20px;background:rgba(225,0,0,0.04);border-radius:10px;border:1px solid rgba(225,0,0,0.15);text-align:center">
        <div id="preview-headline" style="font-size:22px;font-weight:800;color:var(--gt-white);margin-bottom:8px">Buy 1 Get 1 — 100% Off</div>
        <div id="preview-sub" style="font-size:13px;color:var(--gt-soft)">Cheapest eligible item receives the discount. Minimum cart: none.</div>
    </div>
    <script>
    function updatePreview() {
        var buy  = document.querySelector('[name=buy_qty]').value;
        var get  = document.querySelector('[name=get_qty]').value;
        var val  = document.querySelector('[name=discount_value]').value;
        var type = document.querySelector('[name=discount_type]').value;
        var to   = document.querySelector('[name=apply_to]').value;
        var min  = document.querySelector('[name=min_cart_total]').value;
        var suffix = type==='percentage' ? '%' : ' off';
        var toLabel = {cheapest:'Cheapest item',cheapest_n:'N cheapest items',most_exp:'Most expensive item',specific:'Specific product'}[to]||to;
        document.getElementById('preview-headline').textContent = 'Buy ' + buy + ' Get ' + get + ' — ' + val + suffix;
        document.getElementById('preview-sub').textContent = toLabel + ' receives the discount.' + (min>0?' Minimum cart: $'+parseFloat(min).toFixed(2)+'.':' No minimum cart required.');
    }
    document.querySelectorAll('[name=buy_qty],[name=get_qty],[name=discount_value],[name=discount_type],[name=apply_to],[name=min_cart_total]').forEach(el=>el.addEventListener('input',updatePreview));
    document.querySelectorAll('[name=discount_type],[name=apply_to]').forEach(el=>el.addEventListener('change',updatePreview));
    updatePreview();
    </script>
</div>

<!-- CART MESSAGING -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">💬 Cart Notification</h2></div>

    <div class="gt-setting-row">
        <div><div class="gt-setting-label">Show Cart Progress Message</div><div class="gt-setting-desc">Display a message in the cart when the customer is close to qualifying. Encourages customers to add another item.</div></div>
        <label class="gt-toggle"><input type="checkbox" name="notify_cart" value="1" <?php checked(!empty($r['notify_cart'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-form-group" style="margin-top:12px">
        <label class="gt-form-label">Cart Message</label>
        <input type="text" name="cart_message" class="gt-input" value="<?php echo esc_attr($r['cart_message']); ?>" placeholder="Add another item to claim your complimentary product.">
        <div class="gt-form-hint">Shown above the cart when the customer has not yet qualified. Keep under 100 characters. Use neutral language — no exclamation marks.</div>
    </div>
</div>

<!-- PRODUCT BADGE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🏷️ Product Badge</h2></div>
    <div class="gt-setting-row">
        <div><div class="gt-setting-label">Show Badge on Eligible Products</div><div class="gt-setting-desc">Display a small badge on product images for items that can trigger this BOGO rule. Inherits your theme styling.</div></div>
        <label class="gt-toggle"><input type="checkbox" name="show_badge" value="1" <?php checked(!empty($r['show_badge'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-form-group" style="margin-top:12px">
        <label class="gt-form-label">Badge Text</label>
        <input type="text" name="badge_text" class="gt-input" style="max-width:200px" value="<?php echo esc_attr($r['badge_text']); ?>" placeholder="Deal" maxlength="16">
        <div class="gt-form-hint">Short label on the product badge. Keep under 12 characters.</div>
    </div>
</div>

<!-- PRO UPGRADE CTA -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(225,0,0,0.06),rgba(7,12,28,0));border-color:rgba(225,0,0,0.2)">
    <div class="gt-card-header"><h2 class="gt-card-title">🚀 Unlock the Full Power</h2></div>
    <p style="font-size:13px;color:var(--gt-soft);margin-bottom:16px">The Free Rule handles one store-wide BOGO. PRO gives you unlimited rules with precision targeting, scheduling, and enterprise controls.</p>
    <div class="gt-feature-grid gt-feature-grid--3col" style="margin-bottom:20px">
        <?php foreach([
            ['🎯','Unlimited PRO Rules','Category and product-level targeting, multiple simultaneous campaigns'],
            ['⏰','Campaign Scheduler','Set start and end dates, day-of-week schedules, and time-of-day windows'],
            ['🌍','Geo Targeting',     'Run different deals in different countries, states, or postcodes'],
            ['🎨','Variant Rules',     'Target specific sizes, colours, and materials'],
            ['💱','Multi-Currency',    'Per-currency thresholds and discount caps for global stores'],
            ['📊','Full Analytics',    'Rule leaderboard, daily charts, peak hour heatmap, CSV export'],
        ] as $f): ?>
        <div style="padding:14px;border-radius:10px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border)">
            <div style="font-size:20px;margin-bottom:6px"><?php echo $f[0]; ?></div>
            <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html($f[1]); ?></div>
            <div style="font-size:12px;color:var(--gt-soft);line-height:1.5"><?php echo esc_html($f[2]); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php if (!$is_pro): ?>
    <div style="display:flex;gap:12px;justify-content:center">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary" style="padding:14px 36px">Upgrade to PRO — $19.99/yr</a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=license')); ?>" class="gt-btn gt-btn-ghost">Activate License</a>
    </div>
    <?php else: ?>
    <div style="text-align:center"><a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=pro-rules')); ?>" class="gt-btn gt-btn-primary" style="padding:12px 32px">Go to PRO Rules →</a></div>
    <?php endif; ?>
</div>

<div style="text-align:right">
    <button type="submit" name="gtbogo_save_free_rule" class="gt-btn gt-btn-primary" style="padding:14px 40px">💾 Save Free Rule</button>
</div>
</form>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15);margin-top:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🧠 Free Rule Best Practices</h2></div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Start With a Minimum Cart Total</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Set a minimum cart total of at least your average product price to prevent the deal from firing on very small orders. A $25 minimum on a store with a $30 average product price means nearly every order qualifies while still protecting against discount exploitation on low-value baskets.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Cheapest Item = Best Margin Protection</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Apply the discount to the cheapest item in the cart. This means customers who add your most expensive product to get a cheap item discounted — rather than getting your hero product free. It drives up AOV while minimising discount cost as a percentage of revenue.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Cart Message Drives Qualification</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">A well-written cart message is worth an estimated 8–12% increase in qualification rate. "Add one more item to receive a complimentary product" is more effective than "Add to get BOGO" because it implies the customer is close to something valuable — not that they need to do work.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Exclude Sale Items to Protect Margin</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Always enable "Exclude Sale-Priced Items" unless you are running an intentional clearance event. Without this, customers can trigger BOGO on items already discounted 40–50%, resulting in an effective discount of 70%+ that can push the order margin negative.</div></div>
    </div>
</div>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
