<?php
/**
 * Banner Notification Manager Class
 * Handles banner notifications that move across the user dashboard
 */

class BannerNotificationManager {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
        $this->ensureTableExists();
    }
    
    /**
     * Ensure the banner_notifications table exists
     */
    private function ensureTableExists() {
        $sql = "CREATE TABLE IF NOT EXISTS `banner_notifications` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `message` TEXT NOT NULL,
            `is_enabled` TINYINT(1) NOT NULL DEFAULT 0,
            `speed` INT(11) NOT NULL DEFAULT 50,
            `color` VARCHAR(50) NOT NULL DEFAULT 'blue',
            `background_color` VARCHAR(50) NOT NULL DEFAULT 'blue',
            `text_color` VARCHAR(50) NOT NULL DEFAULT 'white',
            `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        
        mysqli_query($this->conn, $sql);
        
        // Insert default banner if none exists
        $check = mysqli_query($this->conn, "SELECT COUNT(*) as count FROM banner_notifications");
        $result = mysqli_fetch_assoc($check);
        if ($result['count'] == 0) {
            mysqli_query($this->conn, "INSERT INTO banner_notifications (message, is_enabled) VALUES ('Welcome to D-Bundles Stores!', 0)");
        }
    }
    
    /**
     * Get the current active banner notification
     */
    public function getActiveBanner() {
        $stmt = $this->conn->prepare("SELECT * FROM banner_notifications WHERE is_enabled = 1 ORDER BY updated_at DESC LIMIT 1");
        $stmt->execute();
        $result = $stmt->get_result();
        $banner = $result->fetch_assoc();
        $stmt->close();
        
        return $banner ? $banner : null;
    }
    
    /**
     * Get all banner notifications (admin view)
     */
    public function getAllBanners() {
        $stmt = $this->conn->prepare("SELECT * FROM banner_notifications ORDER BY updated_at DESC");
        $stmt->execute();
        $result = $stmt->get_result();
        
        $banners = [];
        while ($row = $result->fetch_assoc()) {
            $banners[] = $row;
        }
        
        $stmt->close();
        return $banners;
    }
    
    /**
     * Get a specific banner by ID
     */
    public function getBannerById($id) {
        $stmt = $this->conn->prepare("SELECT * FROM banner_notifications WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $banner = $result->fetch_assoc();
        $stmt->close();
        
        return $banner;
    }
    
    /**
     * Create or update a banner notification
     */
    public function saveBanner($id = null, $message, $isEnabled, $speed = 50, $color = 'blue', $backgroundColor = 'blue', $textColor = 'white') {
        // Validate inputs
        if (empty($message)) {
            return ['success' => false, 'message' => 'Message is required'];
        }
        
        if ($speed < 10 || $speed > 200) {
            return ['success' => false, 'message' => 'Speed must be between 10 and 200'];
        }
        
        // If updating existing banner
        if ($id) {
            // Disable all other banners if this one is being enabled
            if ($isEnabled) {
                mysqli_query($this->conn, "UPDATE banner_notifications SET is_enabled = 0");
            }
            
            $stmt = $this->conn->prepare("UPDATE banner_notifications SET message = ?, is_enabled = ?, speed = ?, color = ?, background_color = ?, text_color = ? WHERE id = ?");
            $stmt->bind_param("siisssi", $message, $isEnabled, $speed, $color, $backgroundColor, $textColor, $id);
        } else {
            // Disable all other banners if this one is being enabled
            if ($isEnabled) {
                mysqli_query($this->conn, "UPDATE banner_notifications SET is_enabled = 0");
            }
            
            $stmt = $this->conn->prepare("INSERT INTO banner_notifications (message, is_enabled, speed, color, background_color, text_color) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("siisss", $message, $isEnabled, $speed, $color, $backgroundColor, $textColor);
        }
        
        if ($stmt->execute()) {
            $stmt->close();
            return ['success' => true, 'message' => 'Banner saved successfully'];
        } else {
            $error = mysqli_error($this->conn);
            $stmt->close();
            return ['success' => false, 'message' => 'Failed to save banner: ' . $error];
        }
    }
    
    /**
     * Toggle banner enabled status
     */
    public function toggleBanner($id, $enabled) {
        // If enabling, disable all other banners first
        if ($enabled) {
            mysqli_query($this->conn, "UPDATE banner_notifications SET is_enabled = 0");
        }
        
        $stmt = $this->conn->prepare("UPDATE banner_notifications SET is_enabled = ? WHERE id = ?");
        $stmt->bind_param("ii", $enabled, $id);
        
        if ($stmt->execute()) {
            $stmt->close();
            return ['success' => true, 'message' => 'Banner status updated'];
        } else {
            $error = mysqli_error($this->conn);
            $stmt->close();
            return ['success' => false, 'message' => 'Failed to update banner: ' . $error];
        }
    }
    
    /**
     * Delete a banner notification
     */
    public function deleteBanner($id) {
        $stmt = $this->conn->prepare("DELETE FROM banner_notifications WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            $stmt->close();
            return ['success' => true, 'message' => 'Banner deleted successfully'];
        } else {
            $error = mysqli_error($this->conn);
            $stmt->close();
            return ['success' => false, 'message' => 'Failed to delete banner: ' . $error];
        }
    }
}

