<?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>
        <h4 class="fw-bold mb-1"><i class="bi bi-stars me-2" style="color:#7c3aed"></i><?= fbt('fb_ads.ai_advisor_title','AI Campaign Advisor') ?></h4>
        <div class="text-muted small"><?= htmlspecialchars($campaign['name']) ?> · <?= htmlspecialchars($campaign['product_title'] ?? '') ?></div>
    </div>
    <div class="d-flex gap-2">
        <?php if($aiAvailable && !empty($insights)): ?>
        <button id="analyze-btn" onclick="runAnalysis()" class="btn fw-semibold px-4"
                style="background:linear-gradient(135deg,#7c3aed,#a855f7);color:#fff;border:none">
            <i class="bi bi-stars me-2"></i><?= fbt('fb_ads.run_analysis','Run AI Analysis') ?>
        </button>
        <?php elseif(empty($insights)): ?>
        <a href="/admin/facebook-ads/analytics/<?= $campaign['id'] ?>" class="btn btn-outline-primary">
            <i class="bi bi-arrow-clockwise me-1"></i><?= fbt('fb_ads.fetch_stats_first','Fetch Stats First') ?>
        </a>
        <?php endif; ?>
        <a href="/admin/facebook-ads/analytics/<?= $campaign['id'] ?>" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-bar-chart me-1"></i><?= fbt('fb_ads.analytics','Analytics') ?>
        </a>
        <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>

<!-- Loading state -->
<div id="analysis-loading" style="display:none" class="mb-4">
    <div class="card border-0 shadow-sm">
        <div class="card-body py-4">
            <div class="d-flex align-items-center gap-3 mb-3">
                <div class="spinner-border" style="color:#7c3aed;width:1.8rem;height:1.8rem"></div>
                <div>
                    <div class="fw-semibold fs-5" style="color:#7c3aed" id="analysis-phase"><?= fbt('fb_ads.analyzing','AI is analyzing your campaign...') ?></div>
                    <div class="text-muted small"><?= fbt('fb_ads.analysis_hint','This may take 15-30 seconds') ?></div>
                </div>
            </div>
            <div class="progress" style="height:6px"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width:100%;background:#7c3aed"></div></div>
        </div>
    </div>
</div>

<!-- Latest analysis -->
<?php if(!empty($allAdvice)): ?>
<?php $latest = $allAdvice[0]; $analysis = json_decode($latest['analysis'], true) ?? []; ?>
<?php
$scoreColor = ($analysis['score']??0) >= 70 ? '#22c55e' : (($analysis['score']??0) >= 40 ? '#f59e0b' : '#ef4444');
$perfIcons  = ['good'=>'🟢','average'=>'🟡','poor'=>'🔴'];
$perfIcon   = $perfIcons[$analysis['performance']??'average'] ?? '🟡';
?>

<div id="analysis-result">

<!-- Score card -->
<div class="row g-4 mb-4">
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100 text-center py-4" style="border-top:4px solid <?= $scoreColor ?> !important">
            <div class="card-body">
                <div style="width:90px;height:90px;border-radius:50%;background:<?= $scoreColor ?>20;border:4px solid <?= $scoreColor ?>;display:flex;align-items:center;justify-content:center;margin:0 auto 14px;font-size:1.8rem;font-weight:900;color:<?= $scoreColor ?>">
                    <?= $analysis['score'] ?? 0 ?>
                </div>
                <div class="fw-bold fs-5"><?= fbt('fb_ads.performance_score','Performance Score') ?></div>
                <div class="mt-2"><?= $perfIcon ?> <span class="fw-semibold"><?= ucfirst($analysis['performance']??'average') ?></span></div>
                <hr class="my-3">
                <div class="text-muted small text-start"><?= htmlspecialchars($analysis['summary'] ?? '') ?></div>
                <div class="text-muted" style="font-size:.7rem;margin-top:10px"><?= fbt('fb_ads.analyzed_on','Analyzed:') ?> <?= date('Y/m/d H:i', strtotime($latest['created_at'])) ?></div>
            </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 text-success"><i class="bi bi-check-circle-fill me-2"></i><?= fbt('fb_ads.strengths','Strengths') ?></h6>
            </div>
            <div class="card-body p-0">
            <?php foreach($analysis['strengths'] ?? [] as $s): ?>
            <div class="d-flex align-items-start gap-2 p-3 border-bottom">
                <i class="bi bi-check-circle-fill text-success mt-1 flex-shrink-0"></i>
                <span class="small"><?= htmlspecialchars($s) ?></span>
            </div>
            <?php endforeach; ?>
            </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 text-danger"><i class="bi bi-exclamation-circle-fill me-2"></i><?= fbt('fb_ads.weaknesses','Weaknesses') ?></h6>
            </div>
            <div class="card-body p-0">
            <?php foreach($analysis['weaknesses'] ?? [] as $w): ?>
            <div class="d-flex align-items-start gap-2 p-3 border-bottom">
                <i class="bi bi-x-circle-fill text-danger mt-1 flex-shrink-0"></i>
                <span class="small"><?= htmlspecialchars($w) ?></span>
            </div>
            <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- Key Insights -->
<?php if(!empty($analysis['insights'])): ?>
<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-lightbulb-fill me-2 text-warning"></i><?= fbt('fb_ads.key_insights','Key Insights') ?></h6>
    </div>
    <div class="card-body">
        <div class="row g-3">
        <?php foreach($analysis['insights'] as $insight):
            $ic = $insight['type']==='positive' ? 'border-success bg-success bg-opacity-10' : ($insight['type']==='negative' ? 'border-danger bg-danger bg-opacity-10' : 'border-primary bg-primary bg-opacity-10');
            $ti = $insight['type']==='positive' ? 'text-success' : ($insight['type']==='negative' ? 'text-danger' : 'text-primary');
        ?>
        <div class="col-md-6">
            <div class="p-3 border rounded-3 <?= $ic ?>">
                <div class="fw-semibold small <?= $ti ?> mb-1"><?= htmlspecialchars($insight['title'] ?? '') ?></div>
                <div class="small text-muted"><?= htmlspecialchars($insight['detail'] ?? '') ?></div>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Recommendations -->
<?php if(!empty($analysis['recommendations'])): ?>
<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-list-check me-2 text-primary"></i><?= fbt('fb_ads.recommendations','Action Recommendations') ?></h6>
    </div>
    <div class="card-body p-0">
    <?php foreach($analysis['recommendations'] as $i => $rec):
        $pColor = $rec['priority']==='high' ? 'danger' : ($rec['priority']==='medium' ? 'warning text-dark' : 'secondary');
    ?>
    <div class="d-flex align-items-start gap-3 p-3 border-bottom">
        <span class="badge bg-<?= $pColor ?> mt-1 flex-shrink-0"><?= $rec['priority'] ?></span>
        <div class="flex-grow-1">
            <div class="fw-semibold small"><?= htmlspecialchars($rec['action'] ?? '') ?></div>
            <div class="text-muted small mt-1"><?= htmlspecialchars($rec['reason'] ?? '') ?></div>
            <?php if(!empty($rec['expected_impact'])): ?>
            <div class="small mt-1"><span class="badge bg-light text-dark border"><i class="bi bi-graph-up me-1"></i><?= htmlspecialchars($rec['expected_impact']) ?></span></div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Next Campaign Config (الأهم!) -->
<?php $next = $latest['next_config'] ?? []; if(!empty($next)): ?>
<div class="card border-0 shadow-sm mb-4" style="border:2px solid #7c3aed !important">
    <div class="card-header border-0 py-4" style="background:linear-gradient(135deg,#4c1d95,#7c3aed);color:#fff">
        <div class="d-flex align-items-center gap-3">
            <div style="width:46px;height:46px;background:rgba(255,255,255,.15);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.5rem">🚀</div>
            <div>
                <div class="fw-bold fs-5"><?= fbt('fb_ads.next_campaign_config','Next Campaign — AI Optimized Config') ?></div>
                <div style="opacity:.85;font-size:.83rem"><?= fbt('fb_ads.based_on_data','Based on your campaign performance data') ?></div>
            </div>
            <a href="/admin/facebook-ads/create/<?= $campaign['product_id'] ?>" class="btn btn-light fw-bold ms-auto px-4">
                <i class="bi bi-plus-lg me-1"></i><?= fbt('fb_ads.launch_next','Launch Next Campaign') ?>
            </a>
        </div>
    </div>
    <div class="card-body">
        <div class="row g-4">
            <div class="col-md-6">
                <div class="p-3 bg-light rounded-3">
                    <div class="fw-semibold mb-3"><i class="bi bi-sliders me-2 text-primary"></i><?= fbt('fb_ads.suggested_settings','Suggested Settings') ?></div>
                    <table class="table table-sm table-borderless mb-0 small">
                        <tr><td class="text-muted"><?= fbt('fb_ads.daily_budget','Budget/Day') ?></td><td class="fw-semibold"><?= number_format((int)($next['budget_suggestion']??0)) ?> DZD</td></tr>
                        <tr><td class="text-muted"><?= fbt('fb_ads.duration','Duration') ?></td><td class="fw-semibold"><?= $next['duration_suggestion'] ?? 7 ?> <?= fbt('fb_ads.days','days') ?></td></tr>
                        <tr><td class="text-muted"><?= fbt('fb_ads.age_range','Age Range') ?></td><td class="fw-semibold"><?= ($next['age_min']??18).'-'.($next['age_max']??45) ?></td></tr>
                        <?php if(!empty($next['best_day_to_run'])): ?>
                        <tr><td class="text-muted"><?= fbt('fb_ads.best_days','Best Days') ?></td><td class="fw-semibold"><?= htmlspecialchars($next['best_day_to_run']) ?></td></tr>
                        <?php endif; ?>
                    </table>
                </div>
            </div>
            <div class="col-md-6">
                <?php if(!empty($next['audience_refinement'])): ?>
                <div class="p-3 bg-light rounded-3 mb-3">
                    <div class="fw-semibold mb-2"><i class="bi bi-people me-2 text-success"></i><?= fbt('fb_ads.audience_refinement','Audience Refinement') ?></div>
                    <div class="small text-muted"><?= htmlspecialchars($next['audience_refinement']) ?></div>
                </div>
                <?php endif; ?>
                <?php if(!empty($next['ad_copy_tips'])): ?>
                <div class="p-3 bg-light rounded-3">
                    <div class="fw-semibold mb-2"><i class="bi bi-pencil me-2 text-warning"></i><?= fbt('fb_ads.copy_tips','Ad Copy Tips') ?></div>
                    <ul class="mb-0 ps-3 small">
                    <?php foreach((array)$next['ad_copy_tips'] as $tip): ?>
                        <li class="text-muted mb-1"><?= htmlspecialchars($tip) ?></li>
                    <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- History of analyses -->
<?php if(count($allAdvice) > 1): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom py-3"><h6 class="mb-0 fw-semibold"><i class="bi bi-clock-history me-2 text-muted"></i><?= fbt('fb_ads.analysis_history','Analysis History') ?></h6></div>
    <div class="card-body p-0">
    <?php foreach(array_slice($allAdvice, 1) as $old):
        $oldData = json_decode($old['analysis'], true) ?? [];
        $c2 = ($oldData['score']??0)>=70?'success':(($oldData['score']??0)>=40?'warning':'danger');
    ?>
    <div class="d-flex align-items-center gap-3 px-3 py-2 border-bottom">
        <div class="badge bg-<?= $c2 ?>"><?= $oldData['score']??'?' ?></div>
        <div class="flex-grow-1 small text-muted"><?= htmlspecialchars($oldData['summary']??'') ?></div>
        <div class="small text-muted"><?= date('Y/m/d', strtotime($old['created_at'])) ?></div>
    </div>
    <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

</div><!-- /#analysis-result -->

<?php elseif(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><?= fbt('fb_ads.no_data_for_advisor','No stats data yet. Fetch insights first, then run AI analysis.') ?></p>
        <a href="/admin/facebook-ads/analytics/<?= $campaign['id'] ?>" class="btn btn-primary">
            <i class="bi bi-arrow-clockwise me-1"></i><?= fbt('fb_ads.go_to_analytics','Go to Analytics') ?>
        </a>
    </div>
</div>
<?php else: ?>
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5">
        <i class="bi bi-stars display-4 d-block mb-3 opacity-50" style="color:#7c3aed"></i>
        <p class="text-muted"><?= fbt('fb_ads.no_analysis_yet','No AI analysis yet. Click the button above to run your first analysis.') ?></p>
        <?php if($aiAvailable): ?>
        <button onclick="runAnalysis()" class="btn fw-semibold px-4"
                style="background:linear-gradient(135deg,#7c3aed,#a855f7);color:#fff;border:none">
            <i class="bi bi-stars me-2"></i><?= fbt('fb_ads.run_first_analysis','Run First Analysis') ?>
        </button>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

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

<script>
var CSRF    = '<?= \Core\System\Csrf::token() ?>';
var CAMP_ID = <?= (int)$campaign['id'] ?>;

var phases = [
    '<?= fbt('fb_ads.phase1','Reading campaign metrics...') ?>',
    '<?= fbt('fb_ads.phase2','Analyzing CTR and CPC performance...') ?>',
    '<?= fbt('fb_ads.phase3','Identifying best audience segments...') ?>',
    '<?= fbt('fb_ads.phase4','Comparing with industry benchmarks...') ?>',
    '<?= fbt('fb_ads.phase5','Generating recommendations...') ?>',
    '<?= fbt('fb_ads.phase6','Building next campaign config...') ?>',
];

function runAnalysis(){
    var btn     = document.getElementById('analyze-btn');
    var loading = document.getElementById('analysis-loading');
    var result  = document.getElementById('analysis-result');
    if(btn) btn.disabled = true;
    loading.style.display = '';
    if(result) result.style.display = 'none';

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

    var fd = new FormData(); fd.append('_csrf', CSRF);
    fetch('/admin/facebook-ads/ai-advisor/'+CAMP_ID, {method:'POST', body:fd})
    .then(r=>r.json())
    .then(function(d){
        clearInterval(timer);
        loading.style.display = 'none';
        if(btn) btn.disabled = false;

        if(d.success){
            setTimeout(()=>location.reload(), 500);
        } else {
            alert('❌ ' + (d.message || 'Analysis failed.'));
        }
    })
    .catch(function(e){
        clearInterval(timer);
        loading.style.display = 'none';
        if(btn) btn.disabled = false;
        alert('❌ Network error: ' + e.message);
    });
}
</script>

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