<?php
/**
 * GT BOGO Engine — Rule Conditions Engine
 * @package GT_BOGO_Engine
 * @since   3.10.1
 */
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 = '';

if ($is_pro && isset($_POST['gtbogo_save_conditions']) && check_admin_referer('gtbogo_conditions', 'gtbogo_conditions_nonce')) {
    $conditions = [
        'categories'       => array_map('intval', (array)($_POST['condition_categories'] ?? [])),
        'tags'             => array_map('intval', (array)($_POST['condition_tags'] ?? [])),
        'min_cart'         => floatval($_POST['condition_min_cart'] ?? 0),
        'max_cart'         => floatval($_POST['condition_max_cart'] ?? 0),
        'days'             => array_map('sanitize_text_field', (array)($_POST['condition_days'] ?? [])),
        'time_start'       => sanitize_text_field(wp_unslash($_POST['condition_time_start'] ?? '00:00')),
        'time_end'         => sanitize_text_field(wp_unslash($_POST['condition_time_end']   ?? '23:59')),
        'exclude_sale'     => isset($_POST['condition_exclude_sale']),
        'exclude_products' => array_map('intval', (array)($_POST['condition_exclude_products'] ?? [])),
        'mode'             => sanitize_text_field(wp_unslash($_POST['condition_mode'] ?? 'all')),
    ];
    update_option('gtbogo_rule_conditions', $conditions);
    $message = 'Conditions saved.';
}

$c = get_option('gtbogo_rule_conditions', [
    'categories' => [], 'tags' => [], 'min_cart' => 0, 'max_cart' => 0,
    'days' => [], 'time_start' => '00:00', 'time_end' => '23:59',
    'exclude_sale' => false, 'exclude_products' => [], 'mode' => 'all',
]);

$all_cats  = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false]);
$all_tags  = get_terms(['taxonomy' => 'product_tag', 'hide_empty' => false]);
$all_days  = ['monday'=>'Monday','tuesday'=>'Tuesday','wednesday'=>'Wednesday','thursday'=>'Thursday','friday'=>'Friday','saturday'=>'Saturday','sunday'=>'Sunday'];

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🎛️ Rule Conditions</h1>
        <p class="gt-page-subtitle">Fine-tune exactly when and where rules fire — category, cart value, time, day</p>
    </div>
</div>
<?php if ($message): ?><div class="gt-notice gt-notice-success gt-animate-in">✓ <?php echo esc_html($message); ?></div><?php endif; ?>

<?php if (!$is_pro): ?>
<div class="gt-pro-gate gt-animate-in">
    <span class="gt-pro-gate-icon">🎛️</span>
    <h2>PRO License Required</h2>
    <p>Rule Conditions let you target rules with surgical precision — specific categories, cart values, days of the week, and time windows.</p>
    <div class="gt-flex" style="justify-content:center;gap:12px">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO</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>
</div>
<?php else: ?>
<form method="post" action="">
<?php wp_nonce_field('gtbogo_conditions', 'gtbogo_conditions_nonce'); ?>

<!-- Mode -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">Condition Mode</h2></div>
    <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
        <?php foreach(['all'=>['Match ALL Conditions','Every condition below must be true for the rule to fire'],'any'=>['Match ANY Condition','Rule fires if at least one condition is true']] as $k=>$v): ?>
        <label style="cursor:pointer" onclick="gtbogoSelectMode(this)">
            <input type="radio" name="condition_mode" value="<?php echo $k; ?>" <?php checked($c['mode']??'all',$k); ?> style="display:none">
            <div class="gt-mode-card" style="padding:16px;border-radius:10px;border:2px solid <?php echo ($c['mode']??'all')===$k?'rgba(225,0,0,0.4)':'rgba(255,255,255,0.06)'; ?>;background:<?php echo ($c['mode']??'all')===$k?'rgba(225,0,0,0.06)':'rgba(255,255,255,0.02)'; ?>;transition:all 0.2s">
                <div style="font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html($v[0]); ?></div>
                <div style="font-size:12px;color:var(--gt-soft)"><?php echo esc_html($v[1]); ?></div>
            </div>
        </label>
        <?php endforeach; ?>
<script>
function gtbogoSelectMode(label) {
    var radio = label.querySelector('input[type=radio]');
    radio.checked = true;
    document.querySelectorAll('input[name=condition_mode]').forEach(function(r) {
        var card = r.parentElement.querySelector('.gt-mode-card');
        if (r.checked) {
            card.style.border = '2px solid rgba(225,0,0,0.4)';
            card.style.background = 'rgba(225,0,0,0.06)';
        } else {
            card.style.border = '2px solid rgba(255,255,255,0.06)';
            card.style.background = 'rgba(255,255,255,0.02)';
        }
    });
}
</script>
    </div>
</div>

<!-- Categories & Tags -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🏷️ Product Categories & Tags</h2><span class="gt-text-soft gt-text-sm">Leave empty to apply to all</span></div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Apply only to these Categories</label>
            <div style="max-height:180px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:8px;padding:10px;display:flex;flex-direction:column;gap:6px">
                <?php foreach ((array)$all_cats as $cat): ?>
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                    <input type="checkbox" name="condition_categories[]" value="<?php echo intval($cat->term_id); ?>"
                           <?php checked(in_array($cat->term_id, (array)($c['categories']??[]))); ?> style="accent-color:var(--gt-red)">
                    <span style="font-size:13px;color:var(--gt-white)"><?php echo esc_html($cat->name); ?></span>
                    <span style="font-size:11px;color:var(--gt-subtle)">(<?php echo intval($cat->count); ?>)</span>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Apply only to these Tags</label>
            <div style="max-height:180px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:8px;padding:10px;display:flex;flex-direction:column;gap:6px">
                <?php foreach ((array)$all_tags as $tag): ?>
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                    <input type="checkbox" name="condition_tags[]" value="<?php echo intval($tag->term_id); ?>"
                           <?php checked(in_array($tag->term_id, (array)($c['tags']??[]))); ?> style="accent-color:var(--gt-red)">
                    <span style="font-size:13px;color:var(--gt-white)"><?php echo esc_html($tag->name); ?></span>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- Cart Value -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🛒 Cart Value Range</h2><span class="gt-text-soft gt-text-sm">Set to 0 to disable limit</span></div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Minimum Cart Value ($)</label>
            <input type="number" name="condition_min_cart" class="gt-input" min="0" step="0.01" value="<?php echo esc_attr($c['min_cart']??0); ?>">
            <div class="gt-form-hint">Rule only fires if cart total is at least this amount</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Maximum Cart Value ($)</label>
            <input type="number" name="condition_max_cart" class="gt-input" min="0" step="0.01" value="<?php echo esc_attr($c['max_cart']??0); ?>">
            <div class="gt-form-hint">Rule only fires if cart total is below this amount (0 = no limit)</div>
        </div>
    </div>
</div>

<!-- Days & Time -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">📅 Days & Time Window</h2></div>
    <div class="gt-form-group" style="margin-bottom:20px">
        <label class="gt-form-label">Active Days (leave empty for all days)</label>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <?php foreach ($all_days as $k=>$v): ?>
            <label style="cursor:pointer">
                <input type="checkbox" name="condition_days[]" value="<?php echo $k; ?>"
                       <?php checked(in_array($k,(array)($c['days']??[]))); ?> style="display:none">
                <span style="display:inline-block;padding:6px 14px;border-radius:50px;font-size:12px;font-weight:600;border:1px solid;cursor:pointer;transition:all 0.2s;<?php echo in_array($k,(array)($c['days']??[]))?'background:rgba(225,0,0,0.1);border-color:rgba(225,0,0,0.4);color:var(--gt-white)':' background:rgba(255,255,255,0.02);border-color:var(--gt-border);color:var(--gt-soft)'; ?>"
                      onclick="this.previousElementSibling.checked=!this.previousElementSibling.checked;this.style.cssText=this.previousElementSibling.checked?'display:inline-block;padding:6px 14px;border-radius:50px;font-size:12px;font-weight:600;border:1px solid;cursor:pointer;background:rgba(225,0,0,0.1);border-color:rgba(225,0,0,0.4);color:var(--gt-white)':' display:inline-block;padding:6px 14px;border-radius:50px;font-size:12px;font-weight:600;border:1px solid;cursor:pointer;background:rgba(255,255,255,0.02);border-color:rgba(255,255,255,0.06);color:var(--gt-soft)'"><?php echo esc_html($v); ?></span>
            </label>
            <?php endforeach; ?>
        </div>
    </div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Active From (Time)</label>
            <input type="time" name="condition_time_start" class="gt-input" value="<?php echo esc_attr($c['time_start']??'00:00'); ?>">
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Active Until (Time)</label>
            <input type="time" name="condition_time_end" class="gt-input" value="<?php echo esc_attr($c['time_end']??'23:59'); ?>">
        </div>
    </div>
</div>

<!-- Exclusions -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🚫 Exclusions</h2></div>
    <div class="gt-setting-row" style="border:none;padding:0">
        <div>
            <div class="gt-setting-label">Exclude Already-On-Sale Products</div>
            <div class="gt-setting-desc">Rule will not apply to products that already have a WooCommerce sale price set</div>
        </div>
        <label class="gt-toggle">
            <input type="checkbox" name="condition_exclude_sale" value="1" <?php checked(!empty($c['exclude_sale'])); ?>>
            <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
        </label>
    </div>
</div>

<div class="gt-card gt-animate-in">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
        <div class="gt-text-soft gt-text-sm">Conditions apply globally to all active PRO rules</div>
        <button type="submit" name="gtbogo_save_conditions" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Conditions</button>
    </div>
</div>
</form>
<?php endif; ?>

<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
    <div class="gt-card-header"><h2 class="gt-card-title">💡 Conditions Strategy Guide</h2><span class="gt-text-soft gt-text-sm">Use conditions to protect margins and target the right customers</span></div>
    <div class="gt-feature-grid gt-feature-grid--2col" style="gap:12px">
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">🕐 Time-Window Rules</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Run BOGO deals only during peak shopping hours — 6pm to 10pm typically converts 40% higher. Set a Friday to Sunday window for weekend promotions that do not dilute your weekday margins.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">🏷️ Category Targeting</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Restrict high-discount rules to slow-moving categories only. Your best-selling products rarely need BOGO incentives — protect margin on those and deploy deals where velocity is lagging.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">🛒 Cart Value Floors</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Set a minimum cart value so BOGO only fires once the customer has already committed to spending. A $40 floor on a $50 AOV store rewards engaged buyers, not bargain hunters adding one cheap item.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">🚫 Sale Price Exclusion</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Always enable Exclude Already-On-Sale Products for luxury and fashion brands. Stacking BOGO on top of a sale price can push discount depth past 60%, damaging brand equity and triggering margin alerts.</p>
        </div>
    </div>
</div>

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