<?php
require_once __DIR__ . '/admin_tool_helper.php';

if (!function_exists('e')) {
    function e($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
function admin_table_exists_local($table) {
    if (function_exists('admin_table_exists')) return admin_table_exists($table);
    try { $s=db()->prepare("SHOW TABLES LIKE ?"); $s->execute([$table]); return (bool)$s->fetchColumn(); } catch(Throwable $e){ return false; }
}
function admin_setting_get_local($key,$default='') {
    try { $s=db()->prepare("SELECT setting_value FROM system_settings WHERE setting_key=? LIMIT 1"); $s->execute([$key]); $v=$s->fetchColumn(); return $v!==false?(string)$v:$default; } catch(Throwable $e){ return $default; }
}
function admin_json_local($v){ if(!$v) return []; $d=json_decode((string)$v,true); return is_array($d)?$d:[]; }
function admin_clean($v,$fallback='N/A',$limit=150){ $t=trim(strip_tags(html_entity_decode((string)($v??''),ENT_QUOTES|ENT_HTML5,'UTF-8'))); $t=preg_replace('/\s+/',' ',$t); if($t==='') return $fallback; return $limit>0 && strlen($t)>$limit ? substr($t,0,$limit).'...' : $t; }
function admin_price($v){ if($v===null || $v==='' || !is_numeric($v)) return 'N/A'; $v=(float)$v; return abs($v)>=100?number_format($v,2):rtrim(rtrim(number_format($v,5),'0'),'.'); }
function admin_tf_code($tf){ $tf=strtolower(str_replace([' ','_'],'',trim((string)$tf))); $m=['m1'=>'1m','1m'=>'1m','m5'=>'5m','5m'=>'5m','m15'=>'15m','15m'=>'15m','m30'=>'30m','30m'=>'30m','h1'=>'1h','1h'=>'1h','h4'=>'4h','4h'=>'4h','d1'=>'1d','1d'=>'1d','w1'=>'1w','1w'=>'1w']; return $m[$tf]??$tf; }
function admin_tf_label($tf){ $tf=strtoupper(str_replace([' ','_'],'',trim((string)$tf))); $m=['M1'=>'1M','1M'=>'1M','M5'=>'5M','5M'=>'5M','M15'=>'15M','15M'=>'15M','M30'=>'30M','30M'=>'30M','H1'=>'1H','1H'=>'1H','H4'=>'4H','4H'=>'4H','D1'=>'1D','1D'=>'1D','W1'=>'1W','1W'=>'1W']; return $m[$tf]??($tf?:'N/A'); }
function admin_confirm_tf($setup){ $setup=admin_tf_code($setup); $cfg=trim(admin_setting_get_local('alert_confirmation_timeframe_map','')); if($cfg!==''){ $j=json_decode($cfg,true); if(is_array($j)&&isset($j[$setup])) return admin_tf_label($j[$setup]); foreach(explode(',',$cfg) as $pair){ $p=array_map('trim',explode(':',$pair,2)); if(count($p)===2 && admin_tf_code($p[0])===$setup) return admin_tf_label($p[1]); }} $d=['1m'=>'1m','5m'=>'1m','15m'=>'5m','30m'=>'5m','1h'=>'15m','4h'=>'1h','1d'=>'4h']; return admin_tf_label($d[$setup]??$setup); }
function admin_stage_label($s){ $s=strtoupper((string)$s); $m=['TRACKING'=>'Tracking','ZONE_APPROACHED'=>'Stage 1','LIQUIDITY_SWEPT'=>'Stage 2','STRUCTURE_CONFIRMED'=>'Stage 3','READY_TO_EXECUTE'=>'Ready','ALERT_SENT'=>'Sent','EXPIRED'=>'Expired','INVALIDATED'=>'Invalidated']; return $m[$s]??ucwords(strtolower(str_replace('_',' ',$s))); }
function admin_badge($v){ $v=strtolower((string)$v); if(in_array($v,['buy','sent','passed','ready','active','yes'],true)) return 'badge-ok'; if(in_array($v,['sell','failed','blocked','expired','invalidated','no'],true)) return 'badge-bad'; return 'badge-warn'; }
function admin_counts($checklist){ $items=is_array($checklist['items']??null)?$checklist['items']:[]; $c=['passed'=>0,'failed'=>0,'pending'=>0]; foreach($items as $it){ if(!is_array($it))continue; $s=strtolower((string)($it['status']??'pending')); if(!isset($c[$s]))$s='pending'; $c[$s]++; } return $c; }

function admin_database_timezone() {
    foreach (['database_timezone','stored_time_timezone','mysql_timezone','server_timezone'] as $key) {
        $value = trim(admin_setting_get_local($key,''));
        if ($value !== '') {
            try { new DateTimeZone($value); return $value; } catch(Throwable $e) {}
        }
    }
    try {
        $row = db()->query("SELECT @@session.time_zone AS session_tz, @@global.time_zone AS global_tz, @@system_time_zone AS system_tz")->fetch(PDO::FETCH_ASSOC) ?: [];
        $session = trim((string)($row['session_tz'] ?? ''));
        if ($session !== '' && strtoupper($session) !== 'SYSTEM') return $session;
        $system = strtoupper(trim((string)($row['system_tz'] ?? '')));
        $map=['UTC'=>'UTC','GMT'=>'UTC','WAT'=>'Africa/Lagos','EDT'=>'America/New_York','EST'=>'America/New_York','CDT'=>'America/Chicago','CST'=>'America/Chicago','PDT'=>'America/Los_Angeles','PST'=>'America/Los_Angeles'];
        return $map[$system] ?? 'UTC';
    } catch(Throwable $e) { return 'UTC'; }
}

function admin_time($v){
    $v=trim((string)($v??''));
    if($v===''||$v==='0000-00-00 00:00:00') return 'Pending';
    try{
        $src=admin_database_timezone();
        if(preg_match('/^[+-]\d{2}:\d{2}$/',$src)) $src='UTC'.$src;
        $dt=new DateTimeImmutable($v,new DateTimeZone($src));
        return $dt->setTimezone(new DateTimeZone('Africa/Lagos'))->format('Y-m-d h:i A T');
    }catch(Throwable $e){ return $v; }
}

$symbol=strtoupper(trim((string)($_GET['symbol']??'')));
$user=trim((string)($_GET['user']??''));
$status=trim((string)($_GET['status']??'active'));
$stage=strtoupper(trim((string)($_GET['stage']??'')));
$page=max(1,(int)($_GET['page']??1)); $perPage=10; $offset=($page-1)*$perPage;
$where=[]; $params=[];
if($symbol!==''){ $where[]='a.symbol LIKE ?'; $params[]='%'.$symbol.'%'; }
if($user!==''){ $where[]='(CAST(a.user_id AS CHAR)=? OR u.email LIKE ? OR u.name LIKE ?)'; $params[]=$user; $params[]='%'.$user.'%'; $params[]='%'.$user.'%'; }
if($stage!==''){ $where[]='UPPER(a.lifecycle_stage)=?'; $params[]=$stage; }
if($status==='active') $where[]="a.is_active=1 AND a.triggered_at IS NULL AND (a.expired_at IS NULL OR a.expired_at='')";
elseif($status==='paused') $where[]="a.is_active=0 AND a.triggered_at IS NULL";
elseif($status==='sent') $where[]="(a.triggered_at IS NOT NULL OR a.final_sent_at IS NOT NULL)";
elseif($status==='blocked') $where[]="(a.last_execution_checklist_status='FAILED' OR a.last_block_reason IS NOT NULL)";
$whereSql=$where?'WHERE '.implode(' AND ',$where):'';
$totalRows=0; $rows=[];
if(admin_table_exists_local('institutional_alerts')){
    $stmt=db()->prepare("SELECT COUNT(*) FROM institutional_alerts a LEFT JOIN users u ON u.id=a.user_id {$whereSql}"); $stmt->execute($params); $totalRows=(int)$stmt->fetchColumn();
    $stmt=db()->prepare("SELECT a.*,u.email user_email,u.name user_name FROM institutional_alerts a LEFT JOIN users u ON u.id=a.user_id {$whereSql} ORDER BY a.created_at DESC,a.id DESC LIMIT {$perPage} OFFSET {$offset}"); $stmt->execute($params); $rows=$stmt->fetchAll(PDO::FETCH_ASSOC)?:[];
}
$totalPages=max(1,(int)ceil(max(1,$totalRows)/$perPage));

admin_layout_header('Active Alerts');
?>
<style>
.admin-shell{max-width:1180px;margin:0 auto}.head-card{background:#fff;border:1px solid #e2e8f0;border-radius:24px;box-shadow:0 12px 34px rgba(15,23,42,.06);overflow:hidden}.head-top{padding:24px 26px;border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap}.title{font-size:30px;font-weight:800;letter-spacing:-.04em;color:#020617}.sub{color:#64748b;font-size:14px;line-height:1.55;margin-top:6px}.filter{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;padding:18px 26px;background:#f8fafc}.input,.select{width:100%;height:42px;border:1px solid #cbd5e1;border-radius:13px;padding:0 12px;font-weight:700;background:#fff}.btn{display:inline-flex;align-items:center;justify-content:center;min-height:38px;padding:0 13px;border:0;border-radius:13px;font-weight:800;text-decoration:none;cursor:pointer}.blue{background:#2563eb;color:#fff}.dark{background:#020617;color:#fff}.red{background:#fee2e2;color:#b91c1c}.soft{background:#eff6ff;color:#1d4ed8}.warn{background:#fffbeb;color:#b45309}.notice{margin:0 0 16px;padding:13px 16px;border-radius:16px;font-weight:700}.success{background:#ecfdf5;color:#047857;border:1px solid #a7f3d0}.err{background:#fef2f2;color:#b91c1c;border:1px solid #fecaca}.alerts{display:grid;gap:16px;padding:22px}.alert-card{border:1px solid #e2e8f0;border-radius:22px;overflow:hidden;background:#fff}.alert-top{padding:18px 20px;background:linear-gradient(135deg,#f8fafc,#fff);border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap}.sym{font-size:20px;font-weight:750;letter-spacing:-.03em}.meta{display:block;margin-top:5px;color:#64748b;font-size:12.5px;font-weight:650;line-height:1.55}.badges{display:flex;gap:8px;flex-wrap:wrap;align-items:flex-start}.badge{display:inline-flex;align-items:center;min-height:27px;border-radius:999px;padding:0 10px;font-size:12px;font-weight:800;border:1px solid}.badge-ok{background:#ecfdf5;color:#047857;border-color:#a7f3d0}.badge-bad{background:#fef2f2;color:#b91c1c;border-color:#fecaca}.badge-warn{background:#fffbeb;color:#b45309;border-color:#fde68a}.alert-body{padding:18px 20px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}.box{background:#f8fafc;border:1px solid #e2e8f0;border-radius:16px;padding:14px}.box-title{display:block;font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#64748b;margin-bottom:10px}.kv{display:flex;justify-content:space-between;gap:10px;margin-top:7px}.k{font-size:12px;color:#64748b;font-weight:700}.v{font-weight:700;text-align:right}.check{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-top:8px}.tile{border-radius:10px;text-align:center;padding:7px 6px;font-size:11px;font-weight:800}.ok{background:#ecfdf5;color:#047857}.bad{background:#fef2f2;color:#b91c1c}.pending{background:#fffbeb;color:#b45309}.decision{padding:0 20px 18px;color:#475569;font-size:13px;font-weight:650;line-height:1.55}.decision strong{display:block;color:#0f172a;margin-bottom:5px}.details{margin-top:10px}.details summary{cursor:pointer;font-weight:800;color:#1d4ed8}.details pre{white-space:pre-wrap;word-break:break-word;background:#020617;color:#dbeafe;border-radius:14px;padding:12px;font-size:12px;max-height:260px;overflow:auto}.actions{display:flex;gap:8px;flex-wrap:wrap;padding:0 20px 20px}.actions form{margin:0}.pager{padding:18px 24px;border-top:1px solid #e2e8f0;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;color:#64748b;font-weight:700}@media(max-width:950px){.alert-body{grid-template-columns:1fr}.filter{grid-template-columns:1fr 1fr}}@media(max-width:600px){.filter{grid-template-columns:1fr}.head-top{padding:20px}.alerts{padding:16px}.alert-body{padding:16px}.alert-top{padding:16px}}
</style>
<div class="admin-shell">
<?php if($message):?><div class="notice success"><?=e($message)?></div><?php endif;?>
<?php if($error):?><div class="notice err"><?=e($error)?></div><?php endif;?>
<section class="head-card">
  <div class="head-top">
    <div><div class="title">Active Alerts</div><div class="sub">Clean admin view for user setups, lifecycle state, confirmation timeframe, checklist status and engine decisions.</div></div>
    <span class="badge badge-warn"><?= (int)$totalRows ?> result(s)</span>
  </div>
  <form class="filter" method="get">
    <input class="input" name="symbol" value="<?=e($symbol)?>" placeholder="Symbol">
    <input class="input" name="user" value="<?=e($user)?>" placeholder="User ID / email / name">
    <select class="select" name="status"><?php foreach(['active'=>'Active','all'=>'All','paused'=>'Paused','sent'=>'Sent','blocked'=>'Blocked'] as $k=>$v):?><option value="<?=e($k)?>" <?=$status===$k?'selected':''?>><?=e($v)?></option><?php endforeach;?></select>
    <button class="btn blue" type="submit">Filter</button>
  </form>
  <div class="alerts">
    <?php if(!$rows):?><div class="box" style="text-align:center;color:#64748b;font-weight:700;">No alerts found.</div><?php endif;?>
    <?php foreach($rows as $r):?>
      <?php
        $market=admin_json_local($r['last_market_snapshot']??''); $eval=admin_json_local($r['last_evaluation_snapshot']??''); $check=admin_json_local($r['last_execution_checklist']??'');
        if(!$check && !empty($eval['execution_checklist']) && is_array($eval['execution_checklist'])) $check=$eval['execution_checklist'];
        $counts=admin_counts($check); $setup=admin_tf_label($market['setup_timeframe']??($r['timeframe']??'')); $confirm=admin_tf_label($market['scan_timeframe']??($market['confirmation_timeframe']??admin_confirm_tf($r['timeframe']??'')));
        $reason=admin_clean($r['last_execution_checklist_reason']??($r['last_block_reason']??($eval['message']??'Waiting for next engine check.')),'Waiting for next engine check.',220);
      ?>
      <article class="alert-card">
        <div class="alert-top">
          <div><div class="sym"><?=e($r['symbol']??'N/A')?> <?=e($r['side']??'')?></div><span class="meta">User: <?=e($r['user_name']?:'User #'.($r['user_id']??''))?> &bull; <?=e($r['user_email']??'No email')?> &bull; Alert #<?=e($r['id']??'')?> &bull; Created <?=e(admin_time($r['tracking_started_at']??($r['created_at']??'')))?></span></div>
          <div class="badges"><span class="badge <?=e(admin_badge($r['side']??''))?>"><?=e($r['side']??'N/A')?></span><span class="badge <?=e(admin_badge(($r['lifecycle_stage']??'TRACKING')==='TRACKING'?'tracking':'active'))?>"><?=e(admin_stage_label($r['lifecycle_stage']??'TRACKING'))?></span></div>
        </div>
        <div class="alert-body">
          <div class="box"><span class="box-title">Timeframe Flow</span><div class="kv"><span class="k">Setup</span><span class="v"><?=e($setup)?></span></div><div class="kv"><span class="k">Confirm</span><span class="v"><?=e($confirm)?></span></div><div class="kv"><span class="k">Mode</span><span class="v"><?=!empty($market['using_confirmation_timeframe'])?'LTF active':'Mapped/fallback'?></span></div><div class="kv"><span class="k">Fresh</span><span class="v"><?=!empty($market['confirmation_fresh'])||!empty($market['setup_fresh'])?'Yes':'No/Unknown'?></span></div></div>
          <div class="box"><span class="box-title">Execution</span><div class="kv"><span class="k">Zone</span><span class="v"><?=e(admin_price($r['entry_low']??null))?> - <?=e(admin_price($r['entry_high']??null))?></span></div><div class="kv"><span class="k">Entry</span><span class="v"><?=e(admin_price($r['entry_price']??null))?></span></div><div class="kv"><span class="k">SL</span><span class="v"><?=e(admin_price($r['stop_loss']??null))?></span></div><div class="kv"><span class="k">Current</span><span class="v"><?=e(admin_price($market['current_price']??null))?></span></div></div>
          <div class="box"><span class="box-title">Progress</span><div class="kv"><span class="k">S1</span><span class="v"><?=e(admin_time($r['stage1_sent_at']??''))?></span></div><div class="kv"><span class="k">S2</span><span class="v"><?=e(admin_time($r['stage2_sent_at']??''))?></span></div><div class="kv"><span class="k">S3</span><span class="v"><?=e(admin_time($r['stage3_sent_at']??''))?></span></div><div class="kv"><span class="k">Final</span><span class="v"><?=e(admin_time($r['final_sent_at']??($r['triggered_at']??'')))?></span></div></div>
        </div>
        <div class="decision"><strong>Checklist: <?=e(strtoupper((string)($r['last_execution_checklist_status']??($check['status']??'PENDING'))))?></strong><div class="check"><div class="tile ok"><?= (int)$counts['passed']?> Passed</div><div class="tile bad"><?= (int)$counts['failed']?> Failed</div><div class="tile pending"><?= (int)$counts['pending']?> Pending</div></div><p><?=e($reason)?></p><details class="details"><summary>Admin debug snapshots</summary><pre><?=e(json_encode(['market'=>$market,'evaluation'=>$eval],JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE))?></pre></details></div>
        <div class="actions">
          <form method="post"><input type="hidden" name="id" value="<?=e($r['id']??'')?>"><?php if(!empty($r['is_active'])):?><button class="btn warn" name="action" value="pause">Pause</button><?php else:?><button class="btn soft" name="action" value="resume">Resume</button><?php endif;?></form>
          <form method="post" onsubmit="return confirm('Reset this alert lifecycle for fresh tracking?');"><input type="hidden" name="id" value="<?=e($r['id']??'')?>"><button class="btn dark" name="action" value="reset_state">Reset</button></form>
          <form method="post" onsubmit="return confirm('Delete this alert?');"><input type="hidden" name="id" value="<?=e($r['id']??'')?>"><button class="btn red" name="action" value="delete">Delete</button></form>
        </div>
      </article>
    <?php endforeach;?>
  </div>
  <div class="pager"><div>Page <?= (int)$page ?> of <?= (int)$totalPages ?> &bull; <?= (int)$totalRows ?> alerts</div><div class="actions"><?php if($page>1):?><a class="btn soft" href="?<?=e(http_build_query(array_merge($_GET,['page'=>$page-1])))?>">Previous</a><?php endif;?><?php if($page<$totalPages):?><a class="btn blue" href="?<?=e(http_build_query(array_merge($_GET,['page'=>$page+1])))?>">Next</a><?php endif;?></div></div>
</section>
</div>
<?php admin_layout_footer(); ?>
