<?php
if (!defined('ROOT_PATH')) { http_response_code(403); exit; }
require_once ROOT_PATH . '/admin/templates/header.php';
$fbMsg = $_SESSION['fb_success'] ?? ''; $fbErr = $_SESSION['fb_error'] ?? '';
unset($_SESSION['fb_success'], $_SESSION['fb_error']);
$statusColors = ['draft'=>'bg-secondary','pending'=>'bg-info text-dark','active'=>'bg-success','paused'=>'bg-warning text-dark','deleted'=>'bg-danger','error'=>'bg-danger'];
$objectiveLabels = ['OUTCOME_SALES'=>'💰 Sales','OUTCOME_TRAFFIC'=>'🔗 Traffic','OUTCOME_AWARENESS'=>'📢 Awareness','OUTCOME_ENGAGEMENT'=>'💬 Engagement'];
?>
<div class="content-wrapper"><section class="content pt-3"><div class="container-fluid pb-5">

<?php if($fbMsg): ?><div class="alert alert-success alert-dismissible fade show border-0 shadow-sm"><i class="bi bi-check-circle-fill me-2"></i><?= htmlspecialchars($fbMsg) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
<?php if($fbErr): ?><div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm"><i class="bi bi-exclamation-triangle-fill me-2"></i><?= htmlspecialchars($fbErr) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

<div class="d-flex align-items-center justify-content-between mb-4">
    <div>
        <h3 class="mb-1 fw-bold"><i class="bi bi-facebook me-2" style="color:#1877f2"></i><?= fbt('fb_ads.title','Facebook Ads Manager') ?></h3>
        <p class="text-muted small mb-0"><?= fbt('fb_ads.subtitle','Create and manage paid Facebook & Instagram ads') ?></p>
    </div>
    <div class="d-flex gap-2">
        <?php if($isConfigured): ?>
        <button class="btn btn-outline-secondary btn-sm" onclick="syncStats()">
            <i class="bi bi-arrow-clockwise me-1"></i><?= fbt('fb_ads.sync_stats','Sync Stats') ?>
        </button>
        <?php endif; ?>
        <a href="/admin/facebook-ads/agent" class="btn fw-semibold btn-sm"
           style="background:linear-gradient(135deg,#7c3aed,#a855f7);color:#fff;border:none">
            <i class="bi bi-robot me-1"></i><?= fbt('fb_ads.ai_agent','AI Agent') ?>
        </a>
        <a href="/admin/facebook-ads/settings" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-gear me-1"></i><?= fbt('fb_ads.settings','Settings') ?>
        </a>
    </div>
</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 fs-5"><?= fbt('fb_ads.setup_required','Setup Required') ?></div>
            <div style="opacity:.9;font-size:.9rem"><?= fbt('fb_ads.setup_hint','Connect your Facebook Ad Account to start launching ads.') ?></div>
        </div>
        <a href="/admin/facebook-ads/settings" class="btn btn-light fw-bold px-4">
            <?= fbt('fb_ads.connect_now','Connect Facebook →') ?>
        </a>
    </div>
</div>
<?php endif; ?>

<?php if(!$aiAvailable): ?>
<div class="alert alert-info border-0 shadow-sm mb-4 small">
    <i class="bi bi-stars me-2 text-primary"></i><?= fbt('fb_ads.ai_hint','Configure AI to auto-generate ad copy.') ?>
    <a href="/admin/settings/ai" class="alert-link ms-2"><?= fbt('fb_ads.configure_ai','Configure AI →') ?></a>
</div>
<?php endif; ?>

<!-- Stats -->
<div class="row g-3 mb-4">
<?php foreach([
    ['bi-collection-fill','primary',  fbt('fb_ads.stat_total','Total Ads'),$stats['total']],
    ['bi-lightning-fill',  'success', fbt('fb_ads.stat_active','Active'),$stats['active']],
    ['bi-cursor-fill',     'info',    fbt('fb_ads.stat_clicks','Total Clicks'),number_format($stats['clicks'])],
    ['bi-cash-stack',      'warning', fbt('fb_ads.stat_spend','Total Spend'),number_format($stats['spend'],2).' DZD'],
] as [$icon,$color,$label,$val]): ?>
<div class="col-6 col-xl-3">
    <div class="card border-0 shadow-sm h-100">
        <div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-<?= $color ?> bg-opacity-10 text-<?= $color ?> d-flex align-items-center justify-content-center" style="width:46px;height:46px;font-size:1.3rem">
                <i class="bi <?= $icon ?>"></i>
            </div>
            <div><div class="fw-bold fs-5 lh-1"><?= $val ?></div><div class="text-muted small"><?= $label ?></div></div>
        </div>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- Choose product to launch ad -->
<?php if($isConfigured): ?>
<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-plus-circle me-2 text-primary"></i><?= fbt('fb_ads.launch_new','Launch New Ad') ?></h6>
    </div>
    <div class="card-body">
        <?php
        $products = db()->query("SELECT id,title,featured_image,price,currency FROM products WHERE status='active' ORDER BY updated_at DESC LIMIT 20")->fetchAll(\PDO::FETCH_ASSOC);
        ?>
        <div class="row g-2">
        <?php foreach($products as $prod): ?>
        <div class="col-md-3 col-sm-4 col-6">
            <a href="/admin/facebook-ads/create/<?= $prod['id'] ?>" class="text-decoration-none">
                <div class="card border h-100" style="transition:all .15s;cursor:pointer" onmouseover="this.style.borderColor='#1877f2'" onmouseout="this.style.borderColor=''">
                    <?php if(!empty($prod['featured_image'])): ?>
                    <img src="<?= htmlspecialchars($prod['featured_image']) ?>" class="card-img-top object-fit-cover" style="height:100px">
                    <?php endif; ?>
                    <div class="card-body p-2">
                        <div class="fw-semibold small text-dark text-truncate"><?= htmlspecialchars($prod['title']) ?></div>
                        <div class="text-primary small"><?= number_format((float)$prod['price']) ?> <?= $prod['currency'] ?></div>
                    </div>
                </div>
            </a>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Campaigns list -->
<?php if(!empty($campaigns)): ?>
<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-collection me-2 text-muted"></i><?= fbt('fb_ads.campaigns','Ad Campaigns') ?></h6>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3"><?= fbt('fb_ads.col_campaign','Campaign') ?></th>
                        <th><?= fbt('fb_ads.col_objective','Objective') ?></th>
                        <th><?= fbt('fb_ads.col_budget','Budget/Day') ?></th>
                        <th><?= fbt('fb_ads.col_stats','Stats') ?></th>
                        <th><?= fbt('fb_ads.col_status','Status') ?></th>
                        <th class="text-end pe-3"><?= fbt('actions.actions','Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach($campaigns as $c): ?>
                <tr>
                    <td class="ps-3">
                        <div class="d-flex align-items-center gap-2">
                            <?php if(!empty($c['featured_image'])): ?>
                            <img src="<?= htmlspecialchars($c['featured_image']) ?>" width="38" height="38" class="rounded-2 border object-fit-cover">
                            <?php endif; ?>
                            <div>
                                <div class="fw-semibold small"><?= htmlspecialchars($c['name']) ?></div>
                                <div class="text-muted" style="font-size:.72rem"><?= htmlspecialchars($c['product_title'] ?? '') ?></div>
                            </div>
                        </div>
                    </td>
                    <td><span class="small"><?= $objectiveLabels[$c['objective']] ?? $c['objective'] ?></span></td>
                    <td class="small"><?= number_format($c['daily_budget']/100) ?> DZD</td>
                    <td>
                        <div class="small text-muted">
                            <i class="bi bi-eye me-1"></i><?= number_format($c['impressions']) ?>
                            <span class="mx-2">·</span>
                            <i class="bi bi-cursor me-1"></i><?= number_format($c['clicks']) ?>
                            <span class="mx-2">·</span>
                            <i class="bi bi-cash me-1"></i><?= number_format($c['spend'],2) ?>
                        </div>
                    </td>
                    <td>
                        <span class="badge <?= $statusColors[$c['status']] ?? 'bg-secondary' ?>"><?= ucfirst($c['status']) ?></span>
                        <?php if($c['status'] === 'error'): ?>
                        <i class="bi bi-info-circle text-danger ms-1" title="<?= htmlspecialchars($c['error_message'] ?? '') ?>"></i>
                        <?php endif; ?>
                    </td>
                    <td class="text-end pe-3">
                        <div class="d-flex gap-1 justify-content-end">
                            <a href="/admin/facebook-ads/campaign/<?= $c['id'] ?>" class="btn btn-sm btn-outline-primary" title="View">
                                <i class="bi bi-eye"></i>
                            </a>
                            <?php if($c['fb_campaign_id']): ?>
                            <a href="https://www.facebook.com/adsmanager/manage/campaigns?act=<?= $cfg['ad_account_id'] ?? '' ?>" target="_blank" class="btn btn-sm btn-outline-secondary" title="Ads Manager">
                                <i class="bi bi-box-arrow-up-right"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<div id="sync-result" class="mt-3"></div>

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

<script>
var CSRF = '<?= \Core\System\Csrf::token() ?>';
function syncStats(){
    var el = document.getElementById('sync-result');
    el.innerHTML = '<div class="alert alert-info border-0 small py-2">⏳ <?= fbt('fb_ads.syncing','Syncing stats...') ?></div>';
    var fd = new FormData(); fd.append('_csrf', CSRF);
    fetch('/admin/facebook-ads/sync-stats',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        el.innerHTML = d.success
            ? '<div class="alert alert-success border-0 small py-2">✅ <?= fbt('fb_ads.synced','Stats synced.') ?> Updated: '+d.updated+' campaigns.</div>'
            : '<div class="alert alert-danger border-0 small py-2">❌ '+d.message+'</div>';
        if(d.success && d.updated > 0) setTimeout(()=>location.reload(), 1500);
    });
}
</script>

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