<?php
// Filename: admin_public.php
require 'config.php';
requireAdmin();

$msg = ''; $msg_type = '';

// 1. DELETE ITEM
if (isset($_GET['delete_id'])) {
    $stmt = $pdo->prepare("SELECT image_path FROM public_content WHERE id=?");
    $stmt->execute([$_GET['delete_id']]);
    $path = $stmt->fetchColumn();
    if($path && file_exists($path)) unlink($path); 

    $pdo->prepare("DELETE FROM public_content WHERE id=?")->execute([$_GET['delete_id']]);
    $msg = "Item deleted."; $msg_type = "warning";
}

// 2. POST HANDLER
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];

    if ($action === 'add_news') {
        $title = trim($_POST['title']);
        $content = $_POST['content']; 
        if ($title && $content) {
            $stmt = $pdo->prepare("INSERT INTO public_content (type, title, content) VALUES ('news', ?, ?)");
            $stmt->execute([$title, $content]);
            $msg = "News published successfully."; $msg_type = "success";
        }
    } 
    elseif ($action === 'add_carousel') {
        if (isset($_FILES['slide_image']) && $_FILES['slide_image']['error'] == 0) {
            $target_dir = "uploads/public/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            
            $ext = strtolower(pathinfo($_FILES["slide_image"]["name"], PATHINFO_EXTENSION));
            $valid = ['jpg', 'jpeg', 'png', 'webp'];
            
            if (in_array($ext, $valid)) {
                $fname = "slide_" . time() . "." . $ext;
                if (move_uploaded_file($_FILES["slide_image"]["tmp_name"], $target_dir . $fname)) {
                    $stmt = $pdo->prepare("INSERT INTO public_content (type, image_path) VALUES ('carousel', ?)");
                    $stmt->execute([$target_dir . $fname]);
                    $msg = "Slide uploaded."; $msg_type = "success";
                }
            } else {
                $msg = "Invalid format. Only JPG, PNG, WEBP."; $msg_type = "danger";
            }
        }
    }
}

// FETCH DATA
$news = $pdo->query("SELECT * FROM public_content WHERE type='news' ORDER BY created_at DESC")->fetchAll();
$slides = $pdo->query("SELECT * FROM public_content WHERE type='carousel' ORDER BY created_at DESC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Public Portal Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; padding-bottom: 80px; }
        
        /* HEADER */
        .header-card {
            background: linear-gradient(135deg, #0d6efd 0%, #004494 100%);
            color: white; border-radius: 0 0 25px 25px;
            padding: 30px 20px 50px 20px; margin-bottom: -30px;
            box-shadow: 0 4px 20px rgba(13, 110, 253, 0.2);
        }
        
        /* CARDS */
        .content-card {
            background: white; border: 0; border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden;
            margin-bottom: 20px;
        }
        .card-header { background: white; border-bottom: 1px solid #f0f0f0; font-weight: 700; padding: 15px; }
        
        /* NEWS LIST */
        .news-item {
            background: white; border-radius: 12px; padding: 15px; margin-bottom: 10px;
            border: 1px solid #eee; transition: 0.2s;
        }
        .news-item:hover { border-color: #0d6efd; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
        
        /* SLIDE LIST */
        .slide-preview {
            width: 100%; height: 140px; object-fit: cover; border-radius: 10px;
        }
        .slide-card { position: relative; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: 0.2s; }
        .slide-card:hover { transform: scale(1.02); }
        .slide-actions {
            position: absolute; bottom: 0; left: 0; width: 100%;
            background: rgba(0,0,0,0.6); padding: 8px; text-align: right;
        }
        
        /* DESKTOP LAYOUT */
        @media (min-width: 992px) {
            .container { max-width: 1200px; }
            .sticky-col { position: sticky; top: 20px; }
        }
    </style>
</head>
<body>

    <div class="header-card">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div><small class="text-white-50 fw-bold text-uppercase">Admin Panel</small></div>
            <div>
                <a href="public.php" target="_blank" class="btn btn-sm btn-outline-light rounded-pill px-3 me-2"><i class="bi bi-eye"></i> View Site</a>
                <a href="admin_dashboard.php" class="btn btn-sm btn-light text-primary fw-bold rounded-pill px-3">Back</a>
            </div>
        </div>
        <h3 class="fw-bold mb-0">Public Portal Manager</h3>
        <div class="opacity-75 small">Manage Announcements & Carousel</div>
    </div>

    <div class="container px-3">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> alert-dismissible fade show shadow-sm border-0 mb-4"><?= $msg ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="row g-4">
            
            <div class="col-lg-8">
                <div class="content-card">
                    <div class="card-header text-primary"><i class="bi bi-newspaper me-2"></i> Post Announcement</div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="action" value="add_news">
                            <div class="mb-3">
                                <label class="form-label small fw-bold text-muted">Title</label>
                                <input type="text" name="title" class="form-control" placeholder="e.g. Annual Sports Day" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold text-muted">Content</label>
                                <textarea name="content" id="editor" placeholder="Write your announcement here..."></textarea>
                            </div>
                            <button class="btn btn-primary w-100 fw-bold rounded-pill py-2">Publish News</button>
                        </form>
                    </div>
                </div>

                <h6 class="fw-bold text-secondary mb-3 px-2 mt-2">Recent News</h6>
                <div class="row">
                    <?php if(empty($news)): ?>
                        <div class="col-12"><div class="text-center py-5 text-muted border rounded-3 bg-white">No news published yet.</div></div>
                    <?php else: ?>
                        <?php foreach($news as $n): ?>
                            <div class="col-12">
                                <div class="news-item">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <div>
                                            <h5 class="fw-bold text-dark mb-1"><?= htmlspecialchars($n['title']) ?></h5>
                                            <small class="text-muted"><i class="bi bi-clock me-1"></i> <?= date('d M Y, h:i A', strtotime($n['created_at'])) ?></small>
                                        </div>
                                        <a href="?delete_id=<?= $n['id'] ?>" class="btn btn-sm btn-outline-danger rounded-pill px-3" onclick="return confirm('Delete this news?')" title="Delete"><i class="bi bi-trash"></i></a>
                                    </div>
                                    <div class="text-secondary text-truncate" style="max-height: 60px; overflow:hidden;">
                                        <?= strip_tags($n['content']) ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="sticky-col">
                    <div class="content-card">
                        <div class="card-header text-success"><i class="bi bi-images me-2"></i> Carousel Slides</div>
                        <div class="card-body">
                            <form method="POST" enctype="multipart/form-data">
                                <input type="hidden" name="action" value="add_carousel">
                                <label class="form-label small fw-bold text-muted">Upload Image</label>
                                <input type="file" name="slide_image" class="form-control mb-3" required accept="image/*">
                                <button class="btn btn-success w-100 fw-bold rounded-pill py-2">Upload Slide</button>
                            </form>
                        </div>
                    </div>

                    <h6 class="fw-bold text-secondary mb-3 px-2">Active Slides (<?= count($slides) ?>)</h6>
                    <div class="row g-3">
                        <?php if(empty($slides)): ?>
                            <div class="col-12 text-center text-muted small py-4">No slides uploaded.</div>
                        <?php else: ?>
                            <?php foreach($slides as $s): ?>
                                <div class="col-6 col-md-4 col-lg-6">
                                    <div class="slide-card">
                                        <img src="<?= $s['image_path'] ?>" class="slide-preview">
                                        <div class="slide-actions">
                                            <a href="?delete_id=<?= $s['id'] ?>" class="text-white small text-decoration-none fw-bold" onclick="return confirm('Delete slide?')"><i class="bi bi-trash-fill"></i> Remove</a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <script>
        ClassicEditor
            .create(document.querySelector('#editor'), {
                toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo' ]
            })
            .catch(error => { console.error(error); });
    </script>
</body>
</html>