<?php

ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

session_start();

require_once __DIR__ . '/../core/functions.php';
require_once __DIR__ . '/../services/AlertService.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../public/login.php');
    exit;
}

if (!function_exists('e')) {
    function e($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function suggested_price($value) {
    if ($value === null || $value === '' || !is_numeric($value)) return 'N/A';
    $v = (float)$value;
    return abs($v) >= 100 ? number_format($v, 2) : rtrim(rtrim(number_format($v, 5), '0'), '.');
}

function suggested_clean($value, $fallback = 'N/A', $limit = 180) {
    $text = trim((string)($value ?? ''));
    if ($text === '') return $fallback;
    $text = strip_tags($text);
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = preg_replace('/[^\P{C}\t\r\n]+/u', ' ', $text);
    $text = preg_replace('/\s+/', ' ', $text);
    $text = trim($text);
    if ($text === '') return $fallback;
    return mb_strlen($text) > $limit ? mb_substr($text, 0, $limit) . '...' : $text;
}

function suggested_time($value) {
    if (!$value) return 'N/A';
    $ts = strtotime((string)$value);
    if (!$ts) return e($value);
    return date('Y-m-d h:i A', $ts) . ' WAT';
}

$userId = (int)$_SESSION['user_id'];
$message = '';
$messageType = 'info';

AlertService::ensureTables();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    $suggestionId = (int)($_POST['suggestion_id'] ?? 0);

    if ($action === 'track' && $suggestionId > 0) {
        $result = AlertService::trackSuggestedSetup($userId, $suggestionId, [
            'email' => !empty($_POST['email']),
            'telegram' => !empty($_POST['telegram']),
        ]);
        $message = (string)($result['message'] ?? 'Suggested setup action completed.');
        $messageType = !empty($result['ok']) ? 'success' : 'error';
    } elseif ($action === 'ignore' && $suggestionId > 0) {
        $result = AlertService::ignoreSuggestedSetup($userId, $suggestionId);
        $message = (string)($result['message'] ?? 'Suggested setup updated.');
        $messageType = !empty($result['ok']) ? 'success' : 'error';
    }
}

$suggestions = AlertService::getPendingSuggestedSetups($userId, 50);

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Suggested Setups</title>
    <style>
        :root { --bg:#f4f7fb; --card:#fff; --ink:#0f172a; --muted:#64748b; --line:#e2e8f0; --blue:#2563eb; --green:#059669; --red:#dc2626; --amber:#d97706; }
        * { box-sizing:border-box; }
        body { margin:0; background:var(--bg); color:var(--ink); font-family:Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
        .hero { background:linear-gradient(135deg, #0f1f46, #030712); color:#fff; padding:36px 24px; }
        .wrap { max-width:1120px; margin:0 auto; }
        .hero h1 { margin:0 0 8px; font-size:30px; letter-spacing:-.04em; }
        .hero p { margin:0; color:#cbd5e1; font-size:14px; }
        .main { padding:28px 24px 60px; }
        .topbar { display:flex; justify-content:space-between; gap:16px; align-items:center; margin-bottom:18px; }
        .btn { display:inline-flex; align-items:center; justify-content:center; border:0; border-radius:12px; padding:12px 16px; font-weight:800; text-decoration:none; cursor:pointer; font-size:14px; }
        .btn-blue { background:var(--blue); color:#fff; }
        .btn-light { background:#e8eef8; color:#1e3a8a; }
        .btn-green { background:#dcfce7; color:#065f46; }
        .btn-red { background:#fee2e2; color:#991b1b; }
        .notice { border-radius:14px; padding:14px 16px; margin-bottom:16px; font-weight:700; }
        .notice.success { background:#dcfce7; color:#065f46; border:1px solid #86efac; }
        .notice.error { background:#fee2e2; color:#991b1b; border:1px solid #fecaca; }
        .empty { background:var(--card); border:1px solid var(--line); border-radius:20px; padding:36px; text-align:center; color:var(--muted); }
        .grid { display:grid; gap:18px; }
        .card { background:var(--card); border:1px solid var(--line); border-radius:22px; overflow:hidden; box-shadow:0 12px 30px rgba(15,23,42,.05); }
        .card-head { padding:22px 24px; display:flex; justify-content:space-between; gap:18px; align-items:flex-start; border-bottom:1px solid var(--line); }
        .title { display:flex; gap:12px; align-items:center; }
        .badge { display:inline-flex; padding:7px 12px; border-radius:999px; font-size:12px; font-weight:900; text-transform:uppercase; letter-spacing:.04em; }
        .badge.sell { background:#fee2e2; color:#991b1b; }
        .badge.buy { background:#dcfce7; color:#065f46; }
        .badge.confidence { background:#eff6ff; color:#1d4ed8; }
        .card h2 { margin:0; font-size:22px; letter-spacing:-.03em; }
        .sub { margin-top:7px; color:var(--muted); font-size:14px; font-weight:700; }
        .section { padding:20px 24px; }
        .metrics { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:12px; }
        .metric { border:1px solid var(--line); border-radius:16px; padding:14px; background:#fbfdff; }
        .label { color:var(--muted); text-transform:uppercase; letter-spacing:.08em; font-size:11px; font-weight:900; margin-bottom:8px; }
        .value { font-weight:850; font-size:16px; }
        .reason { background:#f8fafc; border:1px solid var(--line); border-radius:16px; padding:15px 16px; color:#334155; line-height:1.55; font-weight:600; }
        .actions { display:flex; flex-wrap:wrap; gap:10px; align-items:center; margin-top:16px; }
        .checks { display:flex; gap:14px; color:#475569; font-size:14px; font-weight:700; }
        input[type="checkbox"] { width:16px; height:16px; vertical-align:middle; }
        @media (max-width:850px){ .metrics { grid-template-columns:repeat(2,minmax(0,1fr)); } .card-head { flex-direction:column; } }
        @media (max-width:520px){ .metrics { grid-template-columns:1fr; } .topbar { flex-direction:column; align-items:flex-start; } }
    </style>
</head>
<body>
    <div class="hero">
        <div class="wrap">
            <h1>Suggested New Setups</h1>
            <p>Review high-quality derived setups that formed outside an original tracked zone. Nothing is tracked until you approve it.</p>
        </div>
    </div>

    <main class="main">
        <div class="wrap">
            <div class="topbar">
                <a class="btn btn-blue" href="my_alerts.php">Back to My Alerts</a>
                <span style="color:#64748b;font-weight:800;"><?= count($suggestions) ?> pending suggestion<?= count($suggestions) === 1 ? '' : 's' ?></span>
            </div>

            <?php if ($message !== ''): ?>
                <div class="notice <?= e($messageType) ?>"><?= e($message) ?></div>
            <?php endif; ?>

            <?php if (empty($suggestions)): ?>
                <div class="empty">
                    <h2>No pending suggested setups</h2>
                    <p>The system will show a suggestion here when a valid new setup forms outside an original tracked zone.</p>
                </div>
            <?php else: ?>
                <div class="grid">
                    <?php foreach ($suggestions as $s): ?>
                        <?php $side = strtoupper((string)$s['side']); ?>
                        <article class="card">
                            <div class="card-head">
                                <div>
                                    <div class="title">
                                        <span class="badge <?= strtolower($side) ?>"><?= e($side) ?></span>
                                        <h2><?= e($s['symbol']) ?> <?= e($side) ?></h2>
                                    </div>
                                    <div class="sub">Setup <?= e($s['timeframe']) ?><?= !empty($s['confirmation_timeframe']) ? ' • Confirm ' . e($s['confirmation_timeframe']) : '' ?> • Created <?= suggested_time($s['created_at']) ?></div>
                                </div>
                                <span class="badge confidence"><?= e($s['confidence_label'] ?: 'Review') ?><?= $s['quality_score'] !== null ? ' • ' . e($s['quality_score']) : '' ?></span>
                            </div>

                            <div class="section">
                                <div class="metrics">
                                    <div class="metric"><div class="label">Original Zone</div><div class="value"><?= suggested_price($s['original_entry_low']) ?> - <?= suggested_price($s['original_entry_high']) ?></div></div>
                                    <div class="metric"><div class="label">New Zone</div><div class="value"><?= suggested_price($s['suggested_entry_low']) ?> - <?= suggested_price($s['suggested_entry_high']) ?></div></div>
                                    <div class="metric"><div class="label">Entry</div><div class="value"><?= suggested_price($s['suggested_entry_price']) ?></div></div>
                                    <div class="metric"><div class="label">Stop Loss</div><div class="value"><?= suggested_price($s['stop_loss']) ?></div></div>
                                    <div class="metric"><div class="label">TP1</div><div class="value"><?= suggested_price($s['tp1']) ?></div></div>
                                    <div class="metric"><div class="label">TP2</div><div class="value"><?= suggested_price($s['tp2']) ?></div></div>
                                    <div class="metric"><div class="label">TP3</div><div class="value"><?= suggested_price($s['tp3']) ?></div></div>
                                    <div class="metric"><div class="label">HTF Location</div><div class="value"><?= e(suggested_clean($s['htf_location_label'] ?? 'N/A', 'N/A', 60)) ?><?= isset($s['htf_location_score']) && $s['htf_location_score'] !== null ? ' • ' . e($s['htf_location_score']) : '' ?></div></div>
                                    <div class="metric"><div class="label">LTF Location</div><div class="value"><?= e(suggested_clean($s['ltf_location_label'] ?? 'N/A', 'N/A', 60)) ?><?= isset($s['ltf_location_score']) && $s['ltf_location_score'] !== null ? ' • ' . e($s['ltf_location_score']) : '' ?></div></div>
                                    <div class="metric"><div class="label">Notification</div><div class="value"><?= !empty($s['notification_sent_at']) ? 'Sent ' . suggested_time($s['notification_sent_at']) : (!empty($s['notification_attempted_at']) ? 'Attempted ' . suggested_time($s['notification_attempted_at']) : 'Pending') ?></div></div>
                                    <div class="metric"><div class="label">Expires</div><div class="value"><?= suggested_time($s['expires_at']) ?></div></div>
                                </div>

                                <div style="height:14px"></div>
                                <div class="reason"><strong>Why this appears:</strong> <?= e(suggested_clean($s['reason'])) ?><br><strong>Institutional location gate:</strong> <?= e(suggested_clean($s['location_gate_reason'] ?? 'Premium/discount location was checked before this suggestion was created.', 'Premium/discount location was checked before this suggestion was created.', 260)) ?></div>

                                <form method="post" class="actions">
                                    <input type="hidden" name="suggestion_id" value="<?= (int)$s['id'] ?>">
                                    <div class="checks">
                                        <label><input type="checkbox" name="email" value="1" checked> Email</label>
                                        <label><input type="checkbox" name="telegram" value="1"> Telegram</label>
                                    </div>
                                    <button class="btn btn-green" name="action" value="track" type="submit">Track This Setup</button>
                                    <button class="btn btn-red" name="action" value="ignore" type="submit">Ignore</button>
                                </form>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </main>
</body>
</html>
