<?php
/**
 * GT BOGO Engine — My Packs Manager
 * Per-pack dashboard for managing imported rule packs.
 * Shows pack health, per-rule controls, stats, and re-import options.
 *
 * @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 = '';

// ── Handle actions ────────────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['pack_action'] ) && check_admin_referer( 'gtbogo_pack_action' ) ) {
    $action   = sanitize_text_field( $_GET['pack_action'] );
    $pack_src = sanitize_text_field( $_GET['pack_source'] ?? '' );

    if ( $pack_src && in_array( $action, [ 'enable_all', 'disable_all', 'remove_all' ], true ) ) {
        global $wpdb;
$rtbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) );
if ( ! $rtbl ) {
    echo '<div class="gt-notice gt-notice-warn">Database tables not found. Please deactivate and reactivate the plugin.</div>';
    require_once __DIR__ . '/../ui-system/wrapper-end.php';
    return;
}

        if ( $action === 'enable_all' ) {
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}gtbogo_rules SET status='active' WHERE pack_source=%s",
                $pack_src
            ) );
            delete_transient( 'gtbogo_active_rules' );
            $message = 'All rules in pack enabled.'; $message_type = 'success';
        } elseif ( $action === 'disable_all' ) {
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}gtbogo_rules SET status='inactive' WHERE pack_source=%s",
                $pack_src
            ) );
            delete_transient( 'gtbogo_active_rules' );
            $message = 'All rules in pack paused.'; $message_type = 'success';
        } elseif ( $action === 'remove_all' ) {
            $wpdb->query( $wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}gtbogo_rules WHERE pack_source=%s",
                $pack_src
            ) );
            delete_transient( 'gtbogo_active_rules' );
            $message = 'Pack rules removed. You can re-import from the vault anytime.'; $message_type = 'success';
        }
    }
}

// ── Toggle single rule ────────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['toggle'] ) && check_admin_referer( 'toggle_rule_' . intval( $_GET['toggle'] ) ) ) {
    global $wpdb;
    $rule_id = intval( $_GET['toggle'] );
    $cur     = $wpdb->get_var( $wpdb->prepare( "SELECT status FROM {$wpdb->prefix}gtbogo_rules WHERE id=%d", $rule_id ) );
    $new     = $cur === 'active' ? 'inactive' : 'active';
    $wpdb->update( $wpdb->prefix . 'gtbogo_rules', [ 'status' => $new ], [ 'id' => $rule_id ] );
    delete_transient( 'gtbogo_active_rules' );
    $message = 'Rule ' . ( $new === 'active' ? 'enabled' : 'paused' ) . '.'; $message_type = 'success';
}

// ── Load data ─────────────────────────────────────────────────────────────────
global $wpdb;
$all_rules = $wpdb->get_results(
    "SELECT * FROM {$wpdb->prefix}gtbogo_rules ORDER BY pack_source ASC, priority ASC",
    ARRAY_A
);

// Group by pack_source
$packs_grouped = [];
foreach ( $all_rules as $r ) {
    $src = $r['pack_source'] ?: '_custom';
    $packs_grouped[ $src ][] = $r;
}

// Pack metadata from owned packs
$owned_pack_ids = class_exists( 'GT_BOGO_Pack_Downloader' ) ? GT_BOGO_Pack_Downloader::get_owned_pack_ids() : [];

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">📦 My Packs</h1>
        <p class="gt-page-subtitle">Manage your imported rule packs — enable, pause, configure and monitor each pack</p>
    </div>
    <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
        <span class="gt-badge gt-badge-active"><?php echo esc_html( count( $packs_grouped ) ); ?> <?php esc_html_e( 'packs imported', 'gt-bogo-engine' ); ?></span>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">
            ← <?php esc_html_e( 'Back to Vault', 'gt-bogo-engine' ); ?>
        </a>
    </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><?php esc_html_e( 'PRO License Required', 'gt-bogo-engine' ); ?></h2>
    <p><?php esc_html_e( 'Pack Manager requires a PRO license. Purchase and activate your license to import and manage rule packs.', 'gt-bogo-engine' ); ?></p>
    <div class="gt-flex" style="justify-content:center;gap:12px;flex-wrap:wrap">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary"><?php esc_html_e( 'Purchase PRO License', 'gt-bogo-engine' ); ?></a>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=license' ) ); ?>" class="gt-btn gt-btn-ghost"><?php esc_html_e( 'Activate License', 'gt-bogo-engine' ); ?></a>
    </div>
</div>
<?php elseif ( empty( $packs_grouped ) ) : ?>
<div class="gt-card gt-animate-in" style="text-align:center;padding:48px 24px">
    <div style="font-size:48px;margin-bottom:16px">📦</div>
    <h3 style="color:var(--gt-white);margin:0 0 8px"><?php esc_html_e( 'No Packs Imported Yet', 'gt-bogo-engine' ); ?></h3>
    <p class="gt-text-soft" style="font-size:13px" style="margin-bottom:24px"><?php esc_html_e( 'Purchase and import a Pro Pack from the vault to see it here.', 'gt-bogo-engine' ); ?></p>
    <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-primary"><?php esc_html_e( 'Browse Pro Packs', 'gt-bogo-engine' ); ?></a>
</div>
<?php else : ?>

<?php foreach ( $packs_grouped as $pack_src => $pack_rules ) :
    $is_custom  = $pack_src === '_custom';
    $total      = count( $pack_rules );
    $active_cnt = count( array_filter( $pack_rules, fn($r) => $r['status'] === 'active' ) );
    $health     = $total === 0 ? 'empty' : ( $active_cnt === $total ? 'full' : ( $active_cnt > 0 ? 'partial' : 'paused' ) );
    $health_map = [
        'full'    => [ 'label' => __( 'All Active', 'gt-bogo-engine' ),    'class' => 'gt-badge-active' ],
        'partial' => [ 'label' => __( 'Partial', 'gt-bogo-engine' ),       'class' => 'gt-badge-warn'   ],
        'paused'  => [ 'label' => __( 'All Paused', 'gt-bogo-engine' ),    'class' => 'gt-badge-free'   ],
        'empty'   => [ 'label' => __( 'No Rules', 'gt-bogo-engine' ),      'class' => 'gt-badge-free'   ],
    ];
    $pack_label = $is_custom ? __( 'Custom Rules', 'gt-bogo-engine' ) : esc_html( $pack_src );
    $pack_nonce_url = wp_nonce_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=my-packs&pack_source=' . urlencode( $pack_src ) ), 'gtbogo_pack_action' );
    $rules_fired    = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT SUM(current_uses) FROM {$wpdb->prefix}gtbogo_rules WHERE pack_source=%s",
        $pack_src
    ) );
?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">

    <!-- Pack Header -->
    <div class="gt-card-header" style="flex-wrap:wrap;gap:12px">
        <div style="display:flex;align-items:center;gap:12px;flex:1;min-width:0">
            <div style="width:40px;height:40px;border-radius:8px;background:rgba(225,0,0,0.1);border:1px solid rgba(225,0,0,0.2);display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0">📦</div>
            <div style="min-width:0">
                <h2 class="gt-card-title" style="margin:0 0 2px"><?php echo esc_html( $pack_label ); ?></h2>
                <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
                    <span class="gt-badge <?php echo esc_attr( $health_map[$health]['class'] ); ?>"><?php echo esc_html( $health_map[$health]['label'] ); ?></span>
                    <span class="gt-text-soft" style="font-size:13px"><?php echo esc_html( $active_cnt . '/' . $total ); ?> <?php esc_html_e( 'rules active', 'gt-bogo-engine' ); ?></span>
                    <?php if ( $rules_fired > 0 ) : ?>
                    <span class="gt-text-soft" style="font-size:13px">· <?php echo esc_html( number_format( $rules_fired ) ); ?> <?php esc_html_e( 'times fired', 'gt-bogo-engine' ); ?></span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Pack Actions -->
        <?php if ( ! $is_custom ) : ?>
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
            <a href="<?php echo esc_url( add_query_arg( 'pack_action', 'enable_all', $pack_nonce_url ) ); ?>"
               class="gt-btn gt-btn-sm" style="background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#4ade80"
               title="<?php esc_attr_e( 'Enable all rules in this pack', 'gt-bogo-engine' ); ?>">
                <?php esc_html_e( 'Enable All', 'gt-bogo-engine' ); ?>
            </a>
            <a href="<?php echo esc_url( add_query_arg( 'pack_action', 'disable_all', $pack_nonce_url ) ); ?>"
               class="gt-btn gt-btn-sm gt-btn-ghost"
               title="<?php esc_attr_e( 'Pause all rules in this pack', 'gt-bogo-engine' ); ?>">
                <?php esc_html_e( 'Pause All', 'gt-bogo-engine' ); ?>
            </a>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>"
               class="gt-btn gt-btn-sm gt-btn-ghost"
               title="<?php esc_attr_e( 'Re-import this pack', 'gt-bogo-engine' ); ?>">
                <?php esc_html_e( 'Re-import', 'gt-bogo-engine' ); ?>
            </a>
            <a href="<?php echo esc_url( add_query_arg( 'pack_action', 'remove_all', $pack_nonce_url ) ); ?>"
               class="gt-btn gt-btn-sm" style="background:rgba(220,38,38,0.08);color:#f87171;border:1px solid rgba(220,38,38,0.2)"
               onclick="return confirm('<?php echo esc_js( __( 'Remove all rules from this pack? The pack stays in your vault and can be re-imported.', 'gt-bogo-engine' ) ); ?>')"
               title="<?php esc_attr_e( 'Remove all rules from this pack', 'gt-bogo-engine' ); ?>">
                <?php esc_html_e( 'Remove Pack', 'gt-bogo-engine' ); ?>
            </a>
        </div>
        <?php endif; ?>
    </div>

    <!-- Pack Rules Table -->
    <div style="overflow-x:auto">
        <table class="gt-table" style="margin:0">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'Rule Name', 'gt-bogo-engine' ); ?></th>
                    <th><?php esc_html_e( 'Type', 'gt-bogo-engine' ); ?></th>
                    <th><?php esc_html_e( 'Buy / Get', 'gt-bogo-engine' ); ?></th>
                    <th><?php esc_html_e( 'Discount', 'gt-bogo-engine' ); ?></th>
                    <th><?php esc_html_e( 'Priority', 'gt-bogo-engine' ); ?></th>
                    <th><?php esc_html_e( 'Fired', 'gt-bogo-engine' ); ?></th>
                    <th><?php esc_html_e( 'Status', 'gt-bogo-engine' ); ?></th>
                    <th><?php esc_html_e( 'Toggle', 'gt-bogo-engine' ); ?></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $pack_rules as $r ) :
                $is_active  = $r['status'] === 'active';
                $toggle_url = wp_nonce_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=my-packs&toggle=' . $r['id'] ), 'toggle_rule_' . $r['id'] );
                $disc_label = $r['discount_type'] === 'percentage' || $r['discount_type'] === 'percent'
                    ? floatval( $r['discount_value'] ) . '%'
                    : '$' . number_format( floatval( $r['discount_value'] ), 2 );
            ?>
                <tr style="<?php echo esc_html( $is_active ) ? '' : 'opacity:0.55'; ?>">
                    <td>
                        <strong style="color:var(--gt-white)"><?php echo esc_html( $r['name'] ); ?></strong>
                        <?php if ( ! empty( $r['min_cart_total'] ) && $r['min_cart_total'] > 0 ) : ?>
                        <br><span style="font-size:13px;color:var(--gt-subtle)">Min cart: $<?php echo esc_html( number_format( (float)$r['min_cart_total'], 2 ) ); ?></span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span style="background:rgba(59,130,246,0.1);border:1px solid rgba(59,130,246,0.2);color:#93c5fd;padding:2px 8px;border-radius:50px;font-size:13px;font-weight:700">
                            <?php echo esc_html( str_replace( '_', ' ', ucfirst( $r['type'] ?? 'bogo' ) ) ); ?>
                        </span>
                    </td>
                    <td style="font-family:'DM Mono',monospace;color:var(--gt-white)"><?php echo (int)$r['buy_quantity']; ?> → <?php echo (int)$r['get_quantity']; ?></td>
                    <td style="font-weight:700;color:var(--gt-white)"><?php echo esc_html( $disc_label ); ?></td>
                    <td style="font-family:'DM Mono',monospace;color:var(--gt-soft)"><?php echo (int)$r['priority']; ?></td>
                    <td style="color:var(--gt-subtle)"><?php echo esc_html( number_format( (int)$r['current_uses'] ) ); ?></td>
                    <td>
                        <span class="gt-badge <?php echo esc_html( $is_active ) ? 'gt-badge-active' : 'gt-badge-free'; ?>">
                            <?php echo esc_html( $is_active ) ? '● ' . esc_html__( 'Active', 'gt-bogo-engine' ) : '○ ' . esc_html__( 'Paused', 'gt-bogo-engine' ); ?>
                        </span>
                    </td>
                    <td>
                        <a href="<?php echo esc_url( $toggle_url ); ?>" style="text-decoration:none;display:inline-flex" title="<?php echo esc_html( $is_active ) ? esc_attr__( 'Pause rule', 'gt-bogo-engine' ) : esc_attr__( 'Enable rule', 'gt-bogo-engine' ); ?>">
                            <span class="gtbogo-toggle <?php echo esc_html( $is_active ) ? 'gtbogo-toggle-on' : ''; ?>">
                                <span class="gtbogo-toggle-knob"></span>
                            </span>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Pack Performance Mini-Chart -->
    <?php if ( $rules_fired > 0 ) : ?>
    <div style="padding:16px 20px;border-top:1px solid var(--gt-border);display:flex;gap:24px;flex-wrap:wrap">
        <div>
            <div style="font-size:13px;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px;margin-bottom:4px"><?php esc_html_e( 'Total Activations', 'gt-bogo-engine' ); ?></div>
            <div style="font-size:20px;font-weight:800;color:var(--gt-white)"><?php echo esc_html( number_format( $rules_fired ) ); ?></div>
        </div>
        <div>
            <div style="font-size:13px;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px;margin-bottom:4px"><?php esc_html_e( 'Active Rules', 'gt-bogo-engine' ); ?></div>
            <div style="font-size:20px;font-weight:800;color:var(--gt-white)"><?php echo esc_html( $active_cnt ); ?>/<?php echo esc_html( $total ); ?></div>
        </div>
        <div>
            <div style="font-size:13px;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px;margin-bottom:4px"><?php esc_html_e( 'Pack Health', 'gt-bogo-engine' ); ?></div>
            <div style="font-size:20px;font-weight:800;color:<?php echo $health === 'full' ? '#4ade80' : ( $health === 'partial' ? '#fbbf24' : '#94a3b8' ); ?>">
                <?php echo esc_html( $health_map[$health]['label'] ); ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>

<?php endif; ?>

<style>
.gtbogo-toggle{display:inline-flex;align-items:center;width:40px;height:22px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.2);border-radius:50px;cursor:pointer;transition:background .2s,border-color .2s;flex-shrink:0;position:relative}
.gtbogo-toggle-on{background:rgba(34,197,94,0.25);border-color:rgba(34,197,94,0.5)}
.gtbogo-toggle-knob{width:16px;height:16px;border-radius:50%;background:#64748b;position:absolute;left:2px;transition:left .2s,background .2s}
.gtbogo-toggle-on .gtbogo-toggle-knob{left:20px;background:#22c55e}
</style>

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