<?php
/**
 * GT BOGO Engine — Import / Export (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 = '';

global $wpdb;
$rtbl = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_rules'));
$rules = $rtbl ? $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gtbogo_rules ORDER BY priority DESC, name ASC") : [];

// ── EXPORT RULES JSON ─────────────────────────────────────────────────────
if ($is_pro && isset($_GET['export_rules']) && check_admin_referer('gtbogo_export_rules')) {
    $export = [
        'plugin'    => 'GT BOGO Engine PRO',
        'version'   => defined('GT_BOGO_VERSION') ? GT_BOGO_VERSION : '3.11.0',
        'exported'  => current_time('mysql'),
        'site'      => home_url(),
        'rules'     => array_map(fn($r) => (array)$r, $rules),
    ];
    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename="gt-bogo-rules-' . date('Y-m-d') . '.json"');
    echo wp_json_encode($export, JSON_PRETTY_PRINT);
    exit;
}

// ── EXPORT FULL CONFIG JSON ───────────────────────────────────────────────
if ($is_pro && isset($_GET['export_config']) && check_admin_referer('gtbogo_export_config')) {
    $config_keys = [
        'gtbogo_free_rule','gtbogo_variant_rules','gtbogo_variant_rule_overrides',
        'gtbogo_currency_overrides','gtbogo_currency_rounding','gtbogo_currency_fallback',
        'gtbogo_geo_enabled','gtbogo_geo_detect','gtbogo_geo_fallback','gtbogo_geo_zones',
        'gtbogo_segments','gtbogo_schedules','gtbogo_deal_display','gtbogo_deal_page_id',
        'gtbogo_api_enabled','gtbogo_api_rate_limit','gtbogo_sched_cron_enabled',
        'gtbogo_analytics_enabled','gtbogo_analytics_retention_days',
        'gtbogo_log_enabled','gtbogo_log_max_entries',
    ];
    $config = ['plugin'=>'GT BOGO Engine PRO','version'=>defined('GT_BOGO_VERSION')?GT_BOGO_VERSION:'3.11.0','exported'=>current_time('mysql'),'site'=>home_url(),'settings'=>[],'rules'=>array_map(fn($r)=>(array)$r,array_filter($rules,fn($r)=>empty($r->pack_source)))];
    foreach ($config_keys as $k) $config['settings'][$k] = get_option($k);
    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename="gt-bogo-full-config-' . date('Y-m-d') . '.json"');
    echo wp_json_encode($config, JSON_PRETTY_PRINT);
    exit;
}

// ── IMPORT RULES ──────────────────────────────────────────────────────────
if ($is_pro && isset($_POST['gtbogo_import_rules']) && check_admin_referer('gtbogo_import')) {
    $file = $_FILES['import_file'] ?? null;
    $mode = sanitize_text_field($_POST['import_mode'] ?? 'merge');
    if ($file && !$file['error'] && $rtbl) {
        $raw = file_get_contents($file['tmp_name']);
        $data = json_decode($raw, true);
        if ($data && isset($data['rules']) && is_array($data['rules'])) {
            $imported = 0; $skipped = 0;
            if ($mode === 'replace') {
                $wpdb->query("DELETE FROM {$wpdb->prefix}gtbogo_rules");
            }
            foreach ($data['rules'] as $rule) {
                unset($rule['id']); // always insert fresh
                $rule['name']           = sanitize_text_field($rule['name'] ?? 'Imported Rule');
                $rule['type']           = sanitize_text_field($rule['type'] ?? 'bogo');
                $rule['status']         = 'inactive'; // always import as inactive
                $rule['buy_quantity']   = intval($rule['buy_quantity']  ?? 1);
                $rule['get_quantity']   = intval($rule['get_quantity']  ?? 1);
                $rule['discount_type']  = sanitize_text_field($rule['discount_type']  ?? 'percentage');
                $rule['discount_value'] = floatval($rule['discount_value'] ?? 100);
                $rule['min_cart_total'] = floatval($rule['min_cart_total'] ?? 0);
                $rule['priority']       = intval($rule['priority']      ?? 10);
                $rule['categories']     = sanitize_text_field($rule['categories']     ?? '');
                $rule['products']       = sanitize_text_field($rule['products']       ?? '');
                $rule['max_uses']       = intval($rule['max_uses']      ?? 0);
                $rule['current_uses']   = 0;
                $rule['start_date']     = sanitize_text_field($rule['start_date']     ?? '');
                $rule['end_date']       = sanitize_text_field($rule['end_date']       ?? '');
                $rule['created_at']     = current_time('mysql');
                $rule['updated_at']     = current_time('mysql');
                $res = $wpdb->insert($wpdb->prefix.'gtbogo_rules', $rule);
                if ($res) $imported++; else $skipped++;
            }
            if (function_exists('gt_bogo_log')) gt_bogo_log('Rules imported', $imported.' rules imported, '.$skipped.' skipped. Mode: '.$mode, 'success');
            delete_transient('gtbogo_active_rules');
            $message = $imported.' rule'.($imported!==1?'s':'').' imported successfully'.($skipped?' ('.$skipped.' skipped due to errors)':'').'. All imported rules are set to Inactive — review and activate them in PRO Rules.';
            $message_type = 'success';
        } else {
            $message = 'Invalid file. Expected GT BOGO Engine JSON export format.'; $message_type = 'error';
        }
    } else {
        $message = 'No file uploaded or upload error occurred.'; $message_type = 'error';
    }
}

// ── IMPORT FULL CONFIG ────────────────────────────────────────────────────
if ($is_pro && isset($_POST['gtbogo_import_config']) && check_admin_referer('gtbogo_import_config')) {
    $file = $_FILES['config_file'] ?? null;
    if ($file && !$file['error']) {
        $raw  = file_get_contents($file['tmp_name']);
        $data = json_decode($raw, true);
        if ($data && isset($data['settings']) && is_array($data['settings'])) {
            foreach ($data['settings'] as $k => $v) {
                if (strpos($k, 'gtbogo_') === 0) update_option(sanitize_key($k), $v);
            }
            $config_imported = true;
            if (isset($data['rules']) && is_array($data['rules']) && $rtbl) {
                foreach ($data['rules'] as $rule) {
                    unset($rule['id']);
                    $rule['status']     = 'inactive';
                    $rule['current_uses'] = 0;
                    $rule['created_at'] = current_time('mysql');
                    $rule['updated_at'] = current_time('mysql');
                    $wpdb->insert($wpdb->prefix.'gtbogo_rules', array_map('sanitize_text_field', array_map('strval', $rule)));
                }
            }
            if (function_exists('gt_bogo_log')) gt_bogo_log('Full config imported', 'From '.(isset($data['site'])?$data['site']:'unknown site'), 'success');
            delete_transient('gtbogo_active_rules');
            $message = 'Full configuration imported from '.esc_html($data['site']??'unknown site').'. Review all settings and activate rules before going live.'; $message_type = 'success';
        } else {
            $message = 'Invalid config file. Expected GT BOGO Engine full config JSON.'; $message_type = 'error';
        }
    } else {
        $message = 'Upload error.'; $message_type = 'error';
    }
}

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">📦 Import / Export</h1>
        <p class="gt-page-subtitle">Back up your rules and complete plugin config — transfer between sites or restore after an issue</p>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <span class="gt-badge gt-badge-active"><?php echo count($rules); ?> rule<?php echo count($rules)!==1?'s':''; ?> ready to export</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; ?>

<?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>Import/Export gives you complete control over your BOGO configuration — back up rules, migrate between sites, and restore from JSON in seconds.</p>
    <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
        <?php foreach(['Export all rules to JSON','Export complete plugin config (all settings)','Import with merge or replace mode','Full config import for site migration'] as $f): ?>
        <div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($f); ?></span></div>
        <?php endforeach; ?>
    </div>
    <div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $19.99/yr</a>
    </div>
</div>
<?php else: ?>

<!-- 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">Total Rules</div>
        <div class="gt-metric-value"><?php echo count($rules); ?></div>
        <div class="gt-metric-trend"><?php echo count(array_filter($rules,fn($r)=>$r->status==='active')); ?> active</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#22c55e">
        <span class="gt-metric-icon">⚙️</span>
        <div class="gt-metric-label">Config Options</div>
        <div class="gt-metric-value">21</div>
        <div class="gt-metric-trend">Exportable settings</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#3b82f6">
        <span class="gt-metric-icon">🌍</span>
        <div class="gt-metric-label">Site</div>
        <div class="gt-metric-value" style="font-size:13px"><?php echo esc_html(parse_url(home_url(),PHP_URL_HOST)); ?></div>
        <div class="gt-metric-trend">Export source</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#8b5cf6">
        <span class="gt-metric-icon">📅</span>
        <div class="gt-metric-label">Export Date</div>
        <div class="gt-metric-value" style="font-size:16px"><?php echo date('M j'); ?></div>
        <div class="gt-metric-trend"><?php echo date('Y'); ?></div>
    </div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

<!-- EXPORT -->
<div>
    <div class="gt-card gt-animate-in" style="margin-bottom:16px">
        <div class="gt-card-header"><h2 class="gt-card-title">⬇ Export Rules</h2></div>
        <p style="font-size:13px;color:var(--gt-soft);margin-bottom:16px">Downloads a JSON file containing all <?php echo count($rules); ?> rules with their full configuration. Use this to back up rules or transfer them to another site.</p>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:8px;padding:12px 16px;font-family:'DM Mono',monospace;font-size:11px;color:var(--gt-soft);margin-bottom:16px">
            <div style="color:var(--gt-white);font-size:12px;margin-bottom:4px"><?php echo count($rules); ?> rules · <?php echo date('Y-m-d'); ?> · GT BOGO Engine <?php echo defined('GT_BOGO_VERSION')?GT_BOGO_VERSION:'3.11.0'; ?></div>
            <?php foreach (array_slice($rules,0,3) as $r): ?>
            <div>— <?php echo esc_html($r->name); ?> (<?php echo esc_html($r->status); ?>)</div>
            <?php endforeach; ?>
            <?php if (count($rules)>3): ?><div>… and <?php echo count($rules)-3; ?> more</div><?php endif; ?>
        </div>
        <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['export_rules'=>1,'page'=>'gt-bogo-engine','tab'=>'import-export'],admin_url('admin.php')),'gtbogo_export_rules')); ?>"
           class="gt-btn gt-btn-primary" style="width:100%;text-align:center;justify-content:center;display:block;padding:12px">⬇ Download Rules JSON</a>
    </div>

    <div class="gt-card gt-animate-in">
        <div class="gt-card-header"><h2 class="gt-card-title">⬇ Export Full Config</h2></div>
        <p style="font-size:13px;color:var(--gt-soft);margin-bottom:16px">Downloads a complete JSON snapshot — all rules plus every plugin setting (geo zones, segments, schedules, currency overrides, display options, and more). Use this for site migrations or full backups.</p>
        <div style="padding:10px 14px;background:rgba(245,158,11,0.06);border-radius:8px;border:1px solid rgba(245,158,11,0.15);font-size:12px;color:#fcd34d;margin-bottom:16px">
            ⚠ Full config export includes API keys and sensitive settings. Store the file securely and do not share publicly.
        </div>
        <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['export_config'=>1,'page'=>'gt-bogo-engine','tab'=>'import-export'],admin_url('admin.php')),'gtbogo_export_config')); ?>"
           class="gt-btn gt-btn-ghost" style="width:100%;text-align:center;justify-content:center;display:block;padding:12px">⬇ Download Full Config JSON</a>
    </div>
</div>

<!-- IMPORT -->
<div>
    <div class="gt-card gt-animate-in" style="margin-bottom:16px">
        <div class="gt-card-header"><h2 class="gt-card-title">⬆ Import Rules</h2></div>
        <p style="font-size:13px;color:var(--gt-soft);margin-bottom:16px">Upload a GT BOGO Engine rules JSON export. All imported rules are set to <strong style="color:var(--gt-white)">Inactive</strong> — review and activate them in PRO Rules after importing.</p>
        <form method="post" action="" enctype="multipart/form-data">
            <?php wp_nonce_field('gtbogo_import'); ?>
            <div class="gt-form-group">
                <label class="gt-form-label">Rules JSON File</label>
                <input type="file" name="import_file" accept=".json" class="gt-input" style="padding:8px" required>
            </div>
            <div class="gt-form-group">
                <label class="gt-form-label">Import Mode</label>
                <select name="import_mode" class="gt-select">
                    <option value="merge">Merge — add to existing rules</option>
                    <option value="replace">Replace — delete all existing rules first</option>
                </select>
                <div class="gt-form-hint">Replace mode permanently deletes your current rules. Back them up first.</div>
            </div>
            <div style="padding:10px 14px;background:rgba(225,0,0,0.05);border-radius:8px;border:1px solid rgba(225,0,0,0.15);font-size:12px;color:#fca5a5;margin-bottom:16px">
                🚨 Replace mode cannot be undone. Export your current rules first if you have not already done so.
            </div>
            <button type="submit" name="gtbogo_import_rules" class="gt-btn gt-btn-primary" style="width:100%;padding:12px;text-align:center"
                    onclick="return document.querySelector('[name=import_mode]').value==='replace'?confirm('Replace mode will DELETE all existing rules. Are you sure?'):true">
                ⬆ Import Rules
            </button>
        </form>
    </div>

    <div class="gt-card gt-animate-in">
        <div class="gt-card-header"><h2 class="gt-card-title">⬆ Import Full Config</h2></div>
        <p style="font-size:13px;color:var(--gt-soft);margin-bottom:16px">Upload a full config JSON to restore all settings and rules. This overwrites all current plugin settings. Used for site migration or restoring a backup.</p>
        <form method="post" action="" enctype="multipart/form-data">
            <?php wp_nonce_field('gtbogo_import_config'); ?>
            <div class="gt-form-group">
                <label class="gt-form-label">Full Config JSON File</label>
                <input type="file" name="config_file" accept=".json" class="gt-input" style="padding:8px" required>
            </div>
            <div style="padding:10px 14px;background:rgba(225,0,0,0.05);border-radius:8px;border:1px solid rgba(225,0,0,0.15);font-size:12px;color:#fca5a5;margin-bottom:16px">
                🚨 Importing a full config overwrites all current plugin settings. Export your current config first.
            </div>
            <button type="submit" name="gtbogo_import_config" class="gt-btn gt-btn-primary" style="width:100%;padding:12px;text-align:center"
                    onclick="return confirm('This will overwrite all GT BOGO Engine settings. Proceed?')">
                ⬆ Import Full Config
            </button>
        </form>
    </div>
</div>
</div>

<!-- RULES TABLE PREVIEW -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">📋 Current Rules (Export Preview)</h2><span class="gt-text-soft gt-text-sm">These are the rules that will be included in your export</span></div>
    <?php if (!empty($rules)): ?>
    <div style="overflow-x:auto">
        <table class="gt-table">
            <thead><tr><th>ID</th><th>Name</th><th>Type</th><th>Buy</th><th>Get</th><th>Discount</th><th>Min Cart</th><th>Priority</th><th>Status</th></tr></thead>
            <tbody>
            <?php foreach ($rules as $r): ?>
            <tr>
                <td style="font-family:'DM Mono',monospace;color:var(--gt-subtle)"><?php echo $r->id; ?></td>
                <td style="font-weight:700;color:var(--gt-white)"><?php echo esc_html($r->name); ?></td>
                <td style="font-size:11px;font-family:'DM Mono',monospace;color:var(--gt-soft)"><?php echo esc_html($r->type); ?></td>
                <td style="text-align:center;font-family:'DM Mono',monospace"><?php echo $r->buy_quantity; ?></td>
                <td style="text-align:center;font-family:'DM Mono',monospace"><?php echo $r->get_quantity; ?></td>
                <td style="font-family:'DM Mono',monospace;color:#86efac"><?php echo $r->discount_value; ?>%</td>
                <td style="font-family:'DM Mono',monospace;color:var(--gt-soft)"><?php echo $r->min_cart_total>0?'$'.number_format($r->min_cart_total,2):'—'; ?></td>
                <td style="font-family:'DM Mono',monospace;text-align:center"><?php echo $r->priority; ?></td>
                <td><span class="gt-badge <?php echo $r->status==='active'?'gt-badge-active':'gt-badge-free'; ?>"><?php echo esc_html(ucfirst($r->status)); ?></span></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:32px;color:var(--gt-soft)">No rules yet. Create rules in PRO Rules or import from a JSON file.</div>
    <?php endif; ?>
</div>

<!-- 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)">
    <div class="gt-card-header"><h2 class="gt-card-title">🧠 Import/Export Guide</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">Monthly Backup Routine</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Export Full Config on the first of each month and store it in a dated folder (e.g. gt-bogo-backup-2026-03.json). This gives you a 12-point restore history for the year. Keep at least 3 months of exports before deleting older ones.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Site Migration Workflow</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Export Full Config from your source site. Install GT BOGO Engine PRO on the destination site and activate your license. Import Full Config. All rules will import as Inactive — review them in PRO Rules and activate only the rules you need live on the new site.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Dev to Production Sync</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Build and test your full rule configuration on a staging site. Export Rules JSON when testing is complete. Import to production using Merge mode — this adds the new rules without touching your existing production rules. Activate them one by one after confirming each fires correctly on a test order.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Replace Mode Warning</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Replace mode deletes all existing rules in the database before importing. It is designed for clean site resets, not incremental updates. Always export your current rules to a local file before using Replace — the operation cannot be reversed.</div></div>
    </div>
</div>

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