<?php
require_once __DIR__ . '/../includes/config.php';
requireLogin();

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$uid    = $_SESSION['user_id'];

// ── Self-healing schema (safe even if admin/banners.php was never opened) ──
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `banners` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `title` VARCHAR(150) NOT NULL,
        `message` VARCHAR(500) NOT NULL,
        `icon` VARCHAR(10) DEFAULT '📢',
        `style` VARCHAR(20) DEFAULT 'info',
        `bg_color` VARCHAR(20) DEFAULT NULL,
        `text_color` VARCHAR(20) DEFAULT NULL,
        `link_url` VARCHAR(500) DEFAULT NULL,
        `link_text` VARCHAR(50) DEFAULT NULL,
        `target_type` ENUM('all','user') DEFAULT 'all',
        `target_user_id` INT DEFAULT NULL,
        `is_dismissible` TINYINT(1) DEFAULT 1,
        `is_active` TINYINT(1) DEFAULT 1,
        `starts_at` DATETIME DEFAULT NULL,
        `ends_at` DATETIME DEFAULT NULL,
        `clicks` INT DEFAULT 0,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        KEY `idx_target_user` (`target_user_id`)
    ) ENGINE=InnoDB");
} catch (Exception $e) {}
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `banner_dismissals` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `banner_id` INT NOT NULL,
        `user_id` INT NOT NULL,
        `dismissed_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY `banner_user` (`banner_id`,`user_id`)
    ) ENGINE=InnoDB");
} catch (Exception $e) {}

// ── Click: increments the counter then redirects to the banner's own link ──
// (the target URL always comes from the DB, never from user input, so this
//  can never be abused as an open redirect)
if ($action === 'click' && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = (int)($_GET['id'] ?? 0);
    $url = null;
    if ($id > 0) {
        try {
            $stmt = $pdo->prepare("SELECT link_url FROM banners WHERE id = ? AND is_active = 1");
            $stmt->execute([$id]);
            $url = $stmt->fetchColumn();
            if ($url) {
                $pdo->prepare("UPDATE banners SET clicks = clicks + 1 WHERE id = ?")->execute([$id]);
            }
        } catch (Exception $e) {}
    }
    header('Location: ' . ($url ?: (SITE_URL . '/dashboard.php')));
    exit;
}

// ── Dismiss: remembers per-user so the banner never shows again for them ──
if ($action === 'dismiss' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid banner id']);
        exit;
    }
    try {
        $pdo->prepare("INSERT IGNORE INTO banner_dismissals (banner_id, user_id) VALUES (?, ?)")
            ->execute([$id, $uid]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Could not dismiss banner']);
    }
    exit;
}

header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Invalid action']);
