Shortcodes as of 10/2 1 am

<?php
// File: wp-content/plugins/stella-quotes/includes/class-stq-shortcodes.php
if (!defined(‘ABSPATH’)) exit;

class STQ_Shortcodes {

/* ===== STQ_Shortcodes::init ===== */
public static function init(){
add_shortcode(‘stq_market’, [__CLASS__,’market’]);
add_shortcode(‘stq_compare_picker’, [__CLASS__,’compare_picker’]);
add_shortcode(‘stq_compare’, [__CLASS__,’compare’]);
add_shortcode(‘stq_diag_benefits’, [__CLASS__,’diag_benefits’]);
// NEW: intake form for starting a quote
add_shortcode(‘stq_quote_intake’, [__CLASS__,’quote_intake’]);
}
/* ===== /STQ_Shortcodes::init ===== */

/* ———- Day 2 format helpers (mirror export) ———- */
private static function fmt_benefit($v){
if ($v === ” || $v === null) return ”;
if (is_string($v)) {
if (preg_match(‘/[A-Za-z&]/’, $v)) return (string)$v; // pass through mixed strings
if (preg_match(‘/^\s*0+(\.0+)?\s*$/’, $v)) return ‘$0’; // “$0” no decimals
}
if (is_numeric($v)) {
if (floatval($v) == 0.0) return ‘$0’;
return STQ_Format::money($v);
}
return (string)$v;
}
private static function fmt_coins($v){
if ($v === ” || $v === null) return ”;
if (is_string($v) && preg_match(‘/[A-Za-z]/’, $v)) return (string)$v;
return STQ_Format::coins($v);
}

/* ———- SAFE census-count parser ———- */
/**
* Parse EO/ES/EC/EF counts from a CSV file path or the current upload.
* – If $path is provided and readable, use it.
* – Else, if an upload exists at $_FILES[‘stq_census’][‘tmp_name’], use that.
* – Always guard file reads; return null on failure.
*/
private static function parse_counts_from_upload(string $path = ”){
$file = ”;
if ($path && is_readable($path)) {
$file = $path;
} elseif (!empty($_FILES[‘stq_census’][‘tmp_name’]) && is_uploaded_file($_FILES[‘stq_census’][‘tmp_name’]) && is_readable($_FILES[‘stq_census’][‘tmp_name’])) {
$file = $_FILES[‘stq_census’][‘tmp_name’];
} else {
return null;
}

$fh = @fopen($file, ‘r’);
if (!$fh) return null;

$hdr = fgetcsv($fh);
if (!$hdr || !is_array($hdr)) { fclose($fh); return null; }
$idx = array_flip($hdr);

// find relationship and tier field(s)
$relKey = null;
foreach ([‘Relationship’,’relationship’,’RELATIONSHIP’] as $k) { if (isset($idx[$k])) { $relKey = $k; break; } }

$tierField = null;
foreach ([‘Coverage Tier for Employees’,’Coverage Tier’,’coverage tier’,’Tier’,’tier’] as $k) { if (isset($idx[$k])) { $tierField = $k; break; } }

$waiveField = null;
foreach ([‘Waive’,’waive’,’Waived’,’waived’,’Decline’,’decline’] as $k) { if (isset($idx[$k])) { $waiveField = $k; break; } }

$counts = [‘EO’=>0,’ES’=>0,’EC’=>0,’EF’=>0,’TOTAL’=>0];

while (($r = fgetcsv($fh)) !== false) {
if (!is_array($r)) continue;

$isEmployee = true; // default to employee if we lack a relationship column
if ($relKey !== null) {
$rel = strtolower(trim((string)($r[$idx[$relKey]] ?? ”)));
$isEmployee = in_array($rel, [’employee’,’emp’,’subscriber’,’self’], true);
}
if (!$isEmployee) continue;

// skip waived
if ($waiveField !== null) {
$wv = strtolower(trim((string)($r[$idx[$waiveField]] ?? ”)));
if (in_array($wv, [‘y’,’yes’,’waive’,’waived’,’true’,’1′], true)) continue;
}

if ($tierField === null) continue;
$raw = strtoupper(trim((string)($r[$idx[$tierField]] ?? ”)));
if ($raw === ”) continue;

// normalize into EO/ES/EC/EF
$map = [
‘EMPLOYEE ONLY’ => ‘EO’,
‘EMPLOYEE+SPOUSE’ => ‘ES’,
‘EMPLOYEE + SPOUSE’ => ‘ES’,
‘EMPLOYEE+CHILD’ => ‘EC’,
‘EMPLOYEE + CHILD’ => ‘EC’,
‘EMPLOYEE+CHILDREN’ => ‘EC’,
‘EMPLOYEE + CHILDREN’=> ‘EC’,
‘EMPLOYEE+FAMILY’ => ‘EF’,
‘EMPLOYEE + FAMILY’ => ‘EF’,
];
$tier = $map[$raw] ?? $raw;
if (in_array($tier, [‘EO’,’ES’,’EC’,’EF’], true)) {
$counts[$tier] += 1;
$counts[‘TOTAL’] += 1;
}
}
fclose($fh);
return $counts;
}

private static function header_counts($c){
if(!$c) return ”;
$parts=[]; foreach([‘EO’,’ES’,’EC’,’EF’] as $t){ $parts[]=$t.’ ‘.intval($c[$t]); }
$parts[]=’Total ‘.intval($c[‘TOTAL’]);
return ‘<div style=”font-size:12px;opacity:.8;margin:.25rem 0″>Counts: ‘.implode(‘ | ‘,$parts).'</div>’;
}

public static function market($atts){
$a = shortcode_atts([
‘plans’ => ”,
‘rate_set’ => ”,
‘area’ => ‘1’,
‘sheet’ => ‘SxS_FLAT’,
// meta fields (all optional)
’employer’ => ”,
‘county’ => ”,
‘broker_name’ => ”,
‘broker_agency’ => ”,
‘broker_email’ => ”,
‘broker_phone’ => ”,
‘broker_website’ => ”,
‘disclaimer’ => ”,
// derive amounts (optional anchors)
‘known_plan’ => ”,
‘known_eo’ => ”,
], $atts);
$rate_set_id=STQ_Calc::rate_set_id($a[‘rate_set’]); $area=intval($a[‘area’]);
$plans=STQ_Calc::get_plans($rate_set_id,$area,null);
$rate21=STQ_Calc::rate21($rate_set_id,$area);
$amounts=[]; if($a[‘known_plan’] && $a[‘known_eo’]!==”) $amounts=STQ_Calc::derive_amounts($a[‘known_plan’], floatval($a[‘known_eo’]), $rate21);

// allow preview counts from a freshly uploaded census (safe)
$counts=self::parse_counts_from_upload();

ob_start();
echo ‘<form method=”post” enctype=”multipart/form-data” style=”margin:0 0 1rem 0″><label>Optional census CSV: <input type=”file” name=”stq_census” accept=”.csv”></label> <button class=”button”>Apply Counts</button></form>’;
if($counts) echo self::header_counts($counts);

echo ‘<div style=”overflow:auto”><table class=”widefat striped”>’;
$hdrs=[“Carrier”,”Plan #”,”Plan Name”,”Funding”,”Tier”,”Network Name”,”Network Type”,”Plan Type”,”Deductible – Individual”,”Deductible – Family”,”Coinsurance – Member”,”Coinsurance – Plan”,”Out-of-Pocket – Individual”,”Out-of-Pocket – Family”,”Virtual Visits”,”PCP <19″,”Primary”,”Specialist”,”Prescriptions”,”EO”,”ES”,”EC”,”EF”,”Total”];
if($counts){ $hdrs[19]=’EO (‘.$counts[‘EO’].’)’;$hdrs[20]=’ES (‘.$counts[‘ES’].’)’;$hdrs[21]=’EC (‘.$counts[‘EC’].’)’;$hdrs[22]=’EF (‘.$counts[‘EF’].’)’;$hdrs[23]=’Total (‘.$counts[‘TOTAL’].’)’;}
echo ‘<thead><tr>’; foreach($hdrs as $h){ echo ‘<th>’.esc_html($h).'</th>’; } echo ‘</tr></thead><tbody>’;

foreach($plans as $p){
$b=STQ_Calc::benefits($p[‘carrier’],$p[‘plan_code’]);
echo ‘<tr>’;
echo ‘<td>’.esc_html($p[‘carrier’]).'</td>’;
echo ‘<td>’.esc_html($p[‘plan_code’]).'</td>’;
echo ‘<td>’.esc_html($p[‘marketing_name’]).'</td>’;
echo ‘<td>’.esc_html($p[‘funding’]).'</td>’;
echo ‘<td>’.esc_html($p[‘metal’]).'</td>’;
echo ‘<td>’.esc_html($p[‘network_name’]).'</td>’;
echo ‘<td>’.esc_html($p[‘network_type’]).'</td>’;
echo ‘<td>’.esc_html($p[‘plan_type’]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘deductible_individual’]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘deductible_family’]).'</td>’;
echo ‘<td>’.self::fmt_coins($b[‘coinsurance_member’]).'</td>’;
echo ‘<td>’.self::fmt_coins($b[‘coinsurance_plan’]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘oop_individual’]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘oop_family’]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘virtual_visits’]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘pcp_under19′]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘primary_adult’]).'</td>’;
echo ‘<td>’.self::fmt_benefit($b[‘specialist’]).'</td>’;
echo ‘<td>’.esc_html($b[‘rx_string’]).'</td>’;
if(isset($amounts[$p[‘plan_code’]])){
echo ‘<td>’.STQ_Format::plain_money($amounts[$p[‘plan_code’]][‘EO’]).'</td>’;
echo ‘<td>’.STQ_Format::plain_money($amounts[$p[‘plan_code’]][‘ES’]).'</td>’;
echo ‘<td>’.STQ_Format::plain_money($amounts[$p[‘plan_code’]][‘EC’]).'</td>’;
echo ‘<td>’.STQ_Format::plain_money($amounts[$p[‘plan_code’]][‘EF’]).'</td>’;
echo ‘<td>’.STQ_Format::plain_money(array_sum($amounts[$p[‘plan_code’]])).'</td>’;
} else { echo ‘<td></td><td></td><td></td><td></td><td></td>’; }
echo ‘</tr>’;
}
echo ‘</tbody></table></div>’;

return ob_get_clean();
}

/* ===== START:

 
Plan #
Plan Name
Network Name
Network Type
Plan Type
Deductible - Individual
Deductible - Family
Coinsurance - Member
Coinsurance - Plan
Out-of-Pocket - Individual
Out-of-Pocket - Family
Virtual Visits
PCP <19
Primary
Specialist
Urgent Care
Emergency
Lab/X-Ray
Imaging
Inpatient Services
Outpatient Surgery
Prescriptions
OON Deductible (Individual/Family)
OON Coinsurance (Member)
OON Out-of-Pocket (Individual/Family)
— census-aware renderer ===== */
public static function compare($atts){
$a = shortcode_atts([
‘plans’ => ”,
‘rate_set’ => ”,
‘area’ => ‘1’,
‘sheet’ => ”,
‘fast_strip’ => ‘0’,
‘stream’ => ‘0’,
‘drop_names’ => ‘0’,
‘dry_save’ => ‘0’,
‘nocache’ => ‘0’,

// optional meta (forwarded if present)
’employer’ => ”,
‘county’ => ”,
‘effective’ => ”,
‘rate_style’ => ”,
‘how’ => ”,
‘renewal_carrier’ => ”,
‘renewal_plan’ => ”,
‘renewal_eo’ => ”,
‘cnt_eo’ => ”,
‘cnt_es’ => ”,
‘cnt_ec’ => ”,
‘cnt_ef’ => ”,

// NEW: persisted census file path (absolute on server)
‘census_path’ => ”,

// broker/meta
‘broker_name’ => ”,
‘broker_agency’ => ”,
‘broker_email’ => ”,
‘broker_phone’ => ”,
‘broker_website’ => ”,
‘disclaimer’ => ”,
], $atts);

$plan_list = array_filter(array_map(‘trim’, explode(‘,’, $a[‘plans’])));

// —– Load plan columns (benefits + plan meta)
global $wpdb; $cols=[];
foreach($plan_list as $pc){
$p=$wpdb->get_row($wpdb->prepare(“SELECT * FROM {$wpdb->prefix}stq_plans WHERE year=%d AND plan_code=%s”,2025,$pc),ARRAY_A);
if(!$p) continue; $b=STQ_Calc::benefits($p[‘carrier’],$pc); $cols[$pc]=[‘plan’=>$p,’benefits’=>$b];
}

// —– Compute composite rates if we have an anchor (renewal EO or census file)
$amounts = []; // plan_code => [‘EO’=>..,’ES’=>..,’EC’=>..,’EF’=>..]
$rate_set_id = STQ_Calc::rate_set_id($a[‘rate_set’]);
$area = intval($a[‘area’]);

// Priority 1: explicit renewal EO
$renewalEO = is_numeric($a[‘renewal_eo’]) ? floatval($a[‘renewal_eo’]) : 0.0;
if ($renewalEO > 0 && !empty($plan_list)) {
$anchor = !empty($a[‘renewal_plan’]) ? $a[‘renewal_plan’] : $plan_list[0];
$r21map = STQ_Calc::rate21($rate_set_id, $area);
if (isset($r21map[$anchor]) && $r21map[$anchor] > 0) {
$amounts = STQ_Calc::derive_amounts($anchor, $renewalEO, $r21map);
}
}
// Priority 2: census anchor (if no renewal EO-derived amounts)
if (empty($amounts) && !empty($a[‘census_path’]) && is_readable($a[‘census_path’]) && !empty($plan_list)) {
$res = STQ_Calc::anchor_from_census_file(
$rate_set_id,
$area,
$plan_list,
$a[‘census_path’],
$a[‘effective’] ?: ”
);
if (!empty($res[‘amounts’]) && is_array($res[‘amounts’])) {
$amounts = $res[‘amounts’];
}
}

// Helper to compute group totals if counts present
$cntEO = intval($a[‘cnt_eo’] ?: 0);
$cntES = intval($a[‘cnt_es’] ?: 0);
$cntEC = intval($a[‘cnt_ec’] ?: 0);
$cntEF = intval($a[‘cnt_ef’] ?: 0);
$haveCounts = ($cntEO+$cntES+$cntEC+$cntEF) > 0;

ob_start();
echo ‘<div style=”overflow:auto”><table class=”widefat striped”><thead><tr><th>&nbsp;</th>’;
foreach($cols as $pc=>$col){ echo ‘<th>’.esc_html($pc.’ — ‘.$col[‘plan’][‘marketing_name’]).'</th>’; }
echo ‘</tr></thead><tbody>’;

$rows=[
‘Plan #’ => function($c,$pc){return esc_html($pc);},
‘Plan Name’ => function($c){return esc_html($c[‘plan’][‘marketing_name’]);},
‘Network Name’ => function($c){return esc_html($c[‘plan’][‘network_name’]);},
‘Network Type’ => function($c){return esc_html($c[‘plan’][‘network_type’]);},
‘Plan Type’ => function($c){return esc_html($c[‘plan’][‘plan_type’]);},
‘Deductible – Individual’ => function($c){return STQ_Format::money($c[‘benefits’][‘deductible_individual’]);},
‘Deductible – Family’ => function($c){return STQ_Format::money($c[‘benefits’][‘deductible_family’]);},
‘Coinsurance – Member’ => function($c){return STQ_Format::coins($c[‘benefits’][‘coinsurance_member’]);},
‘Coinsurance – Plan’ => function($c){return STQ_Format::coins($c[‘benefits’][‘coinsurance_plan’]);},
‘Out-of-Pocket – Individual’ => function($c){return STQ_Format::money($c[‘benefits’][‘oop_individual’]);},
‘Out-of-Pocket – Family’ => function($c){return STQ_Format::money($c[‘benefits’][‘oop_family’]);},
‘Virtual Visits’ => function($c){return STQ_Format::money($c[‘benefits’][‘virtual_visits’]);},
‘PCP <19’ => function($c){return STQ_Format::money($c[‘benefits’][‘pcp_under19’]);},
‘Primary’ => function($c){return STQ_Format::money($c[‘benefits’][‘primary_adult’]);},
‘Specialist’ => function($c){return STQ_Format::money($c[‘benefits’][‘specialist’]);},
‘Urgent Care’ => function($c){return STQ_Format::money($c[‘benefits’][‘urgent_care’]);},
‘Emergency’ => function($c){return STQ_Format::money($c[‘benefits’][’emergency’]);},
‘Lab/X-Ray’ => function($c){return STQ_Format::money($c[‘benefits’][‘lab_xray’]);},
‘Imaging’ => function($c){return STQ_Format::money($c[‘benefits’][‘imaging’]);},
‘Inpatient Services’ => function($c){return STQ_Format::money($c[‘benefits’][‘inpatient’]);},
‘Outpatient Surgery’ => function($c){return STQ_Format::money($c[‘benefits’][‘outpatient_surgery’]);},
‘Prescriptions’ => function($c){return esc_html($c[‘benefits’][‘rx_string’]);},
‘OON Deductible (Individual/Family)’ => function($c){
return STQ_Format::na_if_oonsuppressed_pair(
$c[‘benefits’][‘oon_ded_individual’] ?? ”,
$c[‘benefits’][‘oon_ded_family’] ?? ”,
$c[‘plan’][‘network_type’]
);
},
‘OON Coinsurance (Member)’ => function($c){
return STQ_Format::na_if_oonsuppressed_coins(
$c[‘benefits’][‘oon_coins_member’] ?? ”,
$c[‘plan’][‘network_type’]
);
},
‘OON Out-of-Pocket (Individual/Family)’ => function($c){
return STQ_Format::na_if_oonsuppressed_pair(
$c[‘benefits’][‘oon_oop_individual’] ?? ”,
$c[‘benefits’][‘oon_oop_family’] ?? ”,
$c[‘plan’][‘network_type’]
);
},
];

if (!empty($amounts)) {
$rows[‘Monthly Rate — EO’] = function($c,$pc) use ($amounts){ return isset($amounts[$pc][‘EO’]) ? STQ_Format::plain_money($amounts[$pc][‘EO’]) : ”; };
$rows[‘Monthly Rate — ES’] = function($c,$pc) use ($amounts){ return isset($amounts[$pc][‘ES’]) ? STQ_Format::plain_money($amounts[$pc][‘ES’]) : ”; };
$rows[‘Monthly Rate — EC’] = function($c,$pc) use ($amounts){ return isset($amounts[$pc][‘EC’]) ? STQ_Format::plain_money($amounts[$pc][‘EC’]) : ”; };
$rows[‘Monthly Rate — EF’] = function($c,$pc) use ($amounts){ return isset($amounts[$pc][‘EF’]) ? STQ_Format::plain_money($amounts[$pc][‘EF’]) : ”; };
if ($haveCounts) {
$rows[‘Monthly Total (group)’] = function($c,$pc) use ($amounts,$cntEO,$cntES,$cntEC,$cntEF){
if (empty($amounts[$pc])) return ”;
$m = $amounts[$pc];
$tot = ($m[‘EO’]*$cntEO) + ($m[‘ES’]*$cntES) + ($m[‘EC’]*$cntEC) + ($m[‘EF’]*$cntEF);
return STQ_Format::plain_money($tot);
};
}
}

foreach($rows as $label=>$fn){
echo ‘<tr><th>’.esc_html($label).'</th>’;
foreach($cols as $pc=>$col){ echo ‘<td>’.$fn($col,$pc).'</td>’; }
echo ‘</tr>’;
}

echo ‘</tbody></table></div>’;

/* ===== Export buttons ===== */
$final_plans = array_keys($cols);
if (!empty($final_plans)) {
$plans_csv = implode(‘,’, $final_plans);
$export_nonce = wp_create_nonce(‘stq_export_compare’);
$post_url = admin_url(‘admin-post.php’);

$hiddenMeta = function() use ($a, $plans_csv, $export_nonce) {
$h = ‘<input type=”hidden” name=”plans” value=”‘.esc_attr($plans_csv).'”>’;
$h .= ‘<input type=”hidden” name=”rate_set” value=”‘.esc_attr($a[‘rate_set’]).'”>’;
$h .= ‘<input type=”hidden” name=”area” value=”‘.esc_attr($a[‘area’]).'”>’;
if (!empty($a[‘sheet’])) {
$h .= ‘<input type=”hidden” name=”sheet” value=”‘.esc_attr($a[‘sheet’]).'”>’;
}
if (!empty($a[‘effective’])) {
$h .= ‘<input type=”hidden” name=”effective” value=”‘.esc_attr($a[‘effective’]).'”>’;
}
$h .= ‘<input type=”hidden” name=”_stq_export_nonce” value=”‘.esc_attr($export_nonce).'”>’;

foreach ([
’employer’,’county’,’effective’,’rate_style’,
‘how’,’renewal_carrier’,’renewal_plan’,’renewal_eo’,
‘cnt_eo’,’cnt_es’,’cnt_ec’,’cnt_ef’,
‘broker_name’,’broker_agency’,’broker_email’,’broker_phone’,’broker_website’,’disclaimer’,
‘census_path’
] as $k) {
if (isset($a[$k]) && $a[$k] !== ”) {
$h .= ‘<input type=”hidden” name=”‘.esc_attr($k).'” value=”‘.esc_attr($a[$k]).'”>’;
}
}

if ($a[‘fast_strip’] === ‘1’) $h .= ‘<input type=”hidden” name=”fast_strip” value=”1″>’;
if ($a[‘stream’] === ‘1’) $h .= ‘<input type=”hidden” name=”stream” value=”1″>’;
if ($a[‘drop_names’] === ‘1’) $h .= ‘<input type=”hidden” name=”drop_names” value=”1″>’;
if ($a[‘dry_save’] === ‘1’) $h .= ‘<input type=”hidden” name=”dry_save” value=”1″>’;
if ($a[‘nocache’] === ‘1’) $h .= ‘<input type=”hidden” name=”nocache” value=”1″>’;

return $h;
};

echo ‘<div style=”margin:12px 0; display:flex; gap:8px; flex-wrap:wrap;”>’;

echo ‘<form method=”post” action=”‘.esc_url($post_url).'”>’;
echo ‘<input type=”hidden” name=”action” value=”stq_export_compare_xlsx”>’;
echo $hiddenMeta();
echo ‘<button class=”button button-primary” type=”submit”>Download Excel</button>’;
echo ‘</form>’;

echo ‘<form method=”post” action=”‘.esc_url($post_url).'”>’;
echo ‘<input type=”hidden” name=”action” value=”stq_export_compare_pdf”>’;
echo $hiddenMeta();
echo ‘<button class=”button” type=”submit”>Download PDF</button>’;
echo ‘</form>’;

echo ‘<form method=”post” action=”‘.esc_url($post_url).'”>’;
echo ‘<input type=”hidden” name=”action” value=”stq_export_compare_html”>’;
echo $hiddenMeta();
echo ‘<button class=”button” type=”submit”>Download HTML</button>’;
echo ‘</form>’;

echo ‘<form method=”post” action=”‘.esc_url($post_url).'”>’;
echo ‘<input type=”hidden” name=”action” value=”stq_save_case”>’;
echo ‘<input type=”hidden” name=”_stq_save_case_nonce” value=”‘.esc_attr(wp_create_nonce(‘stq_save_case’)).'”>’;
echo $hiddenMeta();
echo ‘<button class=”button” type=”submit”>Save Quote</button>’;
echo ‘</form>’;

echo ‘</div>’;
}

return ob_get_clean();
}
/* ===== END:

 
Plan #
Plan Name
Network Name
Network Type
Plan Type
Deductible - Individual
Deductible - Family
Coinsurance - Member
Coinsurance - Plan
Out-of-Pocket - Individual
Out-of-Pocket - Family
Virtual Visits
PCP <19
Primary
Specialist
Urgent Care
Emergency
Lab/X-Ray
Imaging
Inpatient Services
Outpatient Surgery
Prescriptions
OON Deductible (Individual/Family)
OON Coinsurance (Member)
OON Out-of-Pocket (Individual/Family)
===== */

/* ===== compare_picker — saves census + forwards to

 
Plan #
Plan Name
Network Name
Network Type
Plan Type
Deductible - Individual
Deductible - Family
Coinsurance - Member
Coinsurance - Plan
Out-of-Pocket - Individual
Out-of-Pocket - Family
Virtual Visits
PCP <19
Primary
Specialist
Urgent Care
Emergency
Lab/X-Ray
Imaging
Inpatient Services
Outpatient Surgery
Prescriptions
OON Deductible (Individual/Family)
OON Coinsurance (Member)
OON Out-of-Pocket (Individual/Family)
===== */
public static function compare_picker($atts){
$a = shortcode_atts([
‘rate_set’ => ”,
‘area’ => ‘1’,
‘max_cols’ => ‘6’,
‘choose_for_me’ => ”,
‘bucket’ => ”,
‘anchor_plan’ => ”,
‘balance_by’ => ‘carrier’,
‘sheet’ => ”,
], $atts);

$rate_set_id = STQ_Calc::rate_set_id($a[‘rate_set’]);
$area = intval($a[‘area’]);
$max_cols = max(2, intval($a[‘max_cols’]));

// Persist census upload exactly once (to /stq-data/census)
$saved_census_path = ”;
if (!empty($_FILES[‘stq_census’][‘tmp_name’]) && is_uploaded_file($_FILES[‘stq_census’][‘tmp_name’])) {
$upload = function_exists(‘wp_get_upload_dir’) ? wp_get_upload_dir() : [‘basedir’=>WP_CONTENT_DIR.’/uploads’];
$base = rtrim($upload[‘basedir’],’/\\’).’/stq-data/census’;
if (!is_dir($base)) @wp_mkdir_p($base);
$fname = ‘census-‘.date(‘Ymd-His’).’-‘.wp_generate_password(6, false, false).’.csv’;
$dest = $base.’/’.$fname;
if (@move_uploaded_file($_FILES[‘stq_census’][‘tmp_name’], $dest)) {
@chmod($dest, 0644);
$saved_census_path = $dest;
}
}
// Prefer a previously forwarded census_path if present
$census_path = isset($_POST[‘census_path’]) && $_POST[‘census_path’] !== ”
? sanitize_text_field($_POST[‘census_path’])
: $saved_census_path;

global $wpdb;
$carriers=$wpdb->get_col($wpdb->prepare(
“SELECT DISTINCT carrier FROM {$wpdb->prefix}stq_plan_rates WHERE rate_set_id=%d AND rating_area_id=%d ORDER BY carrier”,
$rate_set_id,$area
));
$plans_by_c=[];
foreach($carriers as $c){
$rows=$wpdb->get_results($wpdb->prepare(
“SELECT r.plan_code, p.marketing_name
FROM {$wpdb->prefix}stq_plan_rates r
JOIN {$wpdb->prefix}stq_plans p
ON p.year=%d AND p.carrier=r.carrier AND p.plan_code=r.plan_code
WHERE r.rate_set_id=%d AND r.rating_area_id=%d AND r.carrier=%s
ORDER BY CAST(SUBSTRING(r.plan_code,2) AS UNSIGNED) ASC”,
2025,$rate_set_id,$area,$c
),ARRAY_A);
$plans_by_c[$c]=$rows;
}

// Prefill via Compare Picker Plus (if available)
$prefill = [];
$chooseN = intval($a[‘choose_for_me’]);
$bucket = sanitize_text_field($a[‘bucket’]);
$anchor = sanitize_text_field($a[‘anchor_plan’]);
$balance = sanitize_text_field($a[‘balance_by’]);

if ($chooseN > 0 && $bucket && class_exists(‘STQ_Compare_Picker_Plus’) && method_exists(‘STQ_Compare_Picker_Plus’,’auto_select’)) {
$picked = STQ_Compare_Picker_Plus::auto_select([
‘count’ => $chooseN,
‘bucket’ => $bucket,
‘rating_area_id’ => $area,
‘rate_set’ => $a[‘rate_set’],
‘anchor_plan’ => $anchor,
‘balance_by’ => $balance ?: ‘carrier’,
]);
if (!empty($picked)) {
$prefill = array_slice(array_values(array_unique($picked)), 0, $max_cols);
}
}

ob_start(); ?>
<div class=”stq-compare-picker-root”>
<form method=”post”>
<?php if ($census_path): ?>
<div style=”font-size:12px;opacity:.8;margin-bottom:8px;”>Census attached ✓</div>
<?php endif; ?>
<div style=”display:flex;gap:12px;flex-wrap:wrap;”>
<?php for($i=0;$i<$max_cols;$i++): ?>
<div style=”min-width:260px;border:1px solid #ddd;padding:8px;border-radius:8px;”>
<div><label>Carrier<br>
<select name=”carrier[]” class=”stq-carrier” data-slot=”<?php echo $i; ?>”>
<option value=””>— Select Carrier —</option>
<?php foreach($carriers as $c): ?>
<option value=”<?php echo esc_attr($c); ?>”><?php echo esc_html($c); ?></option>
<?php endforeach; ?>
</select></label>
</div>
<div style=”margin-top:6px;”><label>Plan<br>
<select name=”plan_code[]” class=”stq-plan” data-slot=”<?php echo $i; ?>”>
<option value=””>— Select Plan —</option>
</select></label>
</div>
</div>
<?php endfor; ?>
</div>
<div style=”margin-top:10px;”>
<button class=”button button-primary” name=”stq_compare_submit” value=”1″>Compare</button>
</div>

<!– meta forwarded from intake (if present) –>
<input type=”hidden” name=”employer” value=”<?php echo esc_attr($_POST[’employer’] ?? ”); ?>”>
<input type=”hidden” name=”county” value=”<?php echo esc_attr($_POST[‘county’] ?? ”); ?>”>
<input type=”hidden” name=”sheet” value=”<?php echo esc_attr($a[‘sheet’]); ?>”>

<!– ensure rate_set/area are present even if picker is used standalone –>
<input type=”hidden” name=”rate_set” value=”<?php echo esc_attr($_POST[‘rate_set’] ?? $a[‘rate_set’]); ?>”>
<input type=”hidden” name=”area” value=”<?php echo esc_attr($_POST[‘area’] ?? $a[‘area’]); ?>”>

<!– new fields carried from intake –>
<input type=”hidden” name=”effective” value=”<?php echo esc_attr($_POST[‘effective’] ?? ”); ?>”>
<input type=”hidden” name=”rate_style” value=”<?php echo esc_attr($_POST[‘rate_style’] ?? ”); ?>”>
<input type=”hidden” name=”how” value=”<?php echo esc_attr($_POST[‘how’] ?? ”); ?>”>
<input type=”hidden” name=”renewal_carrier” value=”<?php echo esc_attr($_POST[‘renewal_carrier’] ?? ”); ?>”>
<input type=”hidden” name=”renewal_plan” value=”<?php echo esc_attr($_POST[‘renewal_plan’] ?? ”); ?>”>
<input type=”hidden” name=”renewal_eo” value=”<?php echo esc_attr($_POST[‘renewal_eo’] ?? ”); ?>”>
<input type=”hidden” name=”cnt_eo” value=”<?php echo esc_attr($_POST[‘cnt_eo’] ?? ”); ?>”>
<input type=”hidden” name=”cnt_es” value=”<?php echo esc_attr($_POST[‘cnt_es’] ?? ”); ?>”>
<input type=”hidden” name=”cnt_ec” value=”<?php echo esc_attr($_POST[‘cnt_ec’] ?? ”); ?>”>
<input type=”hidden” name=”cnt_ef” value=”<?php echo esc_attr($_POST[‘cnt_ef’] ?? ”); ?>”>
<!– NEW: forward persisted census path –>
<input type=”hidden” name=”census_path” value=”<?php echo esc_attr($census_path); ?>”>
</form>
</div>

<script>(function(){
const M=<?php echo json_encode($plans_by_c); ?>;

function fill(slot,carrier){
const sel=document.querySelector(‘.stq-plan[data-slot=”‘+slot+'”]’);
if(!sel) return;
sel.innerHTML='<option value=””><?php echo esc_js(‘— Select Plan —’); ?></option>’;
if(!carrier||!M[carrier]) return;
M[carrier].forEach(function(p){
const opt=document.createElement(‘option’); opt.value=p.plan_code; opt.textContent=p.marketing_name; sel.appendChild(opt);
});
}
document.querySelectorAll(‘.stq-carrier’).forEach(function(c){
c.addEventListener(‘change’,function(){ fill(c.getAttribute(‘data-slot’),c.value); });
});

const PLAN2CARRIER = {};
Object.keys(M).forEach(function(carrier){
(M[carrier]||[]).forEach(function(p){ PLAN2CARRIER[p.plan_code]=carrier; });
});

const PREFILL = <?php echo json_encode(array_values($prefill)); ?>;
if (Array.isArray(PREFILL) && PREFILL.length){
PREFILL.forEach(function(code, idx){
const slot = idx;
const carrier = PLAN2CARRIER[code] || ”;
const carrierSel = document.querySelector(‘.stq-carrier[data-slot=”‘+slot+'”]’);
if (!carrierSel || !carrier) return;
carrierSel.value = carrier;
fill(slot, carrier);
const planSel = document.querySelector(‘.stq-plan[data-slot=”‘+slot+'”]’);
if (planSel){ planSel.value = code; }
});
}
})();</script>
<?php
if($_SERVER[‘REQUEST_METHOD’]===’POST’ && isset($_POST[‘stq_compare_submit’])){
$plans=isset($_POST[‘plan_code’])?array_filter(array_map(‘sanitize_text_field’,(array)$_POST[‘plan_code’])):[];
if(!empty($plans)){
$employer = isset($_POST[’employer’]) ? sanitize_text_field($_POST[’employer’]) : ”;
$county = isset($_POST[‘county’]) ? sanitize_text_field($_POST[‘county’]) : ”;
$rate_set = isset($_POST[‘rate_set’]) ? sanitize_text_field($_POST[‘rate_set’]) : (isset($a[‘rate_set’]) ? $a[‘rate_set’] : ”);
$area = isset($_POST[‘area’]) ? intval($_POST[‘area’]) : (isset($a[‘area’]) ? intval($a[‘area’]) : 1);
$effective = isset($_POST[‘effective’]) ? sanitize_text_field($_POST[‘effective’]) : ”;
$census_path = isset($_POST[‘census_path’]) ? sanitize_text_field($_POST[‘census_path’]) : ”;

$sc = ‘

 
Plan #
Plan Name
Network Name
Network Type
Plan Type
Deductible - Individual
Deductible - Family
Coinsurance - Member
Coinsurance - Plan
Out-of-Pocket - Individual
Out-of-Pocket - Family
Virtual Visits
PCP <19
Primary
Specialist
Urgent Care
Emergency
Lab/X-Ray
Imaging
Inpatient Services
Outpatient Surgery
Prescriptions
OON Deductible (Individual/Family)
OON Coinsurance (Member)
OON Out-of-Pocket (Individual/Family)
) ? ‘ sheet=”‘.esc_attr($a[‘sheet’]).'”‘ : ”).
($effective!==” ? ‘ effective=”‘.esc_attr($effective).'”‘ : ”).
(isset($_POST[‘rate_style’]) && $_POST[‘rate_style’]!==”
? ‘ rate_style=”‘.esc_attr(sanitize_text_field($_POST[‘rate_style’])).'”‘
: ”).
($employer!==” ? ‘ employer=”‘.esc_attr($employer).'”‘ : ”).
($county!==” ? ‘ county=”‘.esc_attr($county).'”‘ : ”).
(isset($_POST[‘how’]) && $_POST[‘how’]!==” ? ‘ how=”‘.esc_attr(sanitize_text_field($_POST[‘how’])).'”‘ : ”).
(isset($_POST[‘renewal_carrier’]) ? ‘ renewal_carrier=”‘.esc_attr(sanitize_text_field($_POST[‘renewal_carrier’])).'”‘ : ”).
(isset($_POST[‘renewal_plan’]) ? ‘ renewal_plan=”‘.esc_attr(sanitize_text_field($_POST[‘renewal_plan’])).'”‘ : ”).
(isset($_POST[‘renewal_eo’]) ? ‘ renewal_eo=”‘.esc_attr(sanitize_text_field($_POST[‘renewal_eo’])).'”‘ : ”).
(isset($_POST[‘cnt_eo’]) ? ‘ cnt_eo=”‘.esc_attr(sanitize_text_field($_POST[‘cnt_eo’])).'”‘ : ”).
(isset($_POST[‘cnt_es’]) ? ‘ cnt_es=”‘.esc_attr(sanitize_text_field($_POST[‘cnt_es’])).'”‘ : ”).
(isset($_POST[‘cnt_ec’]) ? ‘ cnt_ec=”‘.esc_attr(sanitize_text_field($_POST[‘cnt_ec’])).'”‘ : ”).
(isset($_POST[‘cnt_ef’]) ? ‘ cnt_ef=”‘.esc_attr(sanitize_text_field($_POST[‘cnt_ef’])).'”‘ : ”).
($census_path!==” ? ‘ census_path=”‘.esc_attr($census_path).'”‘ : ”).
‘]’;

echo do_shortcode($sc);
}
}
return ob_get_clean();
}
/* ===== /compare_picker ===== */

/* =====

(Only 1st or 15th of a month)
How do you want to quote?
Which option should I choose?

Quote from Renewal (Composite): Use when the employer has a fully-insured, composite-rated small group plan. No census is needed—enter the employee-only renewal rate for any plan they offer (it doesn’t have to be the current plan).

Quote from Census: Use for new groups, groups without a fully-insured plan (e.g., level-funded), or when you want age-rate detail on the side-by-side.

Both: Use when the group is composite-rated but the enrollment census has changed since the carrier issued renewal.

How is the group currently rated?
This is used to calculate the renewal increase; it doesn’t limit what you compare.
Current Plans (optional)
Add the group’s current plan(s) to enable auto-recommendations and current→renewal views.
— intake form + picker hand-off ===== */
public static function quote_intake($atts){
$a = shortcode_atts([
‘sheet’ => ‘SxS_FLAT’,
‘rate_set’ => ‘2025-Q1’,
], $atts);

/* ———- Load counties/areas from CSV (TX-only) ———- */
$COUNTY_OPTIONS = [];
$COUNTY_AREA_MAP = [];
try {
$upload = function_exists(‘wp_get_upload_dir’) ? wp_get_upload_dir() : [‘basedir’ => WP_CONTENT_DIR . ‘/uploads’];
$basedir = rtrim($upload[‘basedir’], ‘/\\’);
$candidates = [
$basedir . ‘/stq-data/county_areas_tx.csv’,
$basedir . ‘/stq-data/county_areas.csv’,
];
foreach ($candidates as $csvPath) {
if (!is_readable($csvPath)) continue;
if (($fh = fopen($csvPath, ‘r’)) === false) continue;
$hdr = fgetcsv($fh);
if (!$hdr) { fclose($fh); continue; }
$idx = array_change_key_case(array_flip($hdr), CASE_LOWER);
$col_county = $idx[‘county’] ?? null;
$col_area = $idx[‘area’] ?? $idx[‘rating area’] ?? $idx[‘rating_area’] ?? null;
if ($col_county === null || $col_area === null) { fclose($fh); continue; }

while (($row = fgetcsv($fh)) !== false) {
$co = trim((string)$row[$col_county]);
$ar = (int)trim((string)$row[$col_area]);
if ($co !== ” && $ar > 0) $COUNTY_AREA_MAP[$co] = $ar;
}
fclose($fh);
break;
}
} catch (\Throwable $e) { /* ignore */ }

if (empty($COUNTY_AREA_MAP)) {
$COUNTY_OPTIONS = apply_filters(‘stq_county_options’, []);
$COUNTY_AREA_MAP = apply_filters(‘stq_county_area_map’, []);
} else {
$COUNTY_OPTIONS = array_keys($COUNTY_AREA_MAP);
}

/* ———- Effective dates (1st/15th only) ———- */
$EFFECTIVE_OPTIONS = apply_filters(‘stq_effective_options’, []);
if (empty($EFFECTIVE_OPTIONS) && class_exists(‘STQ_Calc’) && method_exists(‘STQ_Calc’,’effective_options’)) {
$EFFECTIVE_OPTIONS = (array) STQ_Calc::effective_options();
}
if (empty($EFFECTIVE_OPTIONS)) {
$out = [];
$y = (int)date(‘Y’);
$m = (int)date(‘n’);
$q = intdiv(($m-1),3) + 1;
$qStartMonth = ($q-1)*3 + 1;
for ($i=0;$i<3;$i++) {
$mm = $qStartMonth + $i;
$out[] = sprintf(‘%04d-%02d-01’,$y,$mm);
$out[] = sprintf(‘%04d-%02d-15’,$y,$mm);
}
$nextQ = ($q==4)?1:$q+1;
$nextY = ($q==4)?$y+1:$y;
$nextQStartMonth = ($nextQ-1)*3 + 1;
$nextRateSet = sprintf(‘%04dQ%d’,$nextY,$nextQ);
if (class_exists(‘STQ_Calc’) && method_exists(‘STQ_Calc’,’rate_set_exists’) && STQ_Calc::rate_set_exists($nextRateSet)) {
for ($i=0;$i<3;$i++) {
$mm = $nextQStartMonth + $i;
$out[] = sprintf(‘%04d-%02d-01’,$nextY,$mm);
$out[] = sprintf(‘%04d-%02d-15’,$nextY,$mm);
}
}
$EFFECTIVE_OPTIONS = $out;
}

// TEMP: lock to 2025 Q1
$EFFECTIVE_OPTIONS = [
‘2025-01-01′,’2025-01-15’,
‘2025-02-01′,’2025-02-15’,
‘2025-03-01′,’2025-03-15’,
];

/* ———- Derivers ———- */
$rate_set_for_effective = function($effective, $defaultRS){
if (class_exists(‘STQ_Calc’) && method_exists(‘STQ_Calc’,’rate_set_for_effective’)) {
$rs = STQ_Calc::rate_set_for_effective($effective);
if (!empty($rs)) return $rs;
}
return $defaultRS;
};
$area_for = function($rate_set, $county) use ($COUNTY_AREA_MAP){
if (class_exists(‘STQ_Calc’) && method_exists(‘STQ_Calc’,’rating_area_for_county’)) {
$d = STQ_Calc::rating_area_for_county($rate_set, $county);
if (!empty($d)) return intval($d);
}
if ($county && isset($COUNTY_AREA_MAP[$county])) return intval($COUNTY_AREA_MAP[$county]);
return 1;
};

/* ———- Carriers & renewal plan list ———- */
$CARRIERS = [‘BCBSTX’=>’BCBSTX’,’BSW’=>’BSW’,’UHC’=>’UHC’,’MH’=>’Memorial Hermann (MH)’];
$plans_by_carrier = [];
if (class_exists(‘STQ_Calc’)) {
global $wpdb;
$rate_set_id = STQ_Calc::rate_set_id($a[‘rate_set’]);
$rows = $wpdb->get_results($wpdb->prepare(
“SELECT r.carrier, r.plan_code, p.marketing_name
FROM {$wpdb->prefix}stq_plan_rates r
JOIN {$wpdb->prefix}stq_plans p
ON p.year=%d AND p.carrier=r.carrier AND p.plan_code=r.plan_code
WHERE r.rate_set_id=%d
GROUP BY r.carrier, r.plan_code, p.marketing_name
ORDER BY r.carrier ASC, CAST(SUBSTRING(r.plan_code,2) AS UNSIGNED) ASC”,
2025, $rate_set_id
), ARRAY_A);
foreach ((array)$rows as $row){
$c = (string)$row[‘carrier’];
$plans_by_carrier[$c][] = [‘plan_code’=>$row[‘plan_code’], ‘marketing_name’=>$row[‘marketing_name’]];
}
}

/* ———- View labels → sheet ———- */
$VIEW_MAP = [
‘Side-by-side’ => ‘SxS_FLAT’,
‘Runtime (Lite)’ => ‘SxS_RUNTIME’,
];
$initial_view_label = array_search($a[‘sheet’], $VIEW_MAP, true);
if ($initial_view_label===false) $initial_view_label = ‘Side-by-side’;

/* ———- Handle submit ———- */
if ($_SERVER[‘REQUEST_METHOD’]===’POST’ && ( isset($_POST[‘stq_intake_submit’]) || isset($_POST[‘stq_compare_submit’]) )) {
$employer = sanitize_text_field($_POST[’employer’] ?? ”);
$state = strtoupper(sanitize_text_field($_POST[‘state’] ?? ($GLOBALS[‘__STQ_STATE_NOW__’] ?? ‘TX’)));
$county = sanitize_text_field($_POST[‘county’] ?? ”);
$effective = sanitize_text_field($_POST[‘effective’]?? ”);
$how = sanitize_text_field($_POST[‘how’] ?? ‘both’);
$rate_style = sanitize_text_field($_POST[‘rate_style’] ?? ‘composite’);
$sheetLbl = sanitize_text_field($_POST[‘sheet_label’] ?? $initial_view_label);
$sheet = $VIEW_MAP[$sheetLbl] ?? $a[‘sheet’];

$rate_set = $rate_set_for_effective($effective, $a[‘rate_set’]);
$map_by_state = $GLOBALS[‘__STQ_COUNTY_MAP_BY_STATE__’] ?? [];
$area = 1;
if (!empty($map_by_state[$state]) && !empty($map_by_state[$state][$county])) {
$area = intval($map_by_state[$state][$county]);
} else {
$area = $area_for($rate_set, $county);
}

// ===== Persist census upload ONCE and compute counts safely =====
$census_path = ”;
if (!empty($_FILES[‘stq_census’][‘tmp_name’]) && is_uploaded_file($_FILES[‘stq_census’][‘tmp_name’])) {
$upload = function_exists(‘wp_get_upload_dir’) ? wp_get_upload_dir() : [‘basedir’=>WP_CONTENT_DIR.’/uploads’];
$base = rtrim($upload[‘basedir’],’/\\’).’/stq-data/census’;
if (!is_dir($base)) @wp_mkdir_p($base);
$fn = ‘census-‘.date(‘Ymd-His’).’-‘.wp_generate_password(8,false,false).’.csv’;
$dest = $base.’/’.$fn;
if (@move_uploaded_file($_FILES[‘stq_census’][‘tmp_name’], $dest)) {
@chmod($dest, 0644);
$census_path = $dest;
}
}

// renewal (optional) + counts
$renewal = [
‘carrier’ => sanitize_text_field($_POST[‘renewal_carrier’] ?? ”),
‘plan’ => sanitize_text_field($_POST[‘renewal_plan’] ?? ”),
‘eo’ => floatval($_POST[‘renewal_eo’] ?? 0),
‘EO’ => intval($_POST[‘cnt_eo’] ?? 0),
‘ES’ => intval($_POST[‘cnt_es’] ?? 0),
‘EC’ => intval($_POST[‘cnt_ec’] ?? 0),
‘EF’ => intval($_POST[‘cnt_ef’] ?? 0),
];

// If we have a saved census, prefer its counts
$counts_from_csv = self::parse_counts_from_upload($census_path);
if (is_array($counts_from_csv) && !empty($counts_from_csv[‘TOTAL’])) {
$renewal[‘EO’] = intval($counts_from_csv[‘EO’] ?? $renewal[‘EO’]);
$renewal[‘ES’] = intval($counts_from_csv[‘ES’] ?? $renewal[‘ES’]);
$renewal[‘EC’] = intval($counts_from_csv[‘EC’] ?? $renewal[‘EC’]);
$renewal[‘EF’] = intval($counts_from_csv[‘EF’] ?? $renewal[‘EF’]);
}

echo ‘<div id=”stq-picker-anchor”></div>’;

// Confirmation strip
echo ‘<div style=”margin:8px 0 12px 0;padding:10px;border:1px solid #e5e7eb;border-radius:6px;background:#fafafa”>’;
echo ‘<div><strong>Employer:</strong> ‘.esc_html($employer ?: ‘(not set)’).'</div>’;
echo ‘<div><strong>Effective:</strong> ‘.esc_html($effective ?: ‘(not set)’).’ &nbsp; <strong>Area:</strong> ‘.esc_html($area ?: ‘(n/a)’).’ &nbsp; <strong>Rating:</strong> ‘.esc_html($rate_style ?: ‘(n/a)’).'</div>’;
if (!empty($renewal[‘EO’]) || !empty($renewal[‘ES’]) || !empty($renewal[‘EC’]) || !empty($renewal[‘EF’])) {
$tot = intval($renewal[‘EO’]) + intval($renewal[‘ES’]) + intval($renewal[‘EC’]) + intval($renewal[‘EF’]);
echo ‘<div style=”opacity:.9;margin-top:4px”>Counts → EO ‘.intval($renewal[‘EO’]).’ / ES ‘.intval($renewal[‘ES’]).’ / EC ‘.intval($renewal[‘EC’]).’ / EF ‘.intval($renewal[‘EF’]).’ &nbsp; (Total ‘.$tot.’)</div>’;
}
if ($census_path !== ”) {
echo ‘<div style=”opacity:.8;margin-top:4px;font-size:12px”>Census attached ✓</div>’;
}
echo ‘</div>’;

// Render the picker (passes effective + rate_style as before)
echo do_shortcode(


);
?>
<script>
// Inject hidden fields into the picker form
(function(){
function input(n,v){ const i=document.createElement(‘input’); i.type=’hidden’; i.name=n; i.value=v; return i; }
const btn = document.querySelector(‘button[name=”stq_compare_submit”]’);
if (!btn || !btn.form) return;
const f = btn.form;
f.appendChild(input(’employer’, <?php echo json_encode($employer); ?>));
f.appendChild(input(‘state’, <?php echo json_encode($state); ?>));
f.appendChild(input(‘county’, <?php echo json_encode($county); ?>));
f.appendChild(input(‘sheet’, <?php echo json_encode($sheet); ?>));
f.appendChild(input(‘rate_set’, <?php echo json_encode($rate_set); ?>));
f.appendChild(input(‘effective’, <?php echo json_encode($effective); ?>));
f.appendChild(input(‘area’, <?php echo json_encode($area); ?>));
f.appendChild(input(‘how’, <?php echo json_encode($how); ?>));
f.appendChild(input(‘rate_style’, <?php echo json_encode($rate_style); ?>));
f.appendChild(input(‘renewal_carrier’, <?php echo json_encode($renewal[‘carrier’]); ?>));
f.appendChild(input(‘renewal_plan’, <?php echo json_encode($renewal[‘plan’]); ?>));
f.appendChild(input(‘renewal_eo’, <?php echo json_encode($renewal[‘eo’]); ?>));
f.appendChild(input(‘cnt_eo’, <?php echo json_encode($renewal[‘EO’]); ?>));
f.appendChild(input(‘cnt_es’, <?php echo json_encode($renewal[‘ES’]); ?>));
f.appendChild(input(‘cnt_ec’, <?php echo json_encode($renewal[‘EC’]); ?>));
f.appendChild(input(‘cnt_ef’, <?php echo json_encode($renewal[‘EF’]); ?>));
// Pass the persisted census file (if any)
f.appendChild(input(‘census_path’, <?php echo json_encode($census_path); ?>));
})();
</script>
<?php
return ”;
}

/* ———- Render intake form ———- */
ob_start();
?>
<style>
.stq-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
.stq-card{border:1px solid #e2e4e7;padding:14px;border-radius:10px;margin:12px 0;}
.stq-row{display:grid;grid-template-columns:1fr 1fr;gap:12px;align-items:end;}
.stq-row-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;align-items:end;}
.stq-row-4{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;align-items:end;}
@media (max-width: 860px){
.stq-grid{grid-template-columns:1fr;}
.stq-row,.stq-row-3,.stq-row-4{grid-template-columns:1fr;}
}
.stq-wide input,.stq-wide select{width:100%;}
.stq-label{font-weight:600;margin-bottom:6px;display:block;}
.stq-muted{color:#6b7280;font-size:12px;margin-top:4px;}
.stq-btn-primary{background:#d7263d;color:#fff;border:none;border-radius:8px;padding:12px 18px;font-weight:700;cursor:pointer;}
.stq-radios{display:flex;gap:28px;align-items:center;flex-wrap:wrap;margin:6px 0 10px;}
.stq-radio{display:flex;gap:8px;align-items:center;}
.stq-radio span{white-space:nowrap;}
</style>

<form method=”post” enctype=”multipart/form-data” class=”stq-wide”>
<div class=”stq-grid”>
<div>
<label class=”stq-label”>Employer Name</label>
<input type=”text” name=”employer” placeholder=”Company Inc.” />
</div>
<div>
<label class=”stq-label”>Effective Date</label>
<select name=”effective”>
<?php foreach($EFFECTIVE_OPTIONS as $d): ?>
<option value=”<?php echo esc_attr($d); ?>”><?php echo esc_html(date(‘M j, Y’, strtotime($d))); ?></option>
<?php endforeach; ?>
</select>
<div class=”stq-muted”>(Only 1st or 15th of a month)</div>
</div>

<div>
<label class=”stq-label”>County</label>
<?php if (!empty($COUNTY_OPTIONS)): ?>
<select name=”county” id=”stq-county”>
<option value=””>— Select County —</option>
<?php foreach($COUNTY_OPTIONS as $co): ?>
<option value=”<?php echo esc_attr($co); ?>”><?php echo esc_html($co); ?></option>
<?php endforeach; ?>
</select>
<?php else: ?>
<input type=”text” id=”stq-county” name=”county” placeholder=”County” />
<?php endif; ?>
<div id=”stq-area-line” class=”stq-muted” style=”display:none;”>
Rating Area: <span id=”stq-area-val”></span>
</div>
<input type=”hidden” name=”stq_area” id=”stq-area-hidden” value=””>
</div>

<div>
<label class=”stq-label”>Initial View</label>
<select name=”sheet_label”>
<?php foreach($VIEW_MAP as $label=>$sheetName): ?>
<option value=”<?php echo esc_attr($label); ?>” <?php selected($label,$initial_view_label); ?>>
<?php echo esc_html($label); ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>

<div class=”stq-card”>
<div class=”stq-label”>How do you want to quote?</div>
<div class=”stq-radios”>
<label class=”stq-radio”><input type=”radio” name=”how” value=”renewal” /> <span>Renewal only (composite)</span></label>
<label class=”stq-radio”><input type=”radio” name=”how” value=”census” /> <span>Census only</span></label>
<label class=”stq-radio”><input type=”radio” name=”how” value=”both” checked /> <span>Both (renewal + census)</span></label>
</div>

<div class=”stq-muted” style=”margin-top:6px;”>
<details>
<summary style=”cursor:pointer;font-weight:600;”>Which option should I choose?</summary>
<div style=”margin-top:8px;line-height:1.45;”>
<p><strong>Quote from Renewal (Composite):</strong> Use when the employer has a fully-insured, composite-rated small group plan. No census is needed—enter the employee-only renewal rate for any plan they offer (it doesn’t have to be the current plan).</p>
<p><strong>Quote from Census:</strong> Use for new groups, groups without a fully-insured plan (e.g., level-funded), or when you want age-rate detail on the side-by-side.</p>
<p><strong>Both:</strong> Use when the group is composite-rated but the enrollment census has changed since the carrier issued renewal.</p>
</div>
</details>
</div>

<div class=”stq-label” style=”margin-top:12px;”><strong>How is the group currently rated?</strong></div>
<div class=”stq-radios” style=”margin-top:4px;”>
<label class=”stq-radio”>
<input type=”radio” name=”rate_style” value=”composite” checked />
<span>Composite (tiered)</span>
</label>
<label class=”stq-radio”>
<input type=”radio” name=”rate_style” value=”age” />
<span>Age-rated (per member)</span>
</label>
</div>
<div class=”stq-muted” style=”margin-top:4px;”>
This is used to calculate the renewal increase; it doesn’t limit what you compare.
</div>

<div id=”stq-census-row” style=”margin-top:6px; display:none;”>
<span class=”stq-label”>Optional Census CSV:</span>
<input type=”file” name=”stq_census” accept=”.csv”>
</div>
</div>

<div class=”stq-card” id=”stq-renewal-block”>
<div class=”stq-row-3″>
<div>
<label class=”stq-label”>Current Carrier</label>
<select name=”renewal_carrier” id=”stq-renewal-carrier”>
<option value=””>— Select Carrier —</option>
<?php foreach($CARRIERS as $key=>$label): ?>
<option value=”<?php echo esc_attr($key); ?>”><?php echo esc_html($label); ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label class=”stq-label”>Select Any Renewal Plan</label>
<select name=”renewal_plan” id=”stq-renewal-plan”>
<option value=””>— Select Plan —</option>
</select>
</div>
<div>
<label class=”stq-label”>Renewal EO Rate</label>
<input type=”number” step=”0.01″ name=”renewal_eo” placeholder=”e.g., 475.00″ />
</div>
</div>

<div class=”stq-row-4″ style=”margin-top:10px;”>
<div><label class=”stq-label”>EO Count</label><input type=”number” name=”cnt_eo” value=”0″ min=”0″ /></div>
<div><label class=”stq-label”>ES Count</label><input type=”number” name=”cnt_es” value=”0″ min=”0″ /></div>
<div><label class=”stq-label”>EC Count</label><input type=”number” name=”cnt_ec” value=”0″ min=”0″ /></div>
<div><label class=”stq-label”>EF Count</label><input type=”number” name=”cnt_ef” value=”0″ min=”0″ /></div>
</div>
</div>

<div style=”margin-top:12px;”>
<button class=”stq-btn-primary” type=”submit” name=”stq_intake_submit” value=”1″>NEXT: CHOOSE PLANS</button>
</div>
</form>

<script>
// County → Area preview + hidden (TX-only)
(function(){
const countyEl = document.getElementById(‘stq-county’);
const line = document.getElementById(‘stq-area-line’);
const out = document.getElementById(‘stq-area-val’);
const hidden = document.getElementById(‘stq-area-hidden’);
if (!countyEl) return;

const MAP = <?php echo json_encode($COUNTY_AREA_MAP ?: new stdClass()); ?>;

function updateArea(){
const co = countyEl.value || ”;
const area = MAP && MAP[co] ? MAP[co] : ”;
if (area){
line.style.display = ‘block’;
out.textContent = area;
hidden.value = area;
} else {
line.style.display = ‘none’;
out.textContent = ”;
hidden.value = ”;
}
}

countyEl.addEventListener(‘change’, updateArea);
updateArea();
})();

// Renewal plan dropdown depends on carrier
(function(){
const M = <?php echo json_encode($plans_by_carrier); ?>;
const cSel = document.getElementById(‘stq-renewal-carrier’);
const pSel = document.getElementById(‘stq-renewal-plan’);
function fill(){
if(!cSel||!pSel) return;
const c = cSel.value || ”;
pSel.innerHTML = ‘<option value=””>— Select Plan —</option>’;
if(!c || !M[c]) return;
M[c].forEach(function(row){
const opt=document.createElement(‘option’);
opt.value=row.plan_code; opt.textContent=row.marketing_name;
pSel.appendChild(opt);
});
}
if (cSel){ cSel.addEventListener(‘change’, fill); fill(); }
})();

// Radios: toggle renewal block & census row
(function(){
const renewalBlock = document.getElementById(‘stq-renewal-block’);
const censusRow = document.getElementById(‘stq-census-row’);
function update(){
const v = (document.querySelector(‘input[name=”how”]:checked’)||{}).value || ‘both’;
if (renewalBlock) renewalBlock.style.display = (v === ‘census’) ? ‘none’ : ‘block’;
if (censusRow) censusRow.style.display = (v === ‘census’ || v === ‘both’) ? ‘block’ : ‘none’;
}
document.querySelectorAll(‘input[name=”how”]’).forEach(r=>r.addEventListener(‘change’, update));
update();
})();
</script>
<?php
return ob_get_clean();
}
/* =====

(Only 1st or 15th of a month)
How do you want to quote?
Which option should I choose?

Quote from Renewal (Composite): Use when the employer has a fully-insured, composite-rated small group plan. No census is needed—enter the employee-only renewal rate for any plan they offer (it doesn’t have to be the current plan).

Quote from Census: Use for new groups, groups without a fully-insured plan (e.g., level-funded), or when you want age-rate detail on the side-by-side.

Both: Use when the group is composite-rated but the enrollment census has changed since the carrier issued renewal.

How is the group currently rated?
This is used to calculate the renewal increase; it doesn’t limit what you compare.
Current Plans (optional)
Add the group’s current plan(s) to enable auto-recommendations and current→renewal views.
— END ===== */

/* ===== STQ_Shortcodes::diag_benefits (diagnostic) ===== */
public static function diag_benefits($atts){
$a = shortcode_atts([‘carrier’=>”,’plan’=>”], $atts);
if (!$a[‘carrier’] || !$a[‘plan’]) {
return ‘<em>Provide carrier and plan, e.g.

BCBSTX B046 — G661ADT
BenefitValue
Deductible - Individual$2,100
Deductible - Family$6,300
Coinsurance - Member10%
Coinsurance - Plan90%
Out-of-Pocket - Individual$4,200
Out-of-Pocket - Family$12,600
Virtual VisitsDC
PCP <19DC
PrimaryDC
SpecialistDC
Urgent CareD&C
EmergencyD&C
Lab/X-RayD&C
ImagingD&C
Inpatient ServicesD&C
Outpatient SurgeryD&C
PrescriptionsDed, 10-10-20-30-40-50%
OON Deductible (Individual/Family)N/A
OON Coinsurance (Member)N/A
OON Out-of-Pocket (Individual/Family)N/A
</em>’;
}

$b = STQ_Calc::benefits($a[‘carrier’], $a[‘plan’]);
global $wpdb;
$p = $wpdb->get_row($wpdb->prepare(
“SELECT marketing_name, network_type FROM {$wpdb->prefix}stq_plans WHERE year=%d AND carrier=%s AND plan_code=%s”,
2025, $a[‘carrier’], $a[‘plan’]
), ARRAY_A);
$networkType = (string)($p[‘network_type’] ?? ”);
$marketingName = (string)($p[‘marketing_name’] ?? ”);

$fmt_money = function($val){
if ($val === ” || $val === null) return ”;
if ($val === ‘0’ || $val === 0 || $val === ‘$0’) return ‘$0’;
if (is_string($val) && preg_match(‘/[\$\%A-Za-z]/’, $val)) return (string)$val;
return STQ_Format::money($val);
};
$fmt_coins = function($val){
if ($val === ” || $val === null) return ”;
if (is_string($val) && strpos($val, ‘%’) !== false) return (string)$val;
return STQ_Format::coins($val);
};

ob_start();
echo ‘<div class=”stq-diag”>’;
echo ‘<div style=”margin-bottom:6px;”><strong>’.esc_html($a[‘carrier’].’ ‘.$a[‘plan’]).'</strong>’;
if ($marketingName) echo ‘ — ‘.esc_html($marketingName);
echo ‘</div>’;

echo ‘<table class=”widefat striped” style=”max-width:820px”>’;
echo ‘<thead><tr><th style=”width:45%;”>Benefit</th><th>Value</th></tr></thead><tbody>’;

$rows = [
‘Deductible – Individual’ => $fmt_money($b[‘deductible_individual’] ?? ”),
‘Deductible – Family’ => $fmt_money($b[‘deductible_family’] ?? ”),
‘Coinsurance – Member’ => $fmt_coins($b[‘coinsurance_member’] ?? ”),
‘Coinsurance – Plan’ => $fmt_coins($b[‘coinsurance_plan’] ?? ”),
‘Out-of-Pocket – Individual’ => $fmt_money($b[‘oop_individual’] ?? ”),
‘Out-of-Pocket – Family’ => $fmt_money($b[‘oop_family’] ?? ”),
‘Virtual Visits’ => $fmt_money($b[‘virtual_visits’] ?? ”),
‘PCP <19’ => $fmt_money($b[‘pcp_under19’] ?? ”),
‘Primary’ => $fmt_money($b[‘primary_adult’] ?? ”),
‘Specialist’ => $fmt_money($b[‘specialist’] ?? ”),
‘Urgent Care’ => $fmt_money($b[‘urgent_care’] ?? ”),
‘Emergency’ => $fmt_money($b[’emergency’] ?? ”),
‘Lab/X-Ray’ => $fmt_money($b[‘lab_xray’] ?? ”),
‘Imaging’ => $fmt_money($b[‘imaging’] ?? ”),
‘Inpatient Services’ => $fmt_money($b[‘inpatient’] ?? ”),
‘Outpatient Surgery’ => $fmt_money($b[‘outpatient_surgery’] ?? ”),
‘Prescriptions’ => (string)($b[‘rx_string’] ?? ”),
‘OON Deductible (Individual/Family)’ => STQ_Format::na_if_oonsuppressed_pair(
$b[‘oon_ded_individual’] ?? ”,
$b[‘oon_ded_family’] ?? ”,
$networkType
),
‘OON Coinsurance (Member)’ => STQ_Format::na_if_oonsuppressed_coins(
$b[‘oon_coins_member’] ?? ”,
$networkType
),
‘OON Out-of-Pocket (Individual/Family)’ => STQ_Format::na_if_oonsuppressed_pair(
$b[‘oon_oop_individual’] ?? ”,
$b[‘oon_oop_family’] ?? ”,
$networkType
),
];

foreach ($rows as $label => $val){
echo ‘<tr><th>’.esc_html($label).'</th><td>’.esc_html((string)$val).'</td></tr>’;
}

echo ‘</tbody></table></div>’;
return ob_get_clean();
}

}

STQ_Shortcodes::init();