<?php
/**
 * GT BOGO Engine — My Packs
 * Shows only legitimately purchased and server-activated packs.
 * Re-import re-validates through the license server.
 *
 * @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;

global $wpdb;

// Load owned packs from DB (server-verified purchases only)
$owned_packs_tbl = $wpdb->prefix . 'gtbogo_owned_packs';
$tbl_exists      = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $owned_packs_tbl ) );
$owned_packs_db  = [];
if ( $tbl_exists ) {
    $rows = $wpdb->get_results( "SELECT * FROM {$owned_packs_tbl} ORDER BY imported DESC" );
    foreach ( $rows as $row ) {
        $owned_packs_db[ $row->pack_id ] = $row;
    }
}

// ── Delete pack handler ───────────────────────────────────────────────────
if ( isset( $_GET['gtbogo_delete_pack'] ) && check_admin_referer( 'gtbogo_delete_pack_' . sanitize_text_field( $_GET['gtbogo_delete_pack'] ) ) ) {
    $del_pack_id = sanitize_text_field( $_GET['gtbogo_delete_pack'] );
    // Remove from owned_packs table
    $wpdb->delete( $wpdb->prefix . 'gtbogo_owned_packs', [ 'pack_id' => $del_pack_id ], [ '%s' ] );
    // Cascade: remove any rules imported from this pack
    $wpdb->delete( $wpdb->prefix . 'gtbogo_rules', [ 'pack_source' => $del_pack_id ], [ '%s' ] );
    // Remove from options cache
    $owned_opt = get_option( 'gtbogo_owned_packs', [] );
    $owned_opt = array_values( array_filter( (array) $owned_opt, fn( $p ) => $p !== $del_pack_id ) );
    update_option( 'gtbogo_owned_packs', $owned_opt );
    delete_transient( 'gtbogo_active_rules' );
    // Reload owned packs
    $rows = $tbl_exists ? $wpdb->get_results( "SELECT * FROM {$owned_packs_tbl} ORDER BY imported DESC" ) : [];
    $owned_packs_db = [];
    foreach ( $rows as $row ) { $owned_packs_db[ $row->pack_id ] = $row; }
    $delete_notice = 'Pack removed. All associated rules have been deleted from your rule stack.';
}

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

<!-- PAGE HEADER -->
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">📦 My Packs</h1>
        <p class="gt-page-subtitle">Your purchased PRO packs — re-import rules at any time with server verification</p>
    </div>
</div>

<?php if ( ! empty( $delete_notice ) ): ?>
<div class="gt-notice gt-animate-in" style="background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#86efac;border-radius:8px;padding:12px 18px;margin-bottom:16px">&#10003; <?php echo esc_html( $delete_notice ); ?></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>Purchase GT BOGO Engine PRO to access packs. Each pack is purchased separately and delivered to your email.</p>
    <div style="margin-top:20px">
        <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: ?>

<!-- MY PRO PACKS -->
<div class="gt-card gt-animate-in" style="margin-bottom:24px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🔐 My PRO Packs</h2>
        <span class="gt-text-soft gt-text-sm"><?php echo count( $owned_packs_db ); ?> pack<?php echo count( $owned_packs_db ) !== 1 ? 's' : ''; ?> activated on this store</span>
    </div>

    <?php if ( empty( $owned_packs_db ) ): ?>
    <div style="padding:48px 24px;text-align:center">
        <div style="font-size:44px;margin-bottom:16px">🔒</div>
        <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:10px">No PRO Packs Activated Yet</div>
        <p style="font-size:13px;color:var(--gt-subtle);max-width:460px;margin:0 auto 24px;line-height:1.65">
            Purchase a pack from the PRO Rules / Packs page. After purchase you will receive a
            <code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px">PACK-XXXXXXXXXXXX</code>
            key by email. Enter it on the PRO Rules / Packs page to activate and import your rules.
            Activated packs appear here for re-import.
        </p>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-primary">Browse Packs &rarr;</a>
    </div>

    <?php else: ?>
    <div style="padding:20px 24px">
        <p style="font-size:13px;color:var(--gt-subtle);margin:0 0 20px;line-height:1.5">
            Re-importing re-validates your PRO license with the GT BOGO Engine server before releasing rules.
            Pack rules are never included in config backup exports.
        </p>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px">
            <?php foreach ( $owned_packs_db as $pack_id => $pack_row ):
                $pack_rule_count = (int) $wpdb->get_var( $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}gtbogo_rules WHERE pack_source LIKE %s",
                    '%' . $wpdb->esc_like( $pack_row->pack_name ?? $pack_id ) . '%'
                ) );
                $activated_date = ! empty( $pack_row->imported )
                    ? date( 'M j, Y', strtotime( $pack_row->imported ) )
                    : 'Unknown';
            ?>
            <div style="background:var(--gt-glass);border:1px solid var(--gt-border);border-radius:12px;padding:20px;display:flex;flex-direction:column;gap:12px">
                <div>
                    <div style="font-size:13px;font-weight:800;color:var(--gt-white);margin-bottom:4px">
                        <?php echo esc_html( $pack_row->pack_name ?? $pack_id ); ?>
                    </div>
                    <div style="font-size:11px;color:var(--gt-subtle)">Activated <?php echo esc_html( $activated_date ); ?></div>
                </div>
                <div style="font-size:12px;color:var(--gt-subtle)">
                    <?php echo $pack_rule_count; ?> rule<?php echo $pack_rule_count !== 1 ? 's' : ''; ?> in your rule stack from this pack
                </div>
                <div style="display:flex;gap:8px;margin-top:auto;flex-wrap:wrap">
                    <button onclick="gtBogoReimportPack('<?php echo esc_js( $pack_id ); ?>','<?php echo esc_js( $pack_row->pack_name ?? $pack_id ); ?>',this)"
                        class="gt-btn gt-btn-ghost gt-btn-sm" style="flex:1">
                        &#8635; Re-import Rules
                    </button>
                    <a href="<?php echo esc_url( wp_nonce_url( add_query_arg( [ 'page' => 'gt-bogo-engine', 'tab' => 'templates', 'gtbogo_delete_pack' => $pack_id ], admin_url( 'admin.php' ) ), 'gtbogo_delete_pack_' . $pack_id ) ); ?>"
                        class="gt-btn gt-btn-sm" style="background:rgba(220,38,38,0.1);color:#f87171;border:1px solid rgba(220,38,38,0.25)"
                        onclick="return confirm('Permanently remove this pack and all its rules from your store?\n\nThis cannot be undone. You can re-purchase the pack at any time.')">
                        Remove
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </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);margin-bottom:24px">
    <div class="gt-card-header"><h2 class="gt-card-title">🔒 Pack Security</h2></div>
    <div class="gt-feature-grid gt-feature-grid--2col" style="padding:0 24px 24px">
        <div>
            <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Rules Are Not in Backups</div>
            <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Config backup exports never include rules that originated from a purchased pack. This prevents sharing a backup to grant free access to paid pack rules on another store.</div>
        </div>
        <div>
            <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Re-import Always Re-validates</div>
            <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Every re-import calls the GT BOGO Engine license server to verify your PRO license is active before releasing pack rules. No offline bypass is possible.</div>
        </div>
        <div>
            <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Packs Are Purchased Separately</div>
            <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Each PRO pack is purchased individually from the PRO Rules / Packs page. After purchase you receive a pack key by email. Enter the key to activate and import your rules.</div>
        </div>
        <div>
            <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Lost Your Pack Key?</div>
            <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Check your purchase email for your <code style="background:rgba(255,255,255,0.06);padding:1px 5px;border-radius:3px;font-size:11px">PACK-XXXXXXXXXXXX</code> key. If you cannot locate it, contact <a href="mailto:support@graphictshirts.shop" style="color:var(--gt-red)">support@graphictshirts.shop</a> with your order details.</div>
        </div>
    </div>
</div>

<script>
function gtBogoReimportPack(packId, packName, btn) {
    if (!confirm('Re-import all rules from ' + packName + '?\n\nThis will add the pack rules again as inactive copies for your review.')) return;
    btn.disabled = true;
    btn.textContent = 'Re-importing\u2026';

    var fd = new FormData();
    fd.append('action',  'gtbogo_download_pack');
    fd.append('pack_id', packId);
    fd.append('nonce',   '<?php echo esc_js( wp_create_nonce( 'gtbogo_download_pack' ) ); ?>');

    fetch(ajaxurl, { method: 'POST', body: fd })
        .then(function(r){ return r.json(); })
        .then(function(d){
            if (d.success) {
                btn.textContent = '\u2713 Done';
                btn.style.color = '#22c55e';
                setTimeout(function(){ location.reload(); }, 1500);
            } else {
                btn.textContent = '\u2717 Failed \u2014 retry';
                btn.disabled = false;
                alert('Re-import failed: ' + (d.data ? d.data.message : 'Unknown error'));
                setTimeout(function(){ btn.textContent = '\u8635 Re-import Rules'; btn.style.color=''; }, 2500);
            }
        })
        .catch(function(){
            btn.textContent = 'Error \u2014 retry';
            btn.disabled = false;
        });
}
</script>

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