<?php
$pageTitle = 'Sponsor Campaigns';
include_once 'includes/header.php';

if (!in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin'])) {
    header('Location: dashboard.php');
    exit();
}

$settingModel = new Setting();
$sponsorModel = new Sponsorship();

$campaigns = $sponsorModel->getAllCampaigns();
$analytics = $sponsorModel->getSystemAnalytics();
$total_revenue = $sponsorModel->getTotalRevenue();

$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

include_once 'includes/sidebar.php';
?>

<h1>Sponsor Campaigns</h1>

<?php if (isset($_SESSION['flash_message'])): ?><div class="message success"><?php echo $_SESSION['flash_message']; unset($_SESSION['flash_message']); ?></div><?php endif; ?>
<?php if (isset($_SESSION['flash_error'])): ?><div class="message error"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></div><?php endif; ?>

<div class="dashboard-section">
    <div class="revenue-summary" style="margin-bottom: 20px; display: flex; gap: 20px;">
        <div class="stat-card" style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border-left: 5px solid #2ecc71; flex: 1;">
            <h3 style="margin: 0 0 5px 0; font-size: 0.9rem; color: #7f8c8d; text-transform: uppercase;">Total Revenue</h3>
            <div style="font-size: 2rem; font-weight: 800; color: #2c3e50;"><?php echo $currency_symbol . number_format($total_revenue, 2); ?></div>
        </div>
    </div>

    <h2 class="dashboard-title">System Performance (Last 30 Days)</h2>
    <div class="chart-container" style="position: relative; height: 300px; width: 100%;">
        <canvas id="systemPerformanceChart"></canvas>
    </div>
</div>

<div class="dashboard-section">
    <div class="table-wrapper">
        <table class="styled-table">
            <thead>
                <tr>
                    <th>Sponsor</th>
                    <th>Package</th>
                    <th>Type</th>
                    <th>Status</th>
                    <th>Views</th>
                    <th>Clicks</th>
                    <th>CTR</th>
                    <th>Start Date</th>
                    <th>End Date</th>
                    <th>Content</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($campaigns)): ?>
                    <tr><td colspan="10">No campaigns found.</td></tr>
                <?php else: ?>
                    <?php foreach ($campaigns as $camp): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($camp->first_name . ' ' . $camp->last_name); ?></strong><br>
                                <small><?php echo htmlspecialchars($camp->email); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($camp->package_name); ?></td>
                            <td><?php echo ucfirst($camp->package_type); ?></td>
                            <td>
                                <span class="badge status-<?php echo $camp->status; ?>">
                                    <?php echo ucfirst($camp->status); ?>
                                </span>
                            </td>
                            <td><?php echo number_format($camp->views ?? 0); ?></td>
                            <td><?php echo number_format($camp->clicks ?? 0); ?></td>
                            <td>
                                <?php 
                                    $views = $camp->views ?? 0;
                                    $clicks = $camp->clicks ?? 0;
                                    $ctr = ($views > 0) ? ($clicks / $views) * 100 : 0;
                                    echo number_format($ctr, 2) . '%';
                                ?>
                            </td>
                            <td><?php echo date('d M Y', strtotime($camp->start_date)); ?></td>
                            <td><?php echo date('d M Y', strtotime($camp->end_date)); ?></td>
                            <td>
                                <a href="<?php echo htmlspecialchars($camp->ad_content); ?>" target="_blank" class="btn-sm">View Ad</a>
                            </td>
                            <td>
                                <?php if ($camp->status === 'pending'): ?>
                                    <form action="sponsor_campaign_approval.php" method="POST" style="display:inline;">
                                        <input type="hidden" name="campaign_id" value="<?php echo $camp->id; ?>">
                                        <input type="hidden" name="action" value="approve">
                                        <button type="submit" class="btn-sm btn-success" title="Approve"><i class="fa-solid fa-check"></i></button>
                                    </form>
                                    <form action="sponsor_campaign_approval.php" method="POST" style="display:inline;">
                                        <input type="hidden" name="campaign_id" value="<?php echo $camp->id; ?>">
                                        <input type="hidden" name="action" value="reject">
                                        <button type="submit" class="btn-sm btn-danger" title="Reject" onclick="return confirm('Reject this campaign?');"><i class="fa-solid fa-xmark"></i></button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<style>
.status-active { background: #d4edda; color: #155724; }
.status-pending { background: #fff3cd; color: #856404; }
.status-rejected { background: #f8d7da; color: #721c24; }
.status-completed { background: #e2e3e5; color: #383d41; }
.badge { padding: 4px 8px; border-radius: 4px; font-size: 0.85rem; font-weight: 600; text-transform: uppercase; }
.btn-success { background-color: #2ecc71; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; }
.btn-danger { background-color: #e74c3c; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; }
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const analyticsData = <?php echo json_encode($analytics); ?>;
    
    if (analyticsData && analyticsData.length > 0) {
        const labels = analyticsData.map(item => {
            const date = new Date(item.date);
            return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
        });
        const views = analyticsData.map(item => item.total_views);
        const clicks = analyticsData.map(item => item.total_clicks);

        const ctx = document.getElementById('systemPerformanceChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Total Views',
                        data: views,
                        borderColor: '#3498db',
                        backgroundColor: 'rgba(52, 152, 219, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: 'Total Clicks',
                        data: clicks,
                        borderColor: '#e74c3c',
                        backgroundColor: 'rgba(231, 76, 60, 0.1)',
                        tension: 0.4,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'top' },
                    tooltip: { mode: 'index', intersect: false }
                },
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });
    } else {
        document.querySelector('.chart-container').innerHTML = '<p class="no-data-msg" style="text-align:center; padding-top: 130px;">No analytics data available yet.</p>';
    }
});
</script>

<?php include_once 'includes/footer.php'; ?>