<?php
if (!defined('ROOT_PATH')) { http_response_code(403); exit; }
require_once ROOT_PATH . '/admin/templates/header.php';
$isRtl = \Core\System\Language::direction() === 'rtl';

// Prepare chart data
$chartDates  = json_encode(array_column($insights, 'date'));
$chartImpr   = json_encode(array_map('intval', array_column($insights, 'impressions')));
$chartClicks = json_encode(array_map('intval', array_column($insights, 'clicks')));
$chartSpend  = json_encode(array_map('floatval', array_column($insights, 'spend')));
$chartCtr    = json_encode(array_map('floatval', array_column($insights, 'ctr')));
$chartCpc    = json_encode(array_map('floatval', array_column($insights, 'cpc')));

$totalSpend  = array_sum(array_column($insights, 'spend'));
$totalClicks = array_sum(array_column($insights, 'clicks'));
$totalImpr   = array_sum(array_column($insights, 'impressions'));
$totalPurch  = (int)($campaign['purchases'] ?? 0);
$roas        = $totalSpend > 0 && ($campaign['purchase_value']??0) > 0
               ? round($campaign['purchase_value']/$totalSpend, 2) : 0;
$avgCtr      = $totalImpr > 0 ? round(($totalClicks/$totalImpr)*100, 3) : 0;
?>
<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>
        <h4 class="fw-bold mb-1"><i class="bi bi-bar-chart-fill me-2 text-primary"></i><?= htmlspecialchars($campaign['name']) ?></h4>
        <div class="text-muted small"><i class="bi bi-box-seam me-1"></i><?= htmlspecialchars($campaign['product_title'] ?? '') ?></div>
    </div>
    <div class="d-flex gap-2 flex-wrap">
        <button id="fetch-btn" onclick="fetchInsights()" class="btn btn-outline-primary fw-semibold">
            <i class="bi bi-arrow-clockwise me-1"></i><?= fbt('fb_ads.fetch_insights','Fetch Latest Stats') ?>
        </button>
        <?php if($aiAvailable && !empty($insights)): ?>
        <a href="/admin/facebook-ads/ai-advisor/<?= $campaign['id'] ?>" class="btn fw-semibold"
           style="background:linear-gradient(135deg,#7c3aed,#a855f7);color:#fff;border:none">
            <i class="bi bi-stars me-1"></i><?= fbt('fb_ads.ai_advisor','AI Advisor') ?>
        </a>
        <?php endif; ?>
        <a href="/admin/facebook-ads/campaign/<?= $campaign['id'] ?>" 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>
</div>

<div id="fetch-result" style="display:none" class="mb-4"></div>

<!-- KPI Cards -->
<div class="row g-3 mb-4">
<?php $kpis = [
    ['bi-eye-fill',     'primary',  fbt('fb_ads.impressions','Impressions'), number_format((int)$campaign['impressions'])],
    ['bi-people-fill',  'info',     fbt('fb_ads.reach','Reach'),             number_format((int)($campaign['reach']??0))],
    ['bi-cursor-fill',  'success',  fbt('fb_ads.clicks','Clicks'),           number_format($totalClicks)],
    ['bi-cash-stack',   'warning',  fbt('fb_ads.spend','Spend'),             number_format($totalSpend,2).' '.($campaign['currency']??'DZD')],
    ['bi-cart-check',   'danger',   fbt('fb_ads.purchases','Purchases'),     $totalPurch > 0 ? $totalPurch : '—'],
    ['bi-graph-up',     'dark',     'ROAS',                                   $roas > 0 ? $roas.'x' : '—'],
    ['bi-percent',      'secondary','CTR',                                    $avgCtr.'%'],
    ['bi-currency-exchange','primary',fbt('fb_ads.cpc','CPC'),              number_format((float)($campaign['cpc']??0),2)],
]; foreach($kpis as [$icon,$color,$label,$val]): ?>
<div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm text-center py-3 h-100">
        <i class="bi <?= $icon ?> text-<?= $color ?> fs-3 mb-1"></i>
        <div class="fw-bold fs-5"><?= $val ?></div>
        <div class="text-muted small"><?= $label ?></div>
    </div>
</div>
<?php endforeach; ?>
</div>

<?php if(empty($insights)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5 text-muted">
        <i class="bi bi-bar-chart display-4 d-block mb-3 opacity-25"></i>
        <p class="mb-3"><?= fbt('fb_ads.no_insights','No detailed stats yet.') ?></p>
        <button onclick="fetchInsights()" class="btn btn-primary">
            <i class="bi bi-arrow-clockwise me-1"></i><?= fbt('fb_ads.fetch_now','Fetch Stats Now') ?>
        </button>
    </div>
</div>
<?php else: ?>

<!-- Charts row -->
<div class="row g-4 mb-4">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-bottom py-3 d-flex align-items-center justify-content-between">
                <h6 class="mb-0 fw-semibold"><i class="bi bi-graph-up me-2 text-muted"></i><?= fbt('fb_ads.daily_performance','Daily Performance') ?></h6>
                <div class="d-flex gap-2">
                    <button class="btn btn-sm btn-outline-secondary chart-toggle active" data-metric="impressions">Impressions</button>
                    <button class="btn btn-sm btn-outline-secondary chart-toggle" data-metric="clicks">Clicks</button>
                    <button class="btn btn-sm btn-outline-secondary chart-toggle" data-metric="spend">Spend</button>
                    <button class="btn btn-sm btn-outline-secondary chart-toggle" data-metric="ctr">CTR %</button>
                </div>
            </div>
            <div class="card-body"><canvas id="mainChart" height="120"></canvas></div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-bottom py-3">
                <h6 class="mb-0 fw-semibold"><i class="bi bi-people me-2 text-muted"></i><?= fbt('fb_ads.audience_breakdown','Audience Breakdown') ?></h6>
            </div>
            <div class="card-body d-flex align-items-center">
                <?php
                $lastRow = end($insights);
                $ageData    = $lastRow['age_breakdown']    ?? [];
                $genderData = $lastRow['gender_breakdown'] ?? [];
                ?>
                <?php if(!empty($ageData)): ?>
                <canvas id="ageChart" width="200" height="200"></canvas>
                <?php else: ?>
                <div class="text-center text-muted w-100 py-3">
                    <i class="bi bi-pie-chart display-4 d-block mb-2 opacity-25"></i>
                    <small><?= fbt('fb_ads.no_breakdown','No breakdown data') ?></small>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Daily table -->
<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-table me-2 text-muted"></i><?= fbt('fb_ads.daily_breakdown','Daily Breakdown') ?></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.date','Date') ?></th>
                        <th>Impressions</th>
                        <th>Reach</th>
                        <th>Clicks</th>
                        <th>CTR</th>
                        <th>CPC</th>
                        <th><?= fbt('fb_ads.spend','Spend') ?></th>
                        <th>Purchases</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach(array_reverse($insights) as $row): ?>
                <tr>
                    <td class="ps-3 fw-semibold"><?= $row['date'] ?></td>
                    <td><?= number_format((int)$row['impressions']) ?></td>
                    <td><?= number_format((int)($row['reach']??0)) ?></td>
                    <td><strong><?= number_format((int)$row['clicks']) ?></strong></td>
                    <td><?= number_format((float)$row['ctr'],3) ?>%</td>
                    <td><?= number_format((float)$row['cpc'],2) ?></td>
                    <td><?= number_format((float)$row['spend'],2) ?></td>
                    <td><?= (int)($row['purchases']??0) > 0 ? '<span class="badge bg-success">'.((int)$row['purchases']).'</span>' : '—' ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if(!empty($lastAdvice)): ?>
<!-- Latest AI Advice preview -->
<div class="card border-0 shadow-sm" style="border-left:4px solid #7c3aed !important">
    <div class="card-header bg-white border-bottom py-3 d-flex align-items-center justify-content-between">
        <h6 class="mb-0 fw-semibold"><i class="bi bi-stars me-2" style="color:#7c3aed"></i><?= fbt('fb_ads.ai_latest_advice','Latest AI Analysis') ?></h6>
        <a href="/admin/facebook-ads/ai-advisor/<?= $campaign['id'] ?>" class="btn btn-sm btn-outline-secondary">
            <?= fbt('fb_ads.view_full_analysis','View Full Analysis') ?> →
        </a>
    </div>
    <div class="card-body">
        <?php
        $advice = json_decode($lastAdvice['analysis'], true) ?? [];
        $scoreColor = ($advice['score']??0) >= 70 ? 'success' : (($advice['score']??0) >= 40 ? 'warning' : 'danger');
        ?>
        <div class="d-flex align-items-center gap-3 mb-3">
            <div class="rounded-circle d-flex align-items-center justify-content-center fw-bold text-white"
                 style="width:54px;height:54px;background:var(--bs-<?= $scoreColor ?>);font-size:1.2rem">
                <?= $advice['score'] ?? '?' ?>
            </div>
            <div>
                <div class="fw-bold"><?= $advice['summary'] ?? '' ?></div>
                <div class="text-muted small"><?= date('Y/m/d H:i', strtotime($lastAdvice['created_at'])) ?></div>
            </div>
        </div>
        <?php if(!empty($advice['recommendations'])): ?>
        <div class="small">
            <div class="fw-semibold mb-2"><?= fbt('fb_ads.top_recommendations','Top Recommendations:') ?></div>
            <?php foreach(array_slice($advice['recommendations'], 0, 2) as $rec): ?>
            <div class="d-flex align-items-start gap-2 mb-2">
                <span class="badge bg-<?= $rec['priority']==='high'?'danger':($rec['priority']==='medium'?'warning text-dark':'secondary') ?> mt-1"><?= $rec['priority'] ?></span>
                <div><strong><?= htmlspecialchars($rec['action'] ?? '') ?></strong><div class="text-muted"><?= htmlspecialchars($rec['reason'] ?? '') ?></div></div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
var CSRF      = '<?= \Core\System\Csrf::token() ?>';
var CAMP_ID   = <?= (int)$campaign['id'] ?>;
var isRtl     = <?= $isRtl ? 'true' : 'false' ?>;

var chartData = {
    labels:      <?= $chartDates ?>,
    impressions: <?= $chartImpr ?>,
    clicks:      <?= $chartClicks ?>,
    spend:       <?= $chartSpend ?>,
    ctr:         <?= $chartCtr ?>,
    cpc:         <?= $chartCpc ?>
};

var currentMetric = 'impressions';
var mainChart;

function buildMainChart(metric){
    var ctx = document.getElementById('mainChart');
    if(!ctx) return;
    var colors = {
        impressions: '#1877f2', clicks: '#22c55e',
        spend: '#f59e0b', ctr: '#8b5cf6', cpc: '#ef4444'
    };
    var labels = {
        impressions:'Impressions', clicks:'Clicks',
        spend:'Spend (DZD)', ctr:'CTR (%)', cpc:'CPC'
    };
    if(mainChart) mainChart.destroy();
    mainChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: chartData.labels,
            datasets: [{
                label: labels[metric],
                data: chartData[metric],
                borderColor: colors[metric],
                backgroundColor: colors[metric]+'20',
                fill: true,
                tension: 0.4,
                pointRadius: chartData.labels.length > 14 ? 2 : 4,
                pointHoverRadius: 6,
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: false } },
            scales: {
                x: { grid: { display: false } },
                y: { beginAtZero: true, grid: { color: '#f1f5f9' } }
            }
        }
    });
}
buildMainChart('impressions');

document.querySelectorAll('.chart-toggle').forEach(function(btn){
    btn.addEventListener('click',function(){
        document.querySelectorAll('.chart-toggle').forEach(b=>b.classList.remove('active','btn-primary'));
        document.querySelectorAll('.chart-toggle').forEach(b=>b.classList.add('btn-outline-secondary'));
        btn.classList.remove('btn-outline-secondary'); btn.classList.add('active','btn-primary');
        buildMainChart(btn.dataset.metric);
    });
});

// Age breakdown pie
<?php if(!empty($ageData)): ?>
(function(){
    var ctx = document.getElementById('ageChart');
    if(!ctx) return;
    var ages   = <?= json_encode(array_column($ageData, 'age_range')) ?>;
    var clicks = <?= json_encode(array_column($ageData, 'clicks')) ?>;
    var colors = ['#1877f2','#22c55e','#f59e0b','#ef4444','#8b5cf6','#06b6d4','#f97316'];
    new Chart(ctx, {
        type: 'doughnut',
        data: { labels: ages, datasets: [{ data: clicks, backgroundColor: colors.slice(0,ages.length), borderWidth: 2 }] },
        options: { responsive: true, plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } } }
    });
})();
<?php endif; ?>

// Fetch insights
function fetchInsights(){
    var btn = document.getElementById('fetch-btn');
    var res = document.getElementById('fetch-result');
    btn.disabled=true;
    btn.innerHTML='<div class="spinner-border spinner-border-sm me-1"></div><?= fbt('fb_ads.fetching','Fetching...') ?>';
    res.style.display='none';

    var fd=new FormData(); fd.append('_csrf',CSRF);
    fetch('/admin/facebook-ads/fetch-insights/'+CAMP_ID,{method:'POST',body:fd})
    .then(r=>r.json()).then(d=>{
        btn.disabled=false;
        btn.innerHTML='<i class="bi bi-arrow-clockwise me-1"></i><?= fbt('fb_ads.fetch_insights','Fetch Latest Stats') ?>';
        res.style.display='';
        if(d.success){
            res.innerHTML='<div class="alert alert-success border-0 shadow-sm">✅ <?= fbt('fb_ads.insights_fetched','Stats fetched successfully!') ?> '+
                '<a href="" class="alert-link ms-2"><?= fbt('fb_ads.refresh_page','Refresh to see charts') ?></a></div>';
            setTimeout(()=>location.reload(),2000);
        } else {
            res.innerHTML='<div class="alert alert-danger border-0 shadow-sm">❌ '+d.message+'</div>';
        }
    }).catch(e=>{
        btn.disabled=false;
        btn.innerHTML='<i class="bi bi-arrow-clockwise me-1"></i><?= fbt('fb_ads.fetch_insights','Fetch Latest Stats') ?>';
        res.innerHTML='<div class="alert alert-danger border-0 shadow-sm">❌ '+e.message+'</div>';
        res.style.display='';
    });
}
</script>

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