<?php
if (!defined('ROOT_PATH')) { http_response_code(403); exit; }
require_once ROOT_PATH . '/admin/templates/header.php';
$isRtl = \Core\System\Language::direction() === 'rtl';
?>
<div class="content-wrapper"><section class="content pt-3"><div class="container-fluid pb-5">

<div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-3">
    <div>
        <h3 class="mb-1 fw-bold">
            <i class="bi bi-robot me-2" style="color:#7c3aed"></i>
            <?= fbt('fb_ads.agent_title','AI Autonomous Ad Agent') ?>
            <span class="badge ms-2 text-white" style="background:#7c3aed;font-size:.7rem">Beta</span>
        </h3>
        <p class="text-muted small mb-0"><?= fbt('fb_ads.agent_subtitle','Let AI plan, create and optimize your Facebook campaigns automatically') ?></p>
    </div>
    <a href="/admin/facebook-ads" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-<?= $isRtl?'right':'left' ?> me-1"></i><?= fbt('fb_ads.back','Back') ?>
    </a>
</div>

<?php if(!$isConfigured): ?>
<div class="alert border-0 shadow-sm mb-4" style="background:linear-gradient(135deg,#1877f2,#0c5fcc);color:#fff">
    <div class="d-flex align-items-center gap-3">
        <i class="bi bi-facebook fs-2"></i>
        <div class="flex-grow-1">
            <div class="fw-bold"><?= fbt('fb_ads.setup_required','Setup Required') ?></div>
            <div style="opacity:.9;font-size:.88rem"><?= fbt('fb_ads.agent_needs_config','Agent needs Facebook API configured first.') ?></div>
        </div>
        <a href="/admin/facebook-ads/settings" class="btn btn-light fw-bold"><?= fbt('fb_ads.go_settings','Configure →') ?></a>
    </div>
</div>
<?php endif; ?>

<?php if(!$aiAvailable): ?>
<div class="alert alert-warning border-0 shadow-sm mb-4">
    <i class="bi bi-exclamation-triangle-fill me-2"></i>
    <?= fbt('fb_ads.agent_needs_ai','Agent requires AI to be configured.') ?>
    <a href="/admin/settings/ai" class="alert-link ms-2"><?= fbt('fb_ads.configure_ai','Configure AI →') ?></a>
</div>
<?php endif; ?>

<!-- How it works -->
<div class="card border-0 shadow-sm mb-4" style="background:linear-gradient(135deg,#1e1b4b,#312e81);color:#fff">
    <div class="card-body p-4">
        <div class="fw-bold fs-5 mb-3"><i class="bi bi-stars me-2" style="color:#a5b4fc"></i><?= fbt('fb_ads.agent_how','How the Agent Works') ?></div>
        <div class="row g-3">
        <?php $steps = [
            ['①','bi-search','text-info',        fbt('fb_ads.agent_step1','AI analyzes product + goal'), fbt('fb_ads.agent_step1_d','Builds complete advertising strategy')],
            ['②','bi-pencil-square','text-warning', fbt('fb_ads.agent_step2','Writes 3 ad variants (A/B/C)'), fbt('fb_ads.agent_step2_d','Different styles for split testing')],
            ['③','bi-people','text-success',      fbt('fb_ads.agent_step3','Auto-selects target audience'), fbt('fb_ads.agent_step3_d','Age, gender, interests based on product')],
            ['④','bi-send-fill','text-pink',      fbt('fb_ads.agent_step4','Launches all campaigns'), fbt('fb_ads.agent_step4_d','3 campaigns created via Meta API')],
            ['⑤','bi-bar-chart','text-info',      fbt('fb_ads.agent_step5','Monitors performance daily'), fbt('fb_ads.agent_step5_d','Tracks CTR, CPC, ROAS')],
            ['⑥','bi-arrow-repeat','text-success',fbt('fb_ads.agent_step6','Optimizes automatically'), fbt('fb_ads.agent_step6_d','Pauses poor ads, boosts winners')],
        ]; foreach($steps as [$num,$icon,$col,$title,$desc]): ?>
        <div class="col-md-4 col-sm-6">
            <div class="d-flex gap-3 align-items-start">
                <span style="font-size:1.4rem;opacity:.6"><?= $num ?></span>
                <div>
                    <i class="bi <?= $icon ?> <?= $col ?> me-1"></i>
                    <span class="fw-semibold small"><?= $title ?></span>
                    <div style="font-size:.75rem;opacity:.7;margin-top:2px"><?= $desc ?></div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="row g-4">
<!-- ── Left: Setup Form ───────────────────────────────── -->
<div class="col-lg-6">

    <!-- Step 1: Product + Budget -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white border-bottom py-3">
            <h6 class="mb-0 fw-semibold"><span class="badge bg-primary rounded-pill me-2">1</span><?= fbt('fb_ads.agent_setup','Tell the Agent What to Do') ?></h6>
        </div>
        <div class="card-body">

            <!-- Product selection -->
            <div class="mb-3">
                <label class="form-label fw-semibold"><?= fbt('fb_ads.product','Product') ?> <span class="text-danger">*</span></label>
                <div class="row g-2" id="product-grid">
                <?php foreach($products as $prod): ?>
                <div class="col-6">
                    <label class="product-card d-flex align-items-center gap-2 p-2 border rounded-3" style="cursor:pointer;transition:all .15s">
                        <input type="radio" name="product_id" value="<?= $prod['id'] ?>" class="d-none prod-radio" required>
                        <?php if(!empty($prod['featured_image'])): ?>
                        <img src="<?= htmlspecialchars($prod['featured_image']) ?>" width="40" height="40" class="rounded-2 border object-fit-cover flex-shrink-0">
                        <?php endif; ?>
                        <div class="min-w-0">
                            <div class="fw-semibold text-truncate" style="font-size:.8rem"><?= htmlspecialchars($prod['title']) ?></div>
                            <div class="text-primary" style="font-size:.72rem"><?= number_format((float)$prod['price']) ?> <?= $prod['currency'] ?></div>
                        </div>
                    </label>
                </div>
                <?php endforeach; ?>
                </div>
            </div>

            <!-- Goal -->
            <div class="mb-3">
                <label class="form-label fw-semibold"><?= fbt('fb_ads.goal_label','Campaign Goal') ?></label>
                <div class="d-flex gap-2 flex-wrap">
                <?php foreach([
                    ['sales','💰',fbt('fb_ads.obj_sales','Sales')],
                    ['awareness','📢',fbt('fb_ads.obj_awareness','Awareness')],
                    ['engagement','💬',fbt('fb_ads.obj_engagement','Engagement')],
                ] as [$val,$emoji,$label]): ?>
                <label class="flex-grow-1 goal-card text-center p-2 border rounded-3" style="cursor:pointer;transition:all .15s">
                    <input type="radio" name="goal" value="<?= $val ?>" class="d-none goal-radio" <?= $val==='sales'?'checked':'' ?>>
                    <div><?= $emoji ?></div>
                    <div class="fw-semibold small"><?= $label ?></div>
                </label>
                <?php endforeach; ?>
                </div>
            </div>

            <!-- Monthly budget -->
            <div class="mb-3">
                <label class="form-label fw-semibold"><?= fbt('fb_ads.monthly_budget','Monthly Budget') ?> <span class="text-danger">*</span></label>
                <div class="input-group">
                    <input type="number" id="monthly-budget" class="form-control" value="5000" min="500" step="500">
                    <span class="input-group-text">DZD / <?= fbt('fb_ads.month','month') ?></span>
                </div>
                <div class="form-text"><?= fbt('fb_ads.agent_distributes','Agent will distribute budget across campaigns automatically') ?></div>
            </div>

            <!-- Language -->
            <div class="mb-4">
                <label class="form-label fw-semibold small"><?= fbt('fb_ads.language','Language') ?></label>
                <select id="agent-lang" class="form-select">
                    <option value="ar">🇸🇦 العربية</option>
                    <option value="en">🇬🇧 English</option>
                </select>
            </div>

            <!-- Analyze button -->
            <button id="analyze-btn" onclick="runAnalysis()"
                    class="btn w-100 fw-bold py-3"
                    style="background:linear-gradient(135deg,#7c3aed,#a855f7);color:#fff;border:none;border-radius:12px;font-size:1.05rem"
                    <?= (!$isConfigured||!$aiAvailable)?'disabled':'' ?>>
                <i class="bi bi-stars me-2"></i><?= fbt('fb_ads.analyze_and_plan','Analyze & Plan Strategy') ?>
            </button>
        </div>
    </div>

    <!-- Analysis loading -->
    <div id="analysis-loading" style="display:none" class="card border-0 shadow-sm mb-4">
        <div class="card-body py-4 text-center">
            <div class="spinner-border mb-3" style="color:#7c3aed;width:2rem;height:2rem"></div>
            <div class="fw-semibold fs-5" style="color:#7c3aed" id="analysis-phase-text">
                <?= fbt('fb_ads.agent_analyzing','AI is analyzing your product...') ?>
            </div>
            <div class="text-muted small mt-1"><?= fbt('fb_ads.agent_wait','Building complete strategy. 15-30 seconds.') ?></div>
            <div class="progress mt-3" style="height:4px">
                <div class="progress-bar progress-bar-striped progress-bar-animated" style="width:100%;background:#7c3aed"></div>
            </div>
        </div>
    </div>

</div>

<!-- ── Right: Strategy Preview ─────────────────────────── -->
<div class="col-lg-6">
    <!-- Placeholder -->
    <div id="strategy-placeholder" class="card border-0 shadow-sm" style="border:2px dashed #d4b8ff">
        <div class="card-body text-center py-5 text-muted">
            <i class="bi bi-robot display-4 d-block mb-3 opacity-25" style="color:#7c3aed"></i>
            <div class="fw-semibold" style="color:#7c3aed"><?= fbt('fb_ads.agent_waiting','Waiting for your input...') ?></div>
            <div class="small mt-2"><?= fbt('fb_ads.agent_will_show','The AI strategy will appear here') ?></div>
        </div>
    </div>

    <!-- Strategy result (hidden until AI responds) -->
    <div id="strategy-result" style="display:none">

        <!-- Strategy summary card -->
        <div class="card border-0 shadow-sm mb-4" style="border-top:3px solid #7c3aed !important">
            <div class="card-header border-0 py-3" style="background:linear-gradient(135deg,#4c1d95,#7c3aed);color:#fff">
                <div class="fw-bold" id="strategy-name">Strategy</div>
                <div id="strategy-summary" style="opacity:.85;font-size:.85rem;margin-top:4px"></div>
            </div>
            <div class="card-body p-0">
                <div class="row g-0">
                    <div class="col-4 text-center p-3 border-end">
                        <div class="fw-bold fs-5 text-primary" id="s-budget">—</div>
                        <div class="text-muted small"><?= fbt('fb_ads.daily_budget','Daily Budget') ?>/DZD</div>
                    </div>
                    <div class="col-4 text-center p-3 border-end">
                        <div class="fw-bold fs-5 text-success" id="s-duration">—</div>
                        <div class="text-muted small"><?= fbt('fb_ads.days','Days') ?></div>
                    </div>
                    <div class="col-4 text-center p-3">
                        <div class="fw-bold fs-5 text-warning" id="s-objective">—</div>
                        <div class="text-muted small"><?= fbt('fb_ads.objective','Objective') ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 3 Ad variants -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3">
                <h6 class="mb-0 fw-semibold"><i class="bi bi-columns-gap me-2 text-primary"></i><?= fbt('fb_ads.ab_variants','A/B/C Ad Variants') ?></h6>
            </div>
            <div id="ads-container" class="card-body p-0"></div>
        </div>

        <!-- KPIs -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3">
                <h6 class="mb-0 fw-semibold"><i class="bi bi-target me-2 text-success"></i><?= fbt('fb_ads.success_kpis','Success KPIs') ?></h6>
            </div>
            <div id="kpis-container" class="card-body"></div>
        </div>

        <!-- Agent notes -->
        <div id="agent-notes-wrap" class="alert alert-info border-0 shadow-sm mb-4 d-none">
            <i class="bi bi-robot me-2"></i><strong>AI:</strong> <span id="agent-notes"></span>
        </div>

        <!-- Launch button -->
        <button id="launch-btn" onclick="launchCampaigns()"
                class="btn w-100 fw-bold py-3 fs-6"
                style="background:linear-gradient(135deg,#16a34a,#15803d);color:#fff;border:none;border-radius:12px;box-shadow:0 4px 20px rgba(22,163,74,.35)">
            <i class="bi bi-rocket-takeoff me-2"></i><?= fbt('fb_ads.agent_launch','Launch 3 Campaigns Now') ?>
            <span id="launch-spinner" class="spinner-border spinner-border-sm ms-2 d-none"></span>
        </button>
        <div class="text-center small text-muted mt-2">
            <i class="bi bi-info-circle me-1"></i><?= fbt('fb_ads.agent_paused_note','All campaigns start as PAUSED for your review') ?>
        </div>

        <div id="launch-result" class="mt-3" style="display:none"></div>
    </div>
</div>

</div><!-- /row -->

<!-- Active agents -->
<?php if(!empty($agents)): ?>
<div class="card border-0 shadow-sm mt-4">
    <div class="card-header bg-white border-bottom py-3">
        <h6 class="mb-0 fw-semibold"><i class="bi bi-robot me-2" style="color:#7c3aed"></i><?= fbt('fb_ads.active_agents','Active Agents') ?></h6>
    </div>
    <div class="card-body p-0">
    <div class="table-responsive">
    <table class="table table-hover align-middle mb-0 small">
        <thead class="table-light">
            <tr>
                <th class="ps-3"><?= fbt('fb_ads.col_campaign','Agent / Product') ?></th>
                <th>Budget</th>
                <th><?= fbt('fb_ads.col_status','Status') ?></th>
                <th>Campaigns</th>
                <th>Spent</th>
                <th class="pe-3"><?= fbt('actions.actions','Actions') ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($agents as $agent):
            $stColors = ['active'=>'bg-success','paused'=>'bg-warning text-dark','completed'=>'bg-primary','error'=>'bg-danger','pending'=>'bg-secondary'];
        ?>
        <tr>
            <td class="ps-3">
                <div class="d-flex align-items-center gap-2">
                    <?php if(!empty($agent['featured_image'])): ?><img src="<?= htmlspecialchars($agent['featured_image']) ?>" width="36" height="36" class="rounded-2 border object-fit-cover"><?php endif; ?>
                    <div>
                        <div class="fw-semibold"><?= htmlspecialchars($agent['strategy_name']) ?></div>
                        <div class="text-muted" style="font-size:.72rem"><?= htmlspecialchars($agent['product_title']??'') ?></div>
                    </div>
                </div>
            </td>
            <td><?= number_format((float)$agent['monthly_budget']) ?> DZD</td>
            <td><span class="badge <?= $stColors[$agent['status']]??'bg-secondary' ?>"><?= ucfirst($agent['status']) ?></span></td>
            <td><?= (int)$agent['campaign_count'] ?></td>
            <td><?= number_format((float)$agent['total_spent'],2) ?> DZD</td>
            <td class="pe-3">
                <div class="d-flex gap-1">
                    <button onclick="optimizeAgent(<?= $agent['id'] ?>)" class="btn btn-sm btn-outline-primary" title="Optimize">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                    <a href="/admin/facebook-ads" class="btn btn-sm btn-outline-secondary">
                        <i class="bi bi-eye"></i>
                    </a>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    </div>
</div>
<?php endif; ?>

</div></section></div>

<script>
(function(){
'use strict';
var CSRF = '<?= \Core\System\Csrf::token() ?>';
var currentStrategy = null;
var currentProductId = null;

// Product card selection
document.querySelectorAll('.product-card').forEach(function(card){
    card.addEventListener('click',function(){
        document.querySelectorAll('.product-card').forEach(c=>{c.style.borderColor='';c.style.background='';});
        card.style.borderColor='#7c3aed'; card.style.background='#faf5ff';
        card.querySelector('.prod-radio').checked=true;
        currentProductId = parseInt(card.querySelector('.prod-radio').value);
    });
});

// Goal selection
document.querySelectorAll('.goal-card').forEach(function(card){
    card.addEventListener('click',function(){
        document.querySelectorAll('.goal-card').forEach(c=>{c.style.borderColor='';c.style.background='';});
        card.style.borderColor='#7c3aed'; card.style.background='#faf5ff';
        card.querySelector('.goal-radio').checked=true;
    });
    if(card.querySelector('.goal-radio').checked){ card.style.borderColor='#7c3aed'; card.style.background='#faf5ff'; }
});

// Analysis phases
var phases = [
    '<?= fbt('fb_ads.agent_phase1','Analyzing product description and pricing...') ?>',
    '<?= fbt('fb_ads.agent_phase2','Determining optimal campaign objective...') ?>',
    '<?= fbt('fb_ads.agent_phase3','Identifying target audience segments...') ?>',
    '<?= fbt('fb_ads.agent_phase4','Writing 3 ad variants (A/B/C)...') ?>',
    '<?= fbt('fb_ads.agent_phase5','Calculating budget distribution...') ?>',
    '<?= fbt('fb_ads.agent_phase6','Finalizing strategy...') ?>',
];

window.runAnalysis = function(){
    var prodId  = document.querySelector('.prod-radio:checked')?.value;
    var goal    = document.querySelector('.goal-radio:checked')?.value || 'sales';
    var budget  = document.getElementById('monthly-budget')?.value;
    var lang    = document.getElementById('agent-lang')?.value || 'ar';

    if(!prodId){ alert('<?= fbt('fb_ads.agent_select_product','Select a product first.') ?>'); return; }
    if(!budget || budget < 500){ alert('<?= fbt('fb_ads.agent_min_budget','Minimum budget is 500 DZD.') ?>'); return; }

    document.getElementById('analyze-btn').disabled=true;
    document.getElementById('strategy-placeholder').style.display='none';
    document.getElementById('strategy-result').style.display='none';
    document.getElementById('analysis-loading').style.display='';

    var pi=0; var timer=setInterval(function(){
        pi=(pi+1)%phases.length;
        var el=document.getElementById('analysis-phase-text');
        if(el) el.textContent=phases[pi];
    }, 4000);

    var fd=new FormData();
    fd.append('_csrf',CSRF); fd.append('product_id',prodId);
    fd.append('monthly_budget',budget); fd.append('goal',goal); fd.append('lang',lang);

    fetch('/admin/facebook-ads/agent/analyze',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(function(d){
        clearInterval(timer);
        document.getElementById('analysis-loading').style.display='none';
        document.getElementById('analyze-btn').disabled=false;

        if(!d.success){ alert('❌ '+d.message); document.getElementById('strategy-placeholder').style.display=''; return; }

        currentStrategy = d.strategy;
        currentProductId = parseInt(prodId);
        renderStrategy(d.strategy);
        document.getElementById('strategy-result').style.display='';
    })
    .catch(function(e){
        clearInterval(timer);
        document.getElementById('analysis-loading').style.display='none';
        document.getElementById('analyze-btn').disabled=false;
        document.getElementById('strategy-placeholder').style.display='';
        alert('❌ '+e.message);
    });
};

function renderStrategy(s){
    document.getElementById('strategy-name').textContent    = s.strategy_name    || '';
    document.getElementById('strategy-summary').textContent = s.strategy_summary || '';
    document.getElementById('s-budget').textContent   = (s.daily_budget  || 0).toLocaleString();
    document.getElementById('s-duration').textContent = s.duration_days  || 14;
    document.getElementById('s-objective').textContent= (s.objective||'').replace('OUTCOME_','');

    // Ads
    var adsHtml = '';
    var varColors = {A:'#1877f2',B:'#22c55e',C:'#f59e0b'};
    (s.ads||[]).forEach(function(ad){
        var col = varColors[ad.variant] || '#666';
        adsHtml += '<div class="p-3 border-bottom">'
            + '<div class="d-flex align-items-center gap-2 mb-2">'
            + '<span class="badge fw-bold" style="background:'+col+'">Variant '+ad.variant+'</span>'
            + '<span class="text-muted small">'+escHtml(ad.approach||'')+'</span></div>'
            + '<div class="small fw-semibold mb-1">'+escHtml(ad.primary_text||'')+'</div>'
            + '<div class="small text-primary">'+escHtml(ad.headline||'')+'</div>'
            + '<div class="small text-muted mt-1"><i class="bi bi-lightbulb me-1 text-warning"></i>'+escHtml(ad.why||'')+'</div>'
            + '</div>';
    });
    document.getElementById('ads-container').innerHTML = adsHtml || '<div class="p-3 text-muted">—</div>';

    // KPIs
    var kpis = s.success_kpis || {};
    document.getElementById('kpis-container').innerHTML =
        '<div class="row g-3">'
        + '<div class="col-4 text-center"><div class="fw-bold fs-5 text-primary">'+(kpis.target_ctr||'—')+'</div><div class="text-muted small">Target CTR</div></div>'
        + '<div class="col-4 text-center"><div class="fw-bold fs-5 text-success">'+(kpis.target_cpc||'—')+'</div><div class="text-muted small">Target CPC</div></div>'
        + '<div class="col-4 text-center"><div class="fw-bold fs-5 text-warning">'+(kpis.target_roas||'—')+'</div><div class="text-muted small">Target ROAS</div></div>'
        + '</div>';

    // Agent notes
    if(s.agent_notes){
        document.getElementById('agent-notes').textContent = s.agent_notes;
        document.getElementById('agent-notes-wrap').classList.remove('d-none');
    }
}

window.launchCampaigns = function(){
    if(!currentStrategy){ alert('Run analysis first.'); return; }
    if(!confirm('<?= fbt('fb_ads.agent_confirm_launch','Launch 3 campaigns on Facebook? They start as PAUSED for review.') ?>')) return;

    var btn    = document.getElementById('launch-btn');
    var spin   = document.getElementById('launch-spinner');
    var result = document.getElementById('launch-result');
    btn.disabled=true; spin.classList.remove('d-none'); result.style.display='none';

    var fd=new FormData(); fd.append('_csrf',CSRF);
    fetch('/admin/facebook-ads/agent/launch',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(function(d){
        btn.disabled=false; spin.classList.add('d-none');
        result.style.display='';
        if(d.success){
            var resHtml='<div class="alert border-0" style="background:#f0fdf4;border-left:4px solid #22c55e !important">'
                +'<div class="fw-bold text-success fs-5 mb-2">🚀 '+d.message+'</div>';

            Object.entries(d.results||{}).forEach(function([v,r]){
                resHtml+='<div class="small mb-1">';
                resHtml+= r.success ? '✅ Variant '+v+': '+r.name : '❌ Variant '+v+': '+(r.error||'Failed');
                resHtml+='</div>';
            });

            resHtml+='<div class="d-flex gap-2 mt-3">'
                +'<a href="'+d.ads_manager_url+'" target="_blank" class="btn btn-sm btn-primary"><i class="bi bi-facebook me-1"></i>Open Ads Manager</a>'
                +'<a href="/admin/facebook-ads" class="btn btn-sm btn-outline-secondary">View Campaigns</a>'
                +'</div></div>';
            result.innerHTML=resHtml;
            setTimeout(()=>location.reload(),5000);
        } else {
            result.innerHTML='<div class="alert alert-danger border-0"><div class="fw-bold mb-1">❌ '+d.message+'</div></div>';
        }
    })
    .catch(function(e){
        btn.disabled=false; spin.classList.add('d-none');
        result.innerHTML='<div class="alert alert-danger border-0">❌ '+e.message+'</div>';
        result.style.display='';
    });
};

window.optimizeAgent = function(agentId){
    if(!confirm('<?= fbt('fb_ads.agent_confirm_optimize','Run AI optimization on this agent?') ?>')) return;
    var fd=new FormData(); fd.append('_csrf',CSRF);
    fetch('/admin/facebook-ads/agent/optimize/'+agentId,{method:'POST',body:fd})
    .then(r=>r.json()).then(d=>{
        alert(d.success
            ? '✅ '+d.assessment+'\n\n'+d.actions.join('\n')
            : '❌ '+d.message);
        if(d.success) location.reload();
    });
};

function escHtml(s){ var d=document.createElement('div');d.textContent=s;return d.innerHTML; }

})();
</script>

<style>
.product-card:hover{border-color:#7c3aed!important;background:#faf5ff!important}
.goal-card:hover{border-color:#7c3aed!important;background:#faf5ff!important}
</style>

<?php require_once ROOT_PATH . '/admin/templates/footer.php'; ?>
