<?php
require_once '../core/bootstrap.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Sponsor Dashboard';
include 'includes/header.php';

$sponsorModel = new Sponsorship();
$walletModel = new Wallet();
$leagueModel = new League();
$fixtureModel = new Fixture();

// --- Auto-Migration for Analytics Columns ---
$db = new Database();
try {
    $db->query("SELECT views FROM sponsor_campaigns LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    $db->query("ALTER TABLE sponsor_campaigns ADD COLUMN views INT(11) NOT NULL DEFAULT 0, ADD COLUMN clicks INT(11) NOT NULL DEFAULT 0");
    $db->execute();
}

// --- Auto-Migration for Analytics Table ---
try {
    $db->query("SELECT 1 FROM sponsor_campaign_analytics LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    $db->query("CREATE TABLE IF NOT EXISTS sponsor_campaign_analytics (
        id INT AUTO_INCREMENT PRIMARY KEY,
        campaign_id INT NOT NULL,
        date DATE NOT NULL,
        views INT DEFAULT 0,
        clicks INT DEFAULT 0,
        UNIQUE KEY unique_campaign_date (campaign_id, date)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $db->execute();
}

// --- Auto-Migration for 'paused' status ---
try {
    $db->query("SHOW COLUMNS FROM sponsor_campaigns LIKE 'status'");
    $col = $db->single();
    if ($col && stripos($col->Type, "'paused'") === false) {
        $db->query("ALTER TABLE sponsor_campaigns MODIFY COLUMN status ENUM('pending','active','rejected','completed','paused') NOT NULL DEFAULT 'active'");
        $db->execute();
    }
} catch (Exception $e) {
    // Ignore
}

// --- Auto-Migration for Advertiser Features ---
try {
    $db->query("SELECT daily_budget FROM sponsor_campaigns LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    $db->query("ALTER TABLE sponsor_campaigns 
        ADD COLUMN name VARCHAR(255) DEFAULT NULL,
        ADD COLUMN daily_budget DECIMAL(10,2) DEFAULT 0.00,
        ADD COLUMN total_budget DECIMAL(10,2) DEFAULT 0.00,
        ADD COLUMN remaining_budget DECIMAL(10,2) DEFAULT 0.00,
        ADD COLUMN payment_model ENUM('flat','ppc','ppv') DEFAULT 'flat',
        ADD COLUMN target_url VARCHAR(255) DEFAULT NULL,
        ADD COLUMN contact_number VARCHAR(50) DEFAULT NULL");
    $db->execute();
}

// --- Auto-Migration for Sponsor Profiles ---
try {
    $db->query("SELECT 1 FROM sponsor_profiles LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    $db->query("CREATE TABLE IF NOT EXISTS `sponsor_profiles` (
        `user_id` int(11) NOT NULL,
        `business_name` varchar(255) NOT NULL,
        `business_description` text DEFAULT NULL,
        `business_logo` varchar(255) DEFAULT NULL,
        `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
        PRIMARY KEY (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    $db->execute();
}

$user_id = $_SESSION['user_id'];
$wallet = $walletModel->getOrCreateWallet('user', $user_id);
$packages = $sponsorModel->getAllPackages(true);
$my_campaigns = $sponsorModel->getCampaignsByUser($user_id);

// --- Separate Data for Sponsors vs Advertisers ---
$sponsorship_packages = [];
$ad_packages = [];
foreach ($packages as $pkg) {
    if ($pkg->type === 'ad') {
        $ad_packages[] = $pkg;
    } else {
        $sponsorship_packages[] = $pkg;
    }
}

$sponsorships = [];
$ad_campaigns = [];
foreach ($my_campaigns as $camp) {
    if ($camp->package_type === 'ad') {
        $ad_campaigns[] = $camp;
    } else {
        $sponsorships[] = $camp;
    }
}

$sponsor_profile = $sponsorModel->getSponsorProfileByUserId($user_id);

$leagues = $leagueModel->getAll();
$upcoming_fixtures = $fixtureModel->getUpcomingFixtures(1, 20); // Get next 20 fixtures

// Calculate Totals
$total_views = 0;
$total_clicks = 0;
foreach ($my_campaigns as $c) { $total_views += ($c->views ?? 0); $total_clicks += ($c->clicks ?? 0); }
$avg_ctr = $total_views > 0 ? ($total_clicks / $total_views) * 100 : 0;

// Fetch Analytics Data for Chart
$analytics_data = $sponsorModel->getAnalyticsForUser($user_id);
?>

<div class="page-content">
    <div class="matches-header">
        <h1>Advertising Center</h1>
        <div class="wallet-info-hero">
            <span class="label">Wallet Balance</span>
            <span class="value">$<?php echo number_format($wallet->balance, 2); ?></span>
            <a href="wallet.php" class="btn-sm btn-hero-secondary">Add Funds</a>
        </div>
        <div class="wallet-info-hero" style="margin-right: 20px; background: rgba(255,255,255,0.1);">
            <span class="label">Total Reach</span>
            <span class="value"><?php echo number_format($total_views); ?> <small style="font-size: 0.8rem; font-weight: normal;">Views</small></span>
            <span class="value" style="font-size: 1rem; margin-top: 5px;"><?php echo number_format($total_clicks); ?> <small style="font-size: 0.7rem; font-weight: normal;">Clicks (<?php echo number_format($avg_ctr, 2); ?>% CTR)</small></span>
        </div>
    </div>

    <?php 
    if (!empty($unread_notifications)) {
        foreach ($unread_notifications as $notif) {
            if ($notif->type === 'campaign_status') {
                $alertClass = strpos(strtolower($notif->message), 'rejected') !== false ? 'error' : 'success';
                echo '<div class="status-message ' . $alertClass . '" style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">';
                echo '<span>' . htmlspecialchars($notif->message) . '</span>';
                echo '<button class="btn-sm btn-secondary dismiss-notif" data-id="' . $notif->id . '" style="background: rgba(0,0,0,0.1); border: none; color: inherit; cursor: pointer;"><i class="fa-solid fa-check"></i> Dismiss</button>';
                echo '</div>';
            }
        }
    }
    ?>

    <?php if (isset($_GET['status'])): ?>
        <div class="status-message <?php echo $_GET['status'] === 'success' ? 'success' : 'error'; ?>">
            <?php echo $_GET['msg'] ?? 'Action completed.'; ?>
        </div>
    <?php endif; ?>

    <!-- Dashboard Tabs -->
    <div class="dashboard-tabs">
        <button class="tab-btn active" onclick="switchDashboardTab('sponsors')">
            <i class="fa-solid fa-handshake"></i> Sponsorships
        </button>
        <button class="tab-btn" onclick="switchDashboardTab('advertisers')">
            <i class="fa-solid fa-bullhorn"></i> Advertisers
        </button>
    </div>

    <!-- == SPONSORS TAB == -->
    <div id="sponsors-tab" class="dashboard-tab-content active">
        <div class="dashboard-section">
            <h2 class="dashboard-title">My Business Profile</h2>
            <p class="section-desc">Set up your business details. Your logo will be used for all sponsorship campaigns.</p>
            <form action="sponsor_campaign_process.php" method="POST" enctype="multipart/form-data" class="styled-form" style="max-width: 600px;">
                <input type="hidden" name="action" value="setup_business">
                <div class="form-group">
                    <label>Business Name</label>
                    <input type="text" name="business_name" value="<?php echo htmlspecialchars($sponsor_profile->business_name ?? ''); ?>" required>
                </div>
                <div class="form-group">
                    <label>Business Description</label>
                    <textarea name="business_description" rows="3"><?php echo htmlspecialchars($sponsor_profile->business_description ?? ''); ?></textarea>
                </div>
                <div class="form-group">
                    <label>Business Logo</label>
                    <?php if (!empty($sponsor_profile->business_logo)): ?>
                        <div style="margin-bottom: 10px;"><img src="<?php echo htmlspecialchars($sponsor_profile->business_logo); ?>" alt="Current Logo" style="height: 60px; background: #eee; padding: 5px; border-radius: 5px;"></div>
                    <?php endif; ?>
                    <input type="file" name="business_logo" accept="image/*">
                    <input type="hidden" name="current_logo" value="<?php echo htmlspecialchars($sponsor_profile->business_logo ?? ''); ?>">
                </div>
                <button type="submit" class="btn">Save Profile</button>
            </form>
        </div>
        <div class="dashboard-section">
            <h2 class="dashboard-title">Sponsorship Packages</h2>
            <p class="section-desc">Boost your brand visibility by sponsoring leagues, matches, or fixture lists.</p>
        <div class="packages-grid">
                <?php foreach ($sponsorship_packages as $pkg): ?>
                <div class="package-card">
                    <h3><?php echo htmlspecialchars($pkg->name); ?></h3>
                    <div class="price">$<?php echo number_format($pkg->price, 2); ?></div>
                    <p><?php echo htmlspecialchars($pkg->description); ?></p>
                    <form action="sponsor_campaign_process.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="create">
                        <input type="hidden" name="package_id" value="<?php echo $pkg->id; ?>">
                        <input type="hidden" name="price" value="<?php echo $pkg->price; ?>">
                        
                        <div class="form-group">
                            <label>Preview (Header Appearance)</label>
                            <div class="logo-preview-mockup" style="background: linear-gradient(135deg, var(--primary-color, #3498db) 0%, var(--secondary-color, #2c3e50) 100%); padding: 15px; border-radius: 8px; display: flex; align-items: center; gap: 15px; color: white; margin-bottom: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
                                <?php if (!empty($sponsor_profile->business_logo)): ?>
                                    <img src="<?php echo htmlspecialchars($sponsor_profile->business_logo); ?>" alt="Logo" style="height: 50px; width: auto; background: rgba(255,255,255,0.95); padding: 4px; border-radius: 4px; object-fit: contain;">
                                    <div>
                                        <small style="display: block; font-size: 0.7rem; opacity: 0.9; text-transform: uppercase; letter-spacing: 0.5px;">Sponsored By</small>
                                        <span style="font-weight: 700; font-size: 1.1rem;"><?php echo htmlspecialchars($sponsor_profile->business_name); ?></span>
                                    </div>
                                <?php else: ?>
                                    <div style="color: #ffcccc; font-size: 0.85rem;"><i class="fa-solid fa-triangle-exclamation"></i> Upload a logo in your profile to see preview.</div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <?php if ($pkg->type === 'league'): ?>
                            <div class="form-group">
                                <label>Select League</label>
                                <select name="entity_id" required>
                                    <?php foreach ($leagues as $l): ?>
                                        <option value="<?php echo $l->id; ?>"><?php echo htmlspecialchars($l->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        <?php elseif ($pkg->type === 'match' || $pkg->type === 'fixture'): ?>
                            <div class="form-group">
                                <label>Select Match</label>
                                <select name="entity_id" required>
                                    <?php foreach ($upcoming_fixtures as $f): ?>
                                        <option value="<?php echo $f->id; ?>"><?php echo $f->home_team_name . ' vs ' . $f->away_team_name . ' (' . date('d M', strtotime($f->match_datetime)) . ')'; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        <?php elseif ($pkg->type === 'ad'): ?>
                            <div class="form-group">
                                <label>Aggression (1-10)</label>
                                <input type="range" name="aggression" min="1" max="10" value="1" oninput="this.nextElementSibling.value = this.value">
                                <output>1</output>
                            </div>
                        <?php endif; ?>

                        <button type="submit" class="btn btn-block">Purchase Campaign</button>
                    </form>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="dashboard-section">
            <h2 class="dashboard-title">Active Sponsorships</h2>
        <div class="table-wrapper">
            <table class="styled-table">
                <thead><tr><th>Package</th><th>Target</th><th>Status</th><th>Ends</th><th>Views</th><th>Clicks</th><th>CTR</th><th>Actions</th></tr></thead>
                <tbody>
                        <?php if (empty($sponsorships)): ?>
                            <tr><td colspan="8" style="text-align:center;">No active sponsorships.</td></tr>
                        <?php else: ?>
                            <?php foreach ($sponsorships as $camp): ?>
                                <?php include 'includes/campaign_row.php'; // Refactored row logic below ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- == ADVERTISERS TAB == -->
    <div id="advertisers-tab" class="dashboard-tab-content">
        <!-- Analytics Chart Section (Only for Advertisers) -->
        <div class="dashboard-section">
            <h2 class="dashboard-title">Ad Performance (Last 30 Days)</h2>
            <div class="chart-container" style="position: relative; height: 300px; width: 100%;">
                <canvas id="performanceChart"></canvas>
            </div>
        </div>

        <div class="dashboard-section">
            <h2 class="dashboard-title">Ad Packages (PPC / PPV)</h2>
            <p class="section-desc">Run targeted ad campaigns with flexible aggression settings.</p>
            
            <div style="margin-bottom: 20px;">
                <button class="btn" onclick="openCreateAdModal()"><i class="fa-solid fa-plus"></i> Create New Ad Campaign</button>
            </div>

            <div class="packages-grid">
                <?php foreach ($ad_packages as $pkg): ?>
                    <div class="package-card">
                        <h3><?php echo htmlspecialchars($pkg->name); ?></h3>
                        <div class="price">Rate Card</div>
                        <p><?php echo htmlspecialchars($pkg->description); ?></p>
                        <small>Use the "Create New Ad Campaign" button to customize your budget and targeting.</small>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="dashboard-section">
            <h2 class="dashboard-title">Ad Campaigns</h2>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead><tr><th>Campaign</th><th>Model</th><th>Budget</th><th>Status</th><th>Views</th><th>Clicks</th><th>CTR</th><th>Actions</th></tr></thead>
                    <tbody>
                        <?php if (empty($ad_campaigns)): ?>
                            <tr><td colspan="8" style="text-align:center;">No active ad campaigns.</td></tr>
                        <?php else: ?>
                            <?php foreach ($ad_campaigns as $camp): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($camp->name ?: $camp->package_name); ?></td>
                            <td>
                                <?php 
                                if ($camp->package_type == 'league') echo "League ID: " . $camp->entity_id;
                                elseif ($camp->package_type == 'match') echo "Match ID: " . $camp->entity_id;
                                else echo "General";
                                ?>
                                <br><small><?php echo strtoupper($camp->payment_model); ?></small>
                            </td>
                            <td>
                                <?php if ($camp->payment_model === 'flat'): ?>
                                    Flat Rate
                                <?php else: ?>
                                    $<?php echo number_format($camp->remaining_budget, 2); ?> / $<?php echo number_format($camp->total_budget, 2); ?>
                                <?php endif; ?>
                            </td>
                            <td><span class="status-badge status-<?php echo $camp->status; ?>"><?php echo ucfirst($camp->status); ?></span></td>
                            <td><strong><?php echo number_format($camp->views ?? 0); ?></strong></td>
                            <td><?php echo number_format($camp->clicks ?? 0); ?></td>
                            <td>
                                <?php 
                                    $ctr = ($camp->views > 0) ? ($camp->clicks / $camp->views) * 100 : 0;
                                    echo number_format($ctr, 2) . '%';
                                ?>
                            </td>
                            <td>
                                <?php if (in_array($camp->status, ['active', 'pending', 'paused'])): ?>
                                    <button class="btn-sm btn-edit" onclick='openEditModal(<?php echo json_encode($camp); ?>)'>Edit</button>
                                <?php endif; ?>

                                <?php if ($camp->status === 'active'): ?>
                                    <form action="sponsor_campaign_process.php" method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="pause">
                                        <input type="hidden" name="campaign_id" value="<?php echo $camp->id; ?>">
                                        <button type="submit" class="btn-sm" style="background-color: #f39c12; border: none; color: white; cursor: pointer; padding: 5px 10px; border-radius: 4px;">Pause</button>
                                    </form>
                                    <button class="btn-sm" onclick='openExtendModal(<?php echo json_encode($camp); ?>)' style="background-color: #3498db; border: none; color: white; cursor: pointer; padding: 5px 10px; border-radius: 4px; margin-left: 5px;">Extend</button>
                                <?php elseif ($camp->status === 'paused'): ?>
                                    <form action="sponsor_campaign_process.php" method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="resume">
                                        <input type="hidden" name="campaign_id" value="<?php echo $camp->id; ?>">
                                        <button type="submit" class="btn-sm" style="background-color: #2ecc71; border: none; color: white; cursor: pointer; padding: 5px 10px; border-radius: 4px;">Resume</button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Edit Campaign Modal -->
<div id="editCampaignModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Edit Campaign</h3>
            <button class="modal-close-btn" onclick="closeEditModal()">&times;</button>
        </div>
        <form action="sponsor_campaign_process.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="campaign_id" id="edit_campaign_id">
            
            <div class="form-group">
                <label>Current Content URL (Optional)</label>
                <input type="text" name="ad_content" id="edit_ad_content" placeholder="URL or leave blank to upload new">
            </div>
            <div class="form-group">
                <label>Upload New Media (Replaces current)</label>
                <input type="file" name="ad_media" accept="image/*,video/*">
            </div>
            <div class="form-group">
                <label>Type</label>
                <select name="ad_type" id="edit_ad_type"><option value="image">Image</option><option value="video">Video</option></select>
            </div>
            <div class="form-group" id="edit_aggression_group">
                <label>Aggression (1-10)</label>
                <input type="range" name="aggression" id="edit_aggression" min="1" max="10" oninput="this.nextElementSibling.value = this.value">
                <output id="edit_aggression_output">1</output>
            </div>

            <button type="submit" class="btn btn-block">Update Campaign</button>
        </form>
    </div>
</div>

<!-- Extend Campaign Modal -->
<div id="extendCampaignModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Extend Campaign</h3>
            <button class="modal-close-btn" onclick="closeExtendModal()">&times;</button>
        </div>
        <form action="sponsor_campaign_process.php" method="POST">
            <input type="hidden" name="action" value="extend">
            <input type="hidden" name="campaign_id" id="extend_campaign_id">
            
            <p>Extend the duration of <strong><span id="extend_campaign_name"></span></strong>.</p>
            
            <div class="form-group">
                <label>Days to Extend</label>
                <input type="number" name="days" id="extend_days" min="1" value="7" required oninput="calculateExtensionCost()">
            </div>
            
            <div class="cost-summary" style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                <div style="display:flex; justify-content:space-between; margin-bottom:5px;">
                    <span>Daily Rate:</span>
                    <span id="extend_daily_rate">$0.00</span>
                </div>
                <div style="display:flex; justify-content:space-between; font-weight:bold; font-size:1.1rem; color:var(--primary-color);">
                    <span>Total Cost:</span>
                    <span id="extend_total_cost">$0.00</span>
                </div>
            </div>

            <button type="submit" class="btn btn-block">Pay & Extend</button>
        </form>
    </div>
</div>

<!-- Create Ad Campaign Modal -->
<div id="createAdModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Create Ad Campaign</h3>
            <button class="modal-close-btn" onclick="closeCreateAdModal()">&times;</button>
        </div>
        <form action="sponsor_campaign_process.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="create_custom">
            
            <div class="form-group">
                <label>Campaign Name</label>
                <input type="text" name="name" required placeholder="e.g. Summer Sale 2024">
            </div>

            <div class="form-group">
                <label>Ad Media (Image or Video)</label>
                <input type="file" name="ad_media" accept="image/*,video/*" required>
            </div>

            <div class="form-group">
                <label>Payment Model</label>
                <select name="payment_model" required>
                    <option value="ppc">Pay Per Click (PPC)</option>
                    <option value="ppv">Pay Per View (PPV)</option>
                </select>
            </div>

            <div class="form-row" style="display:flex; gap:10px;">
                <div class="form-group" style="flex:1;">
                    <label>Total Budget ($)</label>
                    <input type="number" name="total_budget" step="0.01" min="10" required placeholder="100.00">
                </div>
                <div class="form-group" style="flex:1;">
                    <label>Daily Budget ($)</label>
                    <input type="number" name="daily_budget" step="0.01" min="1" required placeholder="10.00">
                </div>
            </div>

            <div class="form-group">
                <label>Target Link (Optional)</label>
                <input type="url" name="target_url" placeholder="https://yourwebsite.com">
            </div>
            <div class="form-group">
                <label>Contact Number (Optional)</label>
                <input type="tel" name="contact_number" placeholder="+1234567890">
            </div>

            <button type="submit" class="btn btn-block">Launch Campaign</button>
        </form>
    </div>
</div>

<style>
.packages-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
.package-card { background: #fff; padding: 20px; border-radius: 12px; border: 1px solid #eee; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.package-card h3 { margin-top: 0; color: var(--primary-color); }
.package-card .price { font-size: 1.5rem; font-weight: bold; margin-bottom: 10px; }
.form-group { margin-bottom: 10px; }
.form-group label { display: block; font-size: 0.85rem; margin-bottom: 5px; font-weight: 600; }
.form-group input, .form-group select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }

/* Tab Styles */
.dashboard-tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid #eee; padding-bottom: 10px; }
.tab-btn {
    background: none;
    border: none;
    padding: 10px 20px;
    font-size: 1rem;
    font-weight: 600;
    color: #7f8c8d;
    cursor: pointer;
    border-radius: 8px;
    transition: all 0.2s;
}
.tab-btn:hover { background: #f0f2f5; color: #333; }
.tab-btn.active { background: var(--primary-color); color: white; }
.dashboard-tab-content { display: none; animation: fadeIn 0.3s ease; }
.dashboard-tab-content.active { display: block; }
.section-desc { color: #666; margin-bottom: 20px; margin-top: -10px; }

@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
</style>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const analyticsData = <?php echo json_encode($analytics_data); ?>;
    
    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('performanceChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Views',
                        data: views,
                        borderColor: '#3498db',
                        backgroundColor: 'rgba(52, 152, 219, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: '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>';
    }

    // Tab Switching Logic
    window.switchDashboardTab = function(tabName) {
        document.querySelectorAll('.dashboard-tab-content').forEach(el => el.classList.remove('active'));
        document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
        
        document.getElementById(tabName + '-tab').classList.add('active');
        event.currentTarget.classList.add('active');
    }

    // Create Ad Modal
    const createAdModal = document.getElementById('createAdModal');
    window.openCreateAdModal = function() {
        createAdModal.classList.add('show');
    }
    window.closeCreateAdModal = function() {
        createAdModal.classList.remove('show');
    }

    // Edit Modal Logic
    const editModal = document.getElementById('editCampaignModal');
    
    window.openEditModal = function(campaign) {
        document.getElementById('edit_campaign_id').value = campaign.id;
        document.getElementById('edit_ad_content').value = campaign.ad_content;
        document.getElementById('edit_ad_type').value = campaign.ad_type;
        
        const aggGroup = document.getElementById('edit_aggression_group');
        if (campaign.package_type === 'ad') {
            aggGroup.style.display = 'block';
            document.getElementById('edit_aggression').value = campaign.aggression;
            document.getElementById('edit_aggression_output').value = campaign.aggression;
        } else {
            aggGroup.style.display = 'none';
        }
        editModal.classList.add('show');
    }
    window.closeEditModal = function() { editModal.classList.remove('show'); }
    window.onclick = function(e) { if(e.target == editModal) closeEditModal(); }

    // Extend Modal Logic
    const extendModal = document.getElementById('extendCampaignModal');
    let currentDailyRate = 0;

    window.openExtendModal = function(campaign) {
        document.getElementById('extend_campaign_id').value = campaign.id;
        document.getElementById('extend_campaign_name').textContent = campaign.package_name;
        
        const price = parseFloat(campaign.package_price);
        const duration = parseInt(campaign.package_duration) || 30;
        currentDailyRate = price / duration;
        
        document.getElementById('extend_daily_rate').textContent = '$' + currentDailyRate.toFixed(2);
        calculateExtensionCost();
        
        extendModal.classList.add('show');
    }
    window.closeExtendModal = function() { extendModal.classList.remove('show'); }
    window.calculateExtensionCost = function() {
        const days = parseInt(document.getElementById('extend_days').value) || 0;
        const total = days * currentDailyRate;
        document.getElementById('extend_total_cost').textContent = '$' + total.toFixed(2);
    }
    
    // Close modal on outside click (merging with existing handler)
    const originalOnClick = window.onclick;
    window.onclick = function(e) {
        if (originalOnClick) originalOnClick(e);
        if (e.target == extendModal) closeExtendModal();
        if (e.target == createAdModal) closeCreateAdModal();
    }

    // Dismiss Notification
    document.querySelectorAll('.dismiss-notif').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.dataset.id;
            const parent = this.closest('.status-message');
            fetch('api/mark_notification_read.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'id=' + id
            }).then(() => { parent.remove(); });
        });
    });
});
</script>
<?php include 'includes/footer.php'; ?>