<?php
declare(strict_types=1);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/lib/Database.php';
require_once __DIR__ . '/lib/Auth.php';
require_once __DIR__ . '/lib/AdServer.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_name(SESSION_NAME);
    session_start();
}

$db   = Database::getInstance()->getConnection();
$auth = new Auth($db);

function h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function getCsrfToken(): string
{
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function ensurePostCsrf(): void
{
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $token = $_POST['csrf_token'] ?? '';
        if (!$token || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
            http_response_code(400);
            echo 'Invalid CSRF token.';
            exit;
        }
    }
}

function render_header(string $title, ?array $user, bool $showNav = true): void
{
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>AdServer - <?php echo h($title); ?></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
        <style>
            body { padding-top: 56px; }
            .navbar-brand { font-weight: 600; }
            .container-narrow { max-width: 1200px; }
            footer { margin-top: 40px; padding: 20px 0; font-size: 0.9rem; color: #777; }
            table th, table td { vertical-align: middle; }
        </style>
    </head>
    <body class="bg-light">
    <?php if ($showNav): ?>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="?page=dashboard">AdServer</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item"><a class="nav-link" href="?page=dashboard">Dashboard</a></li>
                    <li class="nav-item"><a class="nav-link" href="?page=zones">Zones</a></li>
                    <li class="nav-item"><a class="nav-link" href="?page=advertisers">Advertisers</a></li>
                    <li class="nav-item"><a class="nav-link" href="?page=campaigns">Campaigns</a></li>
                    <li class="nav-item"><a class="nav-link" href="?page=creatives">Creatives</a></li>
                    <li class="nav-item"><a class="nav-link" href="?page=reports">Reports</a></li>
                </ul>
                <span class="navbar-text">
                    <?php if ($user): ?>
                        Signed in as <?php echo h($user['full_name']); ?> | <a href="?page=logout" class="link-light">Logout</a>
                    <?php endif; ?>
                </span>
            </div>
        </div>
    </nav>
    <?php endif; ?>
    <main class="container container-narrow mt-4">
    <?php
}

function render_footer(): void
{
    ?>
    </main>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
    <footer class="container container-narrow">
        <hr>
        <p>&copy; <?php echo date('Y'); ?> PHP AdServer</p>
    </footer>
    </body>
    </html>
    <?php
}

$page = $_GET['page'] ?? 'dashboard';

try {
    $installNeeded = AdServer::isInstallationNeeded($db);
} catch (\RuntimeException $e) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>AdServer - Setup required</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
    </head>
    <body class="bg-light">
    <div class="container mt-5">
        <div class="alert alert-danger">
            <h1 class="h4 mb-3">Database setup required</h1>
            <p><?php echo h($e->getMessage()); ?></p>
            <p>Import the <code>schema.sql</code> file into your MySQL database, then reload this page.</p>
        </div>
    </div>
    </body>
    </html>
    <?php
    exit;
}

if ($page === 'logout') {
    $auth->logout();
    header('Location: ?page=login');
    exit;
}

if ($installNeeded) {
    $page = 'install';
}

if ($page === 'install') {
    $error = '';
    if (!$installNeeded) {
        header('Location: ?page=login');
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        ensurePostCsrf();
        $name      = trim($_POST['full_name'] ?? '');
        $email     = trim($_POST['email'] ?? '');
        $password  = $_POST['password'] ?? '';
        $password2 = $_POST['password_confirm'] ?? '';
        if ($name === '' || $email === '' || $password === '') {
            $error = 'All fields are required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email address.';
        } elseif ($password !== $password2) {
            $error = 'Passwords do not match.';
        } else {
            AdServer::createAdmin($db, $name, $email, $password);
            header('Location: ?page=login');
            exit;
        }
    }
    render_header('Install', null, false);
    ?>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <h1 class="h3 mb-3">Initial admin setup</h1>
            <p class="mb-4">Create the first administrator account for the ad server.</p>
            <?php if ($error !== ''): ?>
                <div class="alert alert-danger"><?php echo h($error); ?></div>
            <?php endif; ?>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?php echo h(getCsrfToken()); ?>">
                <div class="mb-3">
                    <label class="form-label">Full name</label>
                    <input type="text" name="full_name" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Email address</label>
                    <input type="email" name="email" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Confirm password</label>
                    <input type="password" name="password_confirm" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary">Create admin account</button>
            </form>
        </div>
    </div>
    <?php
    render_footer();
    exit;
}

if ($page === 'login') {
    $error = '';
    if ($auth->isLoggedIn()) {
        header('Location: ?page=dashboard');
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        ensurePostCsrf();
        $email    = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        if ($email === '' || $password === '') {
            $error = 'Email and password are required.';
        } elseif ($auth->login($email, $password)) {
            header('Location: ?page=dashboard');
            exit;
        } else {
            $error = 'Invalid email or password.';
        }
    }
    render_header('Login', null, false);
    ?>
    <div class="row justify-content-center">
        <div class="col-md-5">
            <h1 class="h3 mb-3">Sign in</h1>
            <?php if ($error !== ''): ?>
                <div class="alert alert-danger"><?php echo h($error); ?></div>
            <?php endif; ?>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?php echo h(getCsrfToken()); ?>">
                <div class="mb-3">
                    <label class="form-label">Email address</label>
                    <input type="email" name="email" class="form-control" autofocus required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary w-100">Sign in</button>
            </form>
        </div>
    </div>
    <?php
    render_footer();
    exit;
}

$auth->requireLogin();
$user = $auth->user();

switch ($page) {
    case 'dashboard':
        $totals      = AdServer::getTotals($db);
        $impressions = $totals['impressions'];
        $clicks      = $totals['clicks'];
        $revenue     = $totals['revenue'];
        $ctr         = $impressions > 0 ? ($clicks / $impressions) * 100.0 : 0.0;
        $ecpm        = $impressions > 0 ? ($revenue / $impressions) * 1000.0 : 0.0;

        $topStats = AdServer::getSummaryStats($db);

        render_header('Dashboard', $user);
        ?>
        <div class="row">
            <div class="col-md-3 mb-3">
                <div class="card text-bg-light">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-1 text-muted">Impressions</h6>
                        <div class="display-6"><?php echo number_format($impressions); ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card text-bg-light">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-1 text-muted">Clicks</h6>
                        <div class="display-6"><?php echo number_format($clicks); ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card text-bg-light">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-1 text-muted">CTR</h6>
                        <div class="display-6"><?php echo number_format($ctr, 2); ?>%</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card text-bg-light">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-1 text-muted">eCPM</h6>
                        <div class="display-6">$<?php echo number_format($ecpm, 2); ?></div>
                    </div>
                </div>
            </div>
        </div>

        <h2 class="h4 mt-4">Top creatives</h2>
        <div class="table-responsive">
            <table class="table table-sm table-striped align-middle">
                <thead>
                <tr>
                    <th>Advertiser</th>
                    <th>Campaign</th>
                    <th>Creative</th>
                    <th>Zone</th>
                    <th class="text-end">Impressions</th>
                    <th class="text-end">Clicks</th>
                    <th class="text-end">CTR</th>
                    <th class="text-end">Revenue</th>
                    <th class="text-end">eCPM</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$topStats): ?>
                    <tr><td colspan="9" class="text-muted">No data yet.</td></tr>
                <?php else: ?>
                    <?php foreach ($topStats as $row):
                        $imp = (int)$row['impressions'];
                        $clk = (int)$row['clicks'];
                        $rev = (float)$row['revenue'];
                        $rowCtr  = $imp > 0 ? ($clk / $imp) * 100.0 : 0.0;
                        $rowEcpm = $imp > 0 ? ($rev / $imp) * 1000.0 : 0.0;
                    ?>
                        <tr>
                            <td><?php echo h($row['advertiser_name']); ?></td>
                            <td><?php echo h($row['campaign_name']); ?></td>
                            <td><?php echo h($row['creative_name']); ?></td>
                            <td><?php echo h($row['zone_name']); ?></td>
                            <td class="text-end"><?php echo number_format($imp); ?></td>
                            <td class="text-end"><?php echo number_format($clk); ?></td>
                            <td class="text-end"><?php echo number_format($rowCtr, 2); ?>%</td>
                            <td class="text-end">$<?php echo number_format($rev, 2); ?></td>
                            <td class="text-end">$<?php echo number_format($rowEcpm, 2); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
        render_footer();
        break;

    case 'zones':
        $message = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            ensurePostCsrf();
            $id            = isset($_POST['id']) ? (int)$_POST['id'] : 0;
            $name          = trim($_POST['name'] ?? '');
            $slug          = trim($_POST['slug'] ?? '');
            $description   = trim($_POST['description'] ?? '');
            $width         = $_POST['width'] !== '' ? (int)$_POST['width'] : null;
            $height        = $_POST['height'] !== '' ? (int)$_POST['height'] : null;
            $is_responsive = isset($_POST['is_responsive']) ? 1 : 0;
            $status        = $_POST['status'] === 'inactive' ? 'inactive' : 'active';

            if ($name === '' || $slug === '') {
                $message = 'Name and slug are required.';
            } else {
                if ($id > 0) {
                    $stmt = $db->prepare('UPDATE zones SET name = :name, slug = :slug, description = :description, width = :width, height = :height, is_responsive = :is_responsive, status = :status WHERE id = :id');
                    $stmt->execute([
                        'name'          => $name,
                        'slug'          => $slug,
                        'description'   => $description !== '' ? $description : null,
                        'width'         => $width,
                        'height'        => $height,
                        'is_responsive' => $is_responsive,
                        'status'        => $status,
                        'id'            => $id,
                    ]);
                    $message = 'Zone updated.';
                } else {
                    $stmt = $db->prepare('INSERT INTO zones (name, slug, description, width, height, is_responsive, status) VALUES (:name, :slug, :description, :width, :height, :is_responsive, :status)');
                    $stmt->execute([
                        'name'          => $name,
                        'slug'          => $slug,
                        'description'   => $description !== '' ? $description : null,
                        'width'         => $width,
                        'height'        => $height,
                        'is_responsive' => $is_responsive,
                        'status'        => $status,
                    ]);
                    $message = 'Zone created.';
                }
            }
        }

        if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'toggle') {
            $zoneId = (int)$_GET['id'];
            $stmt = $db->prepare('SELECT status FROM zones WHERE id = :id');
            $stmt->execute(['id' => $zoneId]);
            if ($zone = $stmt->fetch()) {
                $newStatus = $zone['status'] === 'active' ? 'inactive' : 'active';
                $upd = $db->prepare('UPDATE zones SET status = :status WHERE id = :id');
                $upd->execute(['status' => $newStatus, 'id' => $zoneId]);
                $message = 'Zone status updated.';
            }
        }

        $editZone = null;
        if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'edit') {
            $zoneId = (int)$_GET['id'];
            $stmt = $db->prepare('SELECT * FROM zones WHERE id = :id');
            $stmt->execute(['id' => $zoneId]);
            $editZone = $stmt->fetch() ?: null;
        }

        $zonesStmt = $db->query('SELECT * FROM zones ORDER BY name ASC');
        $zones = $zonesStmt->fetchAll();

        render_header('Zones', $user);
        ?>
        <div class="row">
            <div class="col-md-5">
                <h2 class="h4 mb-3"><?php echo $editZone ? 'Edit zone' : 'Add zone'; ?></h2>
                <?php if ($message !== ''): ?>
                    <div class="alert alert-info"><?php echo h($message); ?></div>
                <?php endif; ?>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo h(getCsrfToken()); ?>">
                    <input type="hidden" name="id" value="<?php echo $editZone ? (int)$editZone['id'] : 0; ?>">
                    <div class="mb-3">
                        <label class="form-label">Name</label>
                        <input type="text" name="name" class="form-control" required value="<?php echo $editZone ? h($editZone['name']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Slug (used in embed code)</label>
                        <input type="text" name="slug" class="form-control" required value="<?php echo $editZone ? h($editZone['slug']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Width (px, optional)</label>
                        <input type="number" name="width" class="form-control" value="<?php echo $editZone && $editZone['width'] ? (int)$editZone['width'] : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Height (px, optional)</label>
                        <input type="number" name="height" class="form-control" value="<?php echo $editZone && $editZone['height'] ? (int)$editZone['height'] : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description (optional)</label>
                        <textarea name="description" class="form-control" rows="3"><?php echo $editZone ? h((string)$editZone['description']) : ''; ?></textarea>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="is_responsive" id="is_responsive" <?php echo $editZone && (int)$editZone['is_responsive'] === 1 ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_responsive">Responsive zone (ignore width/height)</label>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="active" <?php echo !$editZone || $editZone['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $editZone && $editZone['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary"><?php echo $editZone ? 'Update zone' : 'Create zone'; ?></button>
                </form>
            </div>
            <div class="col-md-7">
                <h2 class="h4 mb-3">Existing zones</h2>
                <div class="table-responsive">
                    <table class="table table-sm table-striped align-middle">
                        <thead>
                        <tr>
                            <th>Name</th>
                            <th>Slug</th>
                            <th>Size</th>
                            <th>Status</th>
                            <th>Embed</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$zones): ?>
                            <tr><td colspan="6" class="text-muted">No zones defined.</td></tr>
                        <?php else: ?>
                            <?php foreach ($zones as $z): ?>
                                <tr>
                                    <td><?php echo h($z['name']); ?></td>
                                    <td><code><?php echo h($z['slug']); ?></code></td>
                                    <td>
                                        <?php
                                        if ((int)$z['is_responsive'] === 1) {
                                            echo 'Responsive';
                                        } elseif ($z['width'] && $z['height']) {
                                            echo (int)$z['width'] . 'x' . (int)$z['height'];
                                        } else {
                                            echo '—';
                                        }
                                        ?>
                                    </td>
                                    <td><?php echo h($z['status']); ?></td>
                                    <td>
                                        <code>&lt;div id="ad-<?php echo h($z['slug']); ?>"&gt;&lt;/div&gt;
&lt;script async src="<?php echo h(AD_API_BASE_URL); ?>/serve.php?zone=<?php echo h($z['slug']); ?>"&gt;&lt;/script&gt;</code>
                                    </td>
                                    <td class="text-end">
                                        <a href="?page=zones&amp;action=edit&amp;id=<?php echo (int)$z['id']; ?>" class="btn btn-sm btn-outline-secondary">Edit</a>
                                        <a href="?page=zones&amp;action=toggle&amp;id=<?php echo (int)$z['id']; ?>" class="btn btn-sm btn-outline-warning">Toggle</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php
        render_footer();
        break;

    case 'advertisers':
        $message = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            ensurePostCsrf();
            $id            = isset($_POST['id']) ? (int)$_POST['id'] : 0;
            $name          = trim($_POST['name'] ?? '');
            $contact_email = trim($_POST['contact_email'] ?? '');
            $contact_phone = trim($_POST['contact_phone'] ?? '');
            $website       = trim($_POST['website'] ?? '');
            if ($name === '' || $contact_email === '') {
                $message = 'Name and contact email are required.';
            } else {
                if ($id > 0) {
                    $stmt = $db->prepare('UPDATE advertisers SET name = :name, contact_email = :contact_email, contact_phone = :contact_phone, website = :website WHERE id = :id');
                    $stmt->execute([
                        'name'          => $name,
                        'contact_email' => $contact_email,
                        'contact_phone' => $contact_phone !== '' ? $contact_phone : null,
                        'website'       => $website !== '' ? $website : null,
                        'id'            => $id,
                    ]);
                    $message = 'Advertiser updated.';
                } else {
                    $stmt = $db->prepare('INSERT INTO advertisers (name, contact_email, contact_phone, website) VALUES (:name, :contact_email, :contact_phone, :website)');
                    $stmt->execute([
                        'name'          => $name,
                        'contact_email' => $contact_email,
                        'contact_phone' => $contact_phone !== '' ? $contact_phone : null,
                        'website'       => $website !== '' ? $website : null,
                    ]);
                    $message = 'Advertiser created.';
                }
            }
        }

        $editAdvertiser = null;
        if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'edit') {
            $advId = (int)$_GET['id'];
            $stmt = $db->prepare('SELECT * FROM advertisers WHERE id = :id');
            $stmt->execute(['id' => $advId]);
            $editAdvertiser = $stmt->fetch() ?: null;
        }

        $advStmt = $db->query('SELECT * FROM advertisers ORDER BY name ASC');
        $advertisers = $advStmt->fetchAll();

        render_header('Advertisers', $user);
        ?>
        <div class="row">
            <div class="col-md-5">
                <h2 class="h4 mb-3"><?php echo $editAdvertiser ? 'Edit advertiser' : 'Add advertiser'; ?></h2>
                <?php if ($message !== ''): ?>
                    <div class="alert alert-info"><?php echo h($message); ?></div>
                <?php endif; ?>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo h(getCsrfToken()); ?>">
                    <input type="hidden" name="id" value="<?php echo $editAdvertiser ? (int)$editAdvertiser['id'] : 0; ?>">
                    <div class="mb-3">
                        <label class="form-label">Name</label>
                        <input type="text" name="name" class="form-control" required value="<?php echo $editAdvertiser ? h($editAdvertiser['name']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Contact email</label>
                        <input type="email" name="contact_email" class="form-control" required value="<?php echo $editAdvertiser ? h($editAdvertiser['contact_email']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Contact phone</label>
                        <input type="text" name="contact_phone" class="form-control" value="<?php echo $editAdvertiser && $editAdvertiser['contact_phone'] ? h($editAdvertiser['contact_phone']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Website</label>
                        <input type="text" name="website" class="form-control" value="<?php echo $editAdvertiser && $editAdvertiser['website'] ? h($editAdvertiser['website']) : ''; ?>">
                    </div>
                    <button type="submit" class="btn btn-primary"><?php echo $editAdvertiser ? 'Update advertiser' : 'Create advertiser'; ?></button>
                </form>
            </div>
            <div class="col-md-7">
                <h2 class="h4 mb-3">Existing advertisers</h2>
                <div class="table-responsive">
                    <table class="table table-sm table-striped align-middle">
                        <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Website</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$advertisers): ?>
                            <tr><td colspan="5" class="text-muted">No advertisers defined.</td></tr>
                        <?php else: ?>
                            <?php foreach ($advertisers as $a): ?>
                                <tr>
                                    <td><?php echo h($a['name']); ?></td>
                                    <td><?php echo h($a['contact_email']); ?></td>
                                    <td><?php echo $a['contact_phone'] ? h($a['contact_phone']) : '—'; ?></td>
                                    <td>
                                        <?php if ($a['website']): ?>
                                            <a href="<?php echo h($a['website']); ?>" target="_blank" rel="noopener"><?php echo h($a['website']); ?></a>
                                        <?php else: ?>
                                            —
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <a href="?page=advertisers&amp;action=edit&amp;id=<?php echo (int)$a['id']; ?>" class="btn btn-sm btn-outline-secondary">Edit</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php
        render_footer();
        break;

    case 'campaigns':
        $message = '';
        $advStmt = $db->query('SELECT id, name FROM advertisers ORDER BY name ASC');
        $advertisers = $advStmt->fetchAll();
        $zonesStmt = $db->query('SELECT id, name FROM zones WHERE status = "active" ORDER BY name ASC');
        $zones = $zonesStmt->fetchAll();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            ensurePostCsrf();
            $id          = isset($_POST['id']) ? (int)$_POST['id'] : 0;
            $name        = trim($_POST['name'] ?? '');
            $advertiser_id = isset($_POST['advertiser_id']) ? (int)$_POST['advertiser_id'] : 0;
            $status      = $_POST['status'] ?? 'active';
            $start_date  = trim($_POST['start_date'] ?? '');
            $end_date    = trim($_POST['end_date'] ?? '');
            $cpm_rate    = $_POST['cpm_rate'] !== '' ? (float)$_POST['cpm_rate'] : 0.0;
            $total_budget = $_POST['total_budget'] !== '' ? (float)$_POST['total_budget'] : null;
            $impressions_purchased = $_POST['impressions_purchased'] !== '' ? (int)$_POST['impressions_purchased'] : null;
            $priority    = $_POST['priority'] !== '' ? (int)$_POST['priority'] : 5;
            $zone_ids    = isset($_POST['zones']) && is_array($_POST['zones']) ? array_map('intval', $_POST['zones']) : [];

            if ($name === '' || $advertiser_id <= 0) {
                $message = 'Name and advertiser are required.';
            } else {
                if ($id > 0) {
                    $stmt = $db->prepare('UPDATE campaigns SET advertiser_id = :advertiser_id, name = :name, status = :status, start_date = :start_date, end_date = :end_date, cpm_rate = :cpm_rate, total_budget = :total_budget, impressions_purchased = :impressions_purchased, priority = :priority WHERE id = :id');
                    $stmt->execute([
                        'advertiser_id'        => $advertiser_id,
                        'name'                 => $name,
                        'status'               => in_array($status, ['active','paused','completed'], true) ? $status : 'active',
                        'start_date'           => $start_date !== '' ? $start_date : null,
                        'end_date'             => $end_date !== '' ? $end_date : null,
                        'cpm_rate'             => $cpm_rate,
                        'total_budget'         => $total_budget,
                        'impressions_purchased'=> $impressions_purchased,
                        'priority'             => $priority,
                        'id'                   => $id,
                    ]);
                    $campaignId = $id;
                    $message = 'Campaign updated.';
                } else {
                    $stmt = $db->prepare('INSERT INTO campaigns (advertiser_id, name, status, start_date, end_date, cpm_rate, total_budget, impressions_purchased, priority) VALUES (:advertiser_id, :name, :status, :start_date, :end_date, :cpm_rate, :total_budget, :impressions_purchased, :priority)');
                    $stmt->execute([
                        'advertiser_id'        => $advertiser_id,
                        'name'                 => $name,
                        'status'               => in_array($status, ['active','paused','completed'], true) ? $status : 'active',
                        'start_date'           => $start_date !== '' ? $start_date : null,
                        'end_date'             => $end_date !== '' ? $end_date : null,
                        'cpm_rate'             => $cpm_rate,
                        'total_budget'         => $total_budget,
                        'impressions_purchased'=> $impressions_purchased,
                        'priority'             => $priority,
                    ]);
                    $campaignId = (int)$db->lastInsertId();
                    $message = 'Campaign created.';
                }

                $db->prepare('DELETE FROM zone_campaigns WHERE campaign_id = :cid')->execute(['cid' => $campaignId]);
                if ($zone_ids) {
                    $zcStmt = $db->prepare('INSERT INTO zone_campaigns (zone_id, campaign_id) VALUES (:zone_id, :campaign_id)');
                    foreach ($zone_ids as $zid) {
                        if ($zid > 0) {
                            $zcStmt->execute(['zone_id' => $zid, 'campaign_id' => $campaignId]);
                        }
                    }
                }
            }
        }

        $editCampaign = null;
        $editZones = [];
        if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'edit') {
            $cid = (int)$_GET['id'];
            $stmt = $db->prepare('SELECT * FROM campaigns WHERE id = :id');
            $stmt->execute(['id' => $cid]);
            $editCampaign = $stmt->fetch() ?: null;
            if ($editCampaign) {
                $zc = $db->prepare('SELECT zone_id FROM zone_campaigns WHERE campaign_id = :cid');
                $zc->execute(['cid' => $cid]);
                $editZones = array_column($zc->fetchAll(), 'zone_id');
            }
        }

        $campaignsStmt = $db->query('SELECT c.*, a.name AS advertiser_name FROM campaigns c JOIN advertisers a ON a.id = c.advertiser_id ORDER BY c.created_at DESC');
        $campaigns = $campaignsStmt->fetchAll();

        render_header('Campaigns', $user);
        ?>
        <div class="row">
            <div class="col-md-6">
                <h2 class="h4 mb-3"><?php echo $editCampaign ? 'Edit campaign' : 'Add campaign'; ?></h2>
                <?php if ($message !== ''): ?>
                    <div class="alert alert-info"><?php echo h($message); ?></div>
                <?php endif; ?>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo h(getCsrfToken()); ?>">
                    <input type="hidden" name="id" value="<?php echo $editCampaign ? (int)$editCampaign['id'] : 0; ?>">
                    <div class="mb-3">
                        <label class="form-label">Name</label>
                        <input type="text" name="name" class="form-control" required value="<?php echo $editCampaign ? h($editCampaign['name']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Advertiser</label>
                        <select name="advertiser_id" class="form-select" required>
                            <option value="">Select advertiser</option>
                            <?php foreach ($advertisers as $a): ?>
                                <option value="<?php echo (int)$a['id']; ?>" <?php echo $editCampaign && (int)$editCampaign['advertiser_id'] === (int)$a['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($a['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="active" <?php echo !$editCampaign || $editCampaign['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="paused" <?php echo $editCampaign && $editCampaign['status'] === 'paused' ? 'selected' : ''; ?>>Paused</option>
                            <option value="completed" <?php echo $editCampaign && $editCampaign['status'] === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Start date</label>
                        <input type="date" name="start_date" class="form-control" value="<?php echo $editCampaign && $editCampaign['start_date'] ? h($editCampaign['start_date']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">End date</label>
                        <input type="date" name="end_date" class="form-control" value="<?php echo $editCampaign && $editCampaign['end_date'] ? h($editCampaign['end_date']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">CPM rate (USD)</label>
                        <input type="number" name="cpm_rate" step="0.0001" class="form-control" value="<?php echo $editCampaign ? h((string)$editCampaign['cpm_rate']) : '0.0000'; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Total budget (USD, optional)</label>
                        <input type="number" name="total_budget" step="0.01" class="form-control" value="<?php echo $editCampaign && $editCampaign['total_budget'] !== null ? h((string)$editCampaign['total_budget']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Impressions purchased (optional)</label>
                        <input type="number" name="impressions_purchased" class="form-control" value="<?php echo $editCampaign && $editCampaign['impressions_purchased'] !== null ? (int)$editCampaign['impressions_purchased'] : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Priority (1-10, higher = more often)</label>
                        <input type="number" name="priority" min="1" max="10" class="form-control" value="<?php echo $editCampaign ? (int)$editCampaign['priority'] : 5; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Zones</label>
                        <div class="border rounded p-2" style="max-height:200px;overflow:auto;">
                            <?php if (!$zones): ?>
                                <div class="text-muted small">No zones defined.</div>
                            <?php else: ?>
                                <?php foreach ($zones as $z): ?>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="zones[]" value="<?php echo (int)$z['id']; ?>" id="zone-<?php echo (int)$z['id']; ?>" <?php echo $editCampaign && in_array($z['id'], $editZones, true) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="zone-<?php echo (int)$z['id']; ?>"><?php echo h($z['name']); ?></label>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary"><?php echo $editCampaign ? 'Update campaign' : 'Create campaign'; ?></button>
                </form>
            </div>
            <div class="col-md-6">
                <h2 class="h4 mb-3">Existing campaigns</h2>
                <div class="table-responsive">
                    <table class="table table-sm table-striped align-middle">
                        <thead>
                        <tr>
                            <th>Name</th>
                            <th>Advertiser</th>
                            <th>Status</th>
                            <th>CPM</th>
                            <th>Priority</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$campaigns): ?>
                            <tr><td colspan="6" class="text-muted">No campaigns defined.</td></tr>
                        <?php else: ?>
                            <?php foreach ($campaigns as $c): ?>
                                <tr>
                                    <td><?php echo h($c['name']); ?></td>
                                    <td><?php echo h($c['advertiser_name']); ?></td>
                                    <td><?php echo h($c['status']); ?></td>
                                    <td>$<?php echo number_format((float)$c['cpm_rate'], 4); ?></td>
                                    <td><?php echo (int)$c['priority']; ?></td>
                                    <td class="text-end">
                                        <a href="?page=campaigns&amp;action=edit&amp;id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-outline-secondary">Edit</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php
        render_footer();
        break;

    case 'creatives':
        $message = '';
        $campStmt = $db->query('SELECT id, name FROM campaigns ORDER BY name ASC');
        $campaigns = $campStmt->fetchAll();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            ensurePostCsrf();
            $id          = isset($_POST['id']) ? (int)$_POST['id'] : 0;
            $campaign_id = isset($_POST['campaign_id']) ? (int)$_POST['campaign_id'] : 0;
            $name        = trim($_POST['name'] ?? '');
            $type        = $_POST['type'] === 'html' ? 'html' : 'image';
            $width       = $_POST['width'] !== '' ? (int)$_POST['width'] : null;
            $height      = $_POST['height'] !== '' ? (int)$_POST['height'] : null;
            $image_url   = trim($_POST['image_url'] ?? '');
            $click_url   = trim($_POST['click_url'] ?? '');
            $html_code   = trim($_POST['html_code'] ?? '');
            $status      = $_POST['status'] === 'inactive' ? 'inactive' : 'active';

            $hasUpload = ($type === 'image'
                && isset($_FILES['image_file'])
                && is_array($_FILES['image_file'])
                && ($_FILES['image_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE);

            if ($campaign_id <= 0 || $name === '') {
                $message = 'Campaign and name are required.';
            } elseif ($type === 'image' && !$hasUpload && ($image_url === '' || $click_url === '')) {
                $message = 'Image URL and click URL are required for image creatives (or upload an image).';
            } elseif ($type === 'html' && $html_code === '') {
                $message = 'HTML code is required for HTML creatives.';
            }

            $uploadedImageUrl = null;

            if ($message === '' && $type === 'image' && $hasUpload) {
                if (!is_dir(UPLOAD_DIR)) {
                    if (!mkdir(UPLOAD_DIR, 0755, true) && !is_dir(UPLOAD_DIR)) {
                        $message = 'Upload directory could not be created.';
                    }
                }

                if ($message === '') {
                    $fileError = $_FILES['image_file']['error'] ?? UPLOAD_ERR_NO_FILE;
                    if ($fileError !== UPLOAD_ERR_OK) {
                        $message = 'Image upload failed (error code ' . (int)$fileError . ').';
                    } else {
                        $tmpName = $_FILES['image_file']['tmp_name'] ?? '';
                        $origName = $_FILES['image_file']['name'] ?? '';
                        if (!is_uploaded_file($tmpName)) {
                            $message = 'Invalid upload.';
                        } else {
                            $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
                            $allowedExt = ['jpg','jpeg','png','gif','webp'];
                            if ($ext === '' || !in_array($ext, $allowedExt, true)) {
                                $message = 'Unsupported image type. Allowed: jpg, jpeg, png, gif, webp.';
                            } else {
                                $size = (int)($_FILES['image_file']['size'] ?? 0);
                                if ($size <= 0 || $size > 5 * 1024 * 1024) {
                                    $message = 'Image file size must be between 1 byte and 5 MB.';
                                } else {
                                    $base = bin2hex(random_bytes(16));
                                    $filename = $base . '.' . $ext;
                                    $dest = rtrim(UPLOAD_DIR, '/\\') . DIRECTORY_SEPARATOR . $filename;
                                    if (!move_uploaded_file($tmpName, $dest)) {
                                        $message = 'Failed to move uploaded file.';
                                    } else {
                                        $uploadedImageUrl = rtrim(UPLOAD_URL, '/') . '/' . $filename;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if ($message === '') {
                if ($uploadedImageUrl !== null) {
                    $image_url = $uploadedImageUrl;
                }

                if ($type === 'image') {
                    $html_code = '';
                } else {
                    $image_url = '';
                    $click_url = '';
                }

                if ($id > 0) {
                    $stmt = $db->prepare('UPDATE creatives SET campaign_id = :campaign_id, name = :name, type = :type, width = :width, height = :height, image_url = :image_url, click_url = :click_url, html_code = :html_code, status = :status WHERE id = :id');
                    $stmt->execute([
                        'campaign_id' => $campaign_id,
                        'name'        => $name,
                        'type'        => $type,
                        'width'       => $width,
                        'height'      => $height,
                        'image_url'   => $image_url !== '' ? $image_url : null,
                        'click_url'   => $click_url !== '' ? $click_url : null,
                        'html_code'   => $html_code !== '' ? $html_code : null,
                        'status'      => $status,
                        'id'          => $id,
                    ]);
                    $message = 'Creative updated.';
                } else {
                    $stmt = $db->prepare('INSERT INTO creatives (campaign_id, name, type, width, height, image_url, click_url, html_code, status) VALUES (:campaign_id, :name, :type, :width, :height, :image_url, :click_url, :html_code, :status)');
                    $stmt->execute([
                        'campaign_id' => $campaign_id,
                        'name'        => $name,
                        'type'        => $type,
                        'width'       => $width,
                        'height'      => $height,
                        'image_url'   => $image_url !== '' ? $image_url : null,
                        'click_url'   => $click_url !== '' ? $click_url : null,
                        'html_code'   => $html_code !== '' ? $html_code : null,
                        'status'      => $status,
                    ]);
                    $message = 'Creative created.';
                }
            }
        }

        $editCreative = null;
        if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'edit') {
            $cid = (int)$_GET['id'];
            $stmt = $db->prepare('SELECT * FROM creatives WHERE id = :id');
            $stmt->execute(['id' => $cid]);
            $editCreative = $stmt->fetch() ?: null;
        }

        $creativesStmt = $db->query('SELECT c.*, camp.name AS campaign_name FROM creatives c JOIN campaigns camp ON camp.id = c.campaign_id ORDER BY c.created_at DESC');
        $creatives = $creativesStmt->fetchAll();

        render_header('Creatives', $user);
        ?>
        <div class="row">
            <div class="col-md-6">
                <h2 class="h4 mb-3"><?php echo $editCreative ? 'Edit creative' : 'Add creative'; ?></h2>
                <?php if ($message !== ''): ?>
                    <div class="alert alert-info"><?php echo h($message); ?></div>
                <?php endif; ?>
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?php echo h(getCsrfToken()); ?>">
                    <input type="hidden" name="id" value="<?php echo $editCreative ? (int)$editCreative['id'] : 0; ?>">
                    <div class="mb-3">
                        <label class="form-label">Campaign</label>
                        <select name="campaign_id" class="form-select" required>
                            <option value="">Select campaign</option>
                            <?php foreach ($campaigns as $c): ?>
                                <option value="<?php echo (int)$c['id']; ?>" <?php echo $editCreative && (int)$editCreative['campaign_id'] === (int)$c['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($c['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Name</label>
                        <input type="text" name="name" class="form-control" required value="<?php echo $editCreative ? h($editCreative['name']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Type</label>
                        <select name="type" class="form-select">
                            <option value="image" <?php echo !$editCreative || $editCreative['type'] === 'image' ? 'selected' : ''; ?>>Image</option>
                            <option value="html" <?php echo $editCreative && $editCreative['type'] === 'html' ? 'selected' : ''; ?>>HTML / third-party tag</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Width (px, optional)</label>
                        <input type="number" name="width" class="form-control" value="<?php echo $editCreative && $editCreative['width'] ? (int)$editCreative['width'] : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Height (px, optional)</label>
                        <input type="number" name="height" class="form-control" value="<?php echo $editCreative && $editCreative['height'] ? (int)$editCreative['height'] : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Image URL (for image creative)</label>
                        <input type="text" name="image_url" class="form-control" value="<?php echo $editCreative && $editCreative['image_url'] ? h($editCreative['image_url']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Upload image (optional, for image creative)</label>
                        <input type="file" name="image_file" class="form-control" accept="image/*">
                        <?php if ($editCreative && $editCreative['type'] === 'image' && $editCreative['image_url']): ?>
                            <div class="form-text">Current image: <?php echo h($editCreative['image_url']); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Click URL (for image creative)</label>
                        <input type="text" name="click_url" class="form-control" value="<?php echo $editCreative && $editCreative['click_url'] ? h($editCreative['click_url']) : ''; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">HTML code (for HTML or AdSense/DoubleClick tag)</label>
                        <textarea name="html_code" class="form-control" rows="6"><?php echo $editCreative && $editCreative['html_code'] ? h($editCreative['html_code']) : ''; ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="active" <?php echo !$editCreative || $editCreative['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $editCreative && $editCreative['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary"><?php echo $editCreative ? 'Update creative' : 'Create creative'; ?></button>
                </form>
            </div>
            <div class="col-md-6">
                <h2 class="h4 mb-3">Existing creatives</h2>
                <div class="table-responsive">
                    <table class="table table-sm table-striped align-middle">
                        <thead>
                        <tr>
                            <th>Name</th>
                            <th>Campaign</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$creatives): ?>
                            <tr><td colspan="5" class="text-muted">No creatives defined.</td></tr>
                        <?php else: ?>
                            <?php foreach ($creatives as $c): ?>
                                <tr>
                                    <td><?php echo h($c['name']); ?></td>
                                    <td><?php echo h($c['campaign_name']); ?></td>
                                    <td><?php echo h($c['type']); ?></td>
                                    <td><?php echo h($c['status']); ?></td>
                                    <td class="text-end">
                                        <a href="?page=creatives&amp;action=edit&amp;id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-outline-secondary">Edit</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php
        render_footer();
        break;

    case 'reports':
        $stats = AdServer::getSummaryStats($db);
        render_header('Reports', $user);
        ?>
        <h1 class="h3 mb-3">Performance reports</h1>
        <p class="text-muted">Aggregated statistics by advertiser, campaign, creative and zone.</p>
        <div class="table-responsive">
            <table class="table table-sm table-striped align-middle">
                <thead>
                <tr>
                    <th>Advertiser</th>
                    <th>Campaign</th>
                    <th>Creative</th>
                    <th>Zone</th>
                    <th class="text-end">Impressions</th>
                    <th class="text-end">Clicks</th>
                    <th class="text-end">CTR</th>
                    <th class="text-end">Revenue</th>
                    <th class="text-end">eCPM</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$stats): ?>
                    <tr><td colspan="9" class="text-muted">No data yet.</td></tr>
                <?php else: ?>
                    <?php foreach ($stats as $row):
                        $imp = (int)$row['impressions'];
                        $clk = (int)$row['clicks'];
                        $rev = (float)$row['revenue'];
                        $rowCtr  = $imp > 0 ? ($clk / $imp) * 100.0 : 0.0;
                        $rowEcpm = $imp > 0 ? ($rev / $imp) * 1000.0 : 0.0;
                    ?>
                        <tr>
                            <td><?php echo h($row['advertiser_name']); ?></td>
                            <td><?php echo h($row['campaign_name']); ?></td>
                            <td><?php echo h($row['creative_name']); ?></td>
                            <td><?php echo h($row['zone_name']); ?></td>
                            <td class="text-end"><?php echo number_format($imp); ?></td>
                            <td class="text-end"><?php echo number_format($clk); ?></td>
                            <td class="text-end"><?php echo number_format($rowCtr, 2); ?>%</td>
                            <td class="text-end">$<?php echo number_format($rev, 2); ?></td>
                            <td class="text-end">$<?php echo number_format($rowEcpm, 2); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
        render_footer();
        break;

    default:
        render_header('Not found', $user);
        ?>
        <div class="alert alert-warning">Unknown page.</div>
        <?php
        render_footer();
        break;
}
