<?php
/**
 * IBVTE Admin - Marquee/News CMS Management
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Check database connection before proceeding
if (!checkDBConnection()) {
    exit;
}

Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$flash = getFlashMessage();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add' || $action === 'edit') {
        $data = [
            'title' => cleanInput($_POST['title'] ?? ''),
            'content' => $_POST['content'] ?? '',
            'link' => cleanInput($_POST['link'] ?? ''),
            'link_text' => cleanInput($_POST['link_text'] ?? ''),
            'priority' => intval($_POST['priority'] ?? 0),
            'bg_color' => cleanInput($_POST['bg_color'] ?? '#3b0b7c'),
            'text_color' => cleanInput($_POST['text_color'] ?? '#ffffff'),
            'icon' => cleanInput($_POST['icon'] ?? ''),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'display_from' => $_POST['display_from'] ?: null,
            'display_until' => $_POST['display_until'] ?: null,
            'created_by' => $_SESSION['user_id']
        ];
        
        if ($action === 'add') {
            $db->insert('marquee', $data);
            redirectWithMessage('marquee.php', 'News item added successfully', 'success');
        } else {
            $id = intval($_POST['id'] ?? 0);
            $db->update('marquee', $data, ['id' => $id]);
            redirectWithMessage('marquee.php', 'News item updated successfully', 'success');
        }
    }
    
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        $db->delete('marquee', ['id' => $id]);
        redirectWithMessage('marquee.php', 'News item deleted', 'success');
    }
    
    if ($action === 'toggle') {
        $id = intval($_POST['id'] ?? 0);
        $current = $db->fetchOne("SELECT is_active FROM marquee WHERE id = ?", [$id]);
        $db->update('marquee', ['is_active' => $current['is_active'] ? 0 : 1], ['id' => $id]);
        redirectWithMessage('marquee.php', 'Status updated', 'success');
    }
}

// Get all marquee items
$items = $db->fetchAll("SELECT * FROM marquee ORDER BY priority DESC, created_at DESC");

// Get single item for edit
$editItem = null;
if (isset($_GET['edit'])) {
    $editItem = $db->fetchOne("SELECT * FROM marquee WHERE id = ?", [intval($_GET['edit'])]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Marquee/News CMS - <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs5.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
    <style>
        .marquee-preview {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .priority-badge {
            position: absolute;
            top: -10px;
            right: 10px;
        }
        .news-card {
            transition: all 0.3s ease;
        }
        .news-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .color-picker-wrapper {
            position: relative;
        }
        .color-picker-wrapper input[type="color"] {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }
        .color-preview {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            border: 2px solid #ddd;
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/admin_header.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                    <h1 class="h2"><i class="fas fa-scroll me-2 text-primary"></i>Marquee / News CMS</h1>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newsModal">
                        <i class="fas fa-plus me-2"></i>Add News Item
                    </button>
                </div>
                
                <?php if ($flash): ?>
                    <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show">
                        <?= $flash['message'] ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <!-- Live Preview -->
                <div class="card mb-4 border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <h5 class="mb-0"><i class="fas fa-eye me-2"></i>Live Preview (Top 2 Active Items)</h5>
                    </div>
                    <div class="card-body">
                        <?php
                        $activeItems = array_filter($items, function($item) {
                            return $item['is_active'] && 
                                   (empty($item['display_from']) || strtotime($item['display_from']) <= time()) &&
                                   (empty($item['display_until']) || strtotime($item['display_until']) >= time());
                        });
                        $topItems = array_slice($activeItems, 0, 2);
                        ?>
                        
                        <?php if (empty($topItems)): ?>
                            <div class="alert alert-info">No active news items to display</div>
                        <?php else: ?>
                            <div class="marquee-container" style="background: linear-gradient(90deg, #3b0b7c, #6c4ab6); padding: 15px; border-radius: 8px;">
                                <marquee behavior="scroll" direction="left" scrollamount="5" onmouseover="this.stop()" onmouseout="this.start()">
                                    <?php foreach ($topItems as $item): ?>
                                        <span style="color: white; margin-right: 50px;">
                                            <?php if ($item['icon']): ?>
                                                <i class="fas <?= htmlspecialchars($item['icon']) ?> me-2"></i>
                                            <?php endif; ?>
                                            <strong><?= htmlspecialchars($item['title']) ?>:</strong>
                                            <?= strip_tags($item['content']) ?>
                                            <?php if ($item['link']): ?>
                                                <a href="<?= htmlspecialchars($item['link']) ?>" style="color: #ffd700; text-decoration: underline; margin-left: 10px;">
                                                    <?= htmlspecialchars($item['link_text'] ?: 'Read More') ?> <i class="fas fa-arrow-right"></i>
                                                </a>
                                            <?php endif; ?>
                                        </span>
                                        <span style="color: rgba(255,255,255,0.5); margin-right: 50px;">|</span>
                                    <?php endforeach; ?>
                                </marquee>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- All News Items -->
                <div class="row">
                    <?php foreach ($items as $item): ?>
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card news-card h-100 <?= $item['is_active'] ? '' : 'opacity-50' ?>">
                                <div class="card-header d-flex justify-content-between align-items-center" 
                                     style="background: <?= htmlspecialchars($item['bg_color']) ?>; color: <?= htmlspecialchars($item['text_color']) ?>;">
                                    <span><i class="fas <?= htmlspecialchars($item['icon'] ?: 'fa-bullhorn') ?> me-2"></i><?= htmlspecialchars($item['title']) ?></span>
                                    <span class="badge bg-light text-dark">Priority: <?= $item['priority'] ?></span>
                                </div>
                                <div class="card-body">
                                    <p class="card-text"><?= substr(strip_tags($item['content']), 0, 150) ?>...</p>
                                    
                                    <?php if ($item['link']): ?>
                                        <a href="<?= htmlspecialchars($item['link']) ?>" class="btn btn-sm btn-outline-primary">
                                            <?= htmlspecialchars($item['link_text'] ?: 'View Link') ?>
                                        </a>
                                    <?php endif; ?>
                                    
                                    <div class="mt-3 small text-muted">
                                        <div><i class="fas fa-calendar me-1"></i>From: <?= $item['display_from'] ?: 'Always' ?></div>
                                        <div><i class="fas fa-calendar-check me-1"></i>Until: <?= $item['display_until'] ?: 'No End' ?></div>
                                    </div>
                                </div>
                                <div class="card-footer bg-white border-top-0">
                                    <div class="btn-group w-100">
                                        <a href="?edit=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="toggle">
                                            <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-<?= $item['is_active'] ? 'warning' : 'success' ?>">
                                                <i class="fas fa-<?= $item['is_active'] ? 'pause' : 'play' ?>"></i>
                                                <?= $item['is_active'] ? 'Disable' : 'Enable' ?>
                                            </button>
                                        </form>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this item?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Add/Edit Modal -->
    <div class="modal fade" id="newsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header" style="background: linear-gradient(135deg, #3b0b7c, #6c4ab6); color: white;">
                    <h5 class="modal-title"><i class="fas fa-plus me-2"></i><?= $editItem ? 'Edit' : 'Add' ?> News Item</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="<?= $editItem ? 'edit' : 'add' ?>">
                        <?php if ($editItem): ?>
                            <input type="hidden" name="id" value="<?= $editItem['id'] ?>">
                        <?php endif; ?>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Title</label>
                                    <input type="text" name="title" class="form-control" required 
                                           value="<?= $editItem ? htmlspecialchars($editItem['title']) : '' ?>">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Priority</label>
                                    <input type="number" name="priority" class="form-control" min="0" max="100"
                                           value="<?= $editItem ? $editItem['priority'] : '0' ?>">
                                    <small class="text-muted">Higher = Shows first</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Content</label>
                            <textarea name="content" id="summernote" class="form-control"><?= $editItem ? htmlspecialchars($editItem['content']) : '' ?></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Link URL (Optional)</label>
                                    <input type="url" name="link" class="form-control" 
                                           value="<?= $editItem ? htmlspecialchars($editItem['link']) : '' ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Link Text</label>
                                    <input type="text" name="link_text" class="form-control" 
                                           value="<?= $editItem ? htmlspecialchars($editItem['link_text']) : 'Read More' ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Icon Class</label>
                                    <select name="icon" class="form-select">
                                        <option value="">None</option>
                                        <option value="fa-bullhorn" <?= ($editItem && $editItem['icon'] == 'fa-bullhorn') ? 'selected' : '' ?>>Announcement</option>
                                        <option value="fa-calendar" <?= ($editItem && $editItem['icon'] == 'fa-calendar') ? 'selected' : '' ?>>Event</option>
                                        <option value="fa-trophy" <?= ($editItem && $editItem['icon'] == 'fa-trophy') ? 'selected' : '' ?>>Result</option>
                                        <option value="fa-exclamation-triangle" <?= ($editItem && $editItem['icon'] == 'fa-exclamation-triangle') ? 'selected' : '' ?>>Important</option>
                                        <option value="fa-gift" <?= ($editItem && $editItem['icon'] == 'fa-gift') ? 'selected' : '' ?>>Offer</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Background Color</label>
                                    <div class="color-picker-wrapper">
                                        <div class="input-group">
                                            <span class="color-preview" id="bgColorPreview" 
                                                  style="background: <?= $editItem ? htmlspecialchars($editItem['bg_color']) : '#3b0b7c' ?>"></span>
                                            <input type="text" name="bg_color" id="bgColor" class="form-control" 
                                                   value="<?= $editItem ? htmlspecialchars($editItem['bg_color']) : '#3b0b7c' ?>">
                                            <input type="color" id="bgColorPicker" 
                                                   value="<?= $editItem ? htmlspecialchars($editItem['bg_color']) : '#3b0b7c' ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Text Color</label>
                                    <div class="color-picker-wrapper">
                                        <div class="input-group">
                                            <span class="color-preview" id="textColorPreview" 
                                                  style="background: <?= $editItem ? htmlspecialchars($editItem['text_color']) : '#ffffff' ?>"></span>
                                            <input type="text" name="text_color" id="textColor" class="form-control" 
                                                   value="<?= $editItem ? htmlspecialchars($editItem['text_color']) : '#ffffff' ?>">
                                            <input type="color" id="textColorPicker" 
                                                   value="<?= $editItem ? htmlspecialchars($editItem['text_color']) : '#ffffff' ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Display From</label>
                                    <input type="date" name="display_from" class="form-control" 
                                           value="<?= $editItem ? $editItem['display_from'] : '' ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Display Until</label>
                                    <input type="date" name="display_until" class="form-control" 
                                           value="<?= $editItem ? $editItem['display_until'] : '' ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" id="isActive" 
                                   <?= ($editItem && $editItem['is_active']) || !$editItem ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="isActive">Active</label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i><?= $editItem ? 'Update' : 'Save' ?> Item
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs5.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#summernote').summernote({
                height: 200,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link', 'picture', 'video']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });
            
            // Color picker sync
            document.getElementById('bgColorPicker').addEventListener('input', function() {
                document.getElementById('bgColor').value = this.value;
                document.getElementById('bgColorPreview').style.background = this.value;
            });
            
            document.getElementById('textColorPicker').addEventListener('input', function() {
                document.getElementById('textColor').value = this.value;
                document.getElementById('textColorPreview').style.background = this.value;
            });
        });
        
        <?php if ($editItem): ?>
        // Auto-open modal for edit
        var newsModal = new bootstrap.Modal(document.getElementById('newsModal'));
        newsModal.show();
        <?php endif; ?>
    </script>
</body>
</html>
