<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
include 'functions.php';

// Check if user is logged in and is an admin
if (!isset($_SESSION['username']) || $_SESSION['user_type'] !== 'admin') {
    header("Location: index.php");
    exit();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PMED - Admin Bulletin</title>
    <link rel="icon" href="favicon_io/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="css/admin_dashboard.css">
    <link rel="stylesheet" href="css/preview.css">
    <link rel="stylesheet" href="css/user_modal.css">
        <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            min-height: 100vh;
            position: relative;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: 
                linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)),
                url('icons/provincial.webp');
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            z-index: -1;
        }

        .layout {
            width: 100%;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* Main Header Banner */
        .header {
            background-color: #d32f2f;
            position: relative;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }

        .header-bg-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            opacity: 0.3;
            z-index: 1;
        }

        .header-content {
            position: relative;
            z-index: 2;
            display: grid;
            /* left fixed, center flexible, right fixed */
            grid-template-columns: 1fr auto 1fr;
            align-items: center;
            padding: 20px;
            gap: 15px;
        }

        .header-logo-left-container {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }

        .header-logo-right-container {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            gap: 15px;
        }

        .header-right {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .header-logo-left,
        .header-logo-right {
            height: 80px;
            width: auto;
            object-fit: contain;
            flex-shrink: 0;
        }

        .header-text {
            text-align: center;
            color: white;
            justify-self: center; /* keep centered */
        }

        .republic-text {
            display: block;
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 5px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        .provincial-text {
            font-size: 1.8rem;
            font-weight: bold;
            margin: 0;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            letter-spacing: 1px;
        }

        /* Office Title Band */
        .office-title {
            background-color: white;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-bottom: 2px solid #d32f2f;
        }
        .office-title h2 {
            color: #B10000;
            font-size: 1.4rem;
            font-weight: 600;
            margin: 0;
        }

        /* Main two-column content */
        .main-content {
            display: grid;
            /* fixed left column for calendar, right column for announcements */
            grid-template-columns: 1fr 2fr 1fr;
            gap: 20px;
            max-width: none;
            /* align to the left edge of the page (with a small page padding) */
            margin: 20px 0;
            padding: 0 20px 20px;
            justify-content: start;
            align-items: start;
        }

        /* Left column (calendar + details) */
        .left {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .right {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .calendar-wrapper {
            background: #d6d6d6ff;
            border-radius: 6px;
            padding: 6px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        /* center column (announcements) */
        .center { display:flex; flex-direction: column; width: 2fr;}
        .announcements-header { margin-bottom: 8px; }
        .announcements-list { background: #fff; padding: 12px; border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.06); max-height: calc(100vh - 235px); overflow-y: auto; margin: 0 0;}

    .announcement-card { border: 1px solid #eee; padding: 12px; border-radius: 6px; margin-bottom: 12px; display:flex; gap:12px; align-items:flex-start; position: relative; }
        .announcement-card img.attachment-img { width:140px; height:auto; object-fit:cover; border-radius:4px; cursor:pointer; transition: transform 0.18s ease, box-shadow 0.18s ease; }
        .announcement-card img.attachment-img:hover { transform: scale(1.001); box-shadow: 0 8px 20px rgba(0,0,0,0.25); }
        .announcement-body { flex:1; }
        .announcement-meta { font-size:12px; color:#666; margin-top:8px; display:flex; justify-content:flex-end; gap:12px; align-items:center; }
        .attachment-pdf { display:inline-block; padding:6px 8px; background:#b10000; border-radius:4px; font-size:13px; color:#fff; text-decoration:none; }

            /* controls (edit/delete) */
            .announcement-controls { position: absolute; top: 8px; right: 8px; display:flex; gap:8px; z-index: 5; }
            .announcement-controls img.control-icon { width:22px; height:22px; cursor:pointer; opacity:0.9; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.25)); }
            .announcement-controls img.control-icon:hover { opacity:1; transform: scale(1.05); }

            /* Image modal styles */
        .image-modal { display: none; position: fixed; z-index: 9999; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.8); align-items: center; justify-content: center; }
        .image-modal.open { display: flex; }
        .image-modal .modal-content { min-width: auto; min-height: auto; box-shadow: 0 8px 30px rgba(0,0,0,0.6); border-radius: 6px; }
        .image-modal .modal-content img { width: auto; max-height: 720px; display: block; border-radius: 6px; }
        .image-modal .close-btn { position: absolute; top: 18px; right: 22px; color: #fff; font-size: 28px; font-weight: bold; background: transparent; border: none; cursor: pointer; }
        .image-modal .close-btn:focus { outline: none; }

        @media (max-width: 900px) {
            .main-content { grid-template-columns: 1fr; padding: 0 12px 30px; }
            .announcements-list { max-height: none; }
        }

        .navbar-right {
            display: flex;
            align-items: center;
            justify-content: flex-end;
        }

        .navbar-right a {
            color: #FAF9F6;
            text-decoration: none;
            display: flex;
            flex-direction: column;
            align-items: center;
            font-size: 12px;
        }

        .navbar-right a img {
            margin-bottom: 5px;
        }

        .navbar-right a:hover {
            text-decoration: underline;
        }

        .right-container {
            width: auto;
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 6px;
            padding: 15px;
            text-align: center;
        }

        .right-container h2 {
            color:rgb(148, 0, 0);
            margin-bottom: 1.5rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #333;
            font-weight: bold;
        }

        .form-group input[type="text"],
        .form-group input[type="password"] {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            box-sizing: border-box;
        }

        .form-group input[type="text"]:focus,
        .form-group input[type="password"]:focus {
            outline: none;
            border-color:rgb(148, 0, 0);
            box-shadow: 0 0 5px rgba(0, 53, 148, 0.3);
        }

        .radio-group {
            display: flex;
            gap: 1rem;
            justify-content: center;
            margin-bottom: 1.5rem;
        }

        .radio-option {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .radio-option input[type="radio"] {
            margin: 0;
        }

        .radio-option label {
            margin: 0;
            color: #333;
            font-weight: normal;
        }

        .login-button {
            background-color:rgb(148, 0, 0);
            color: white;
            border: none;
            padding: 0.75rem 2rem;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: bold;
            width: 100%;
            transition: background-color 0.3s;
        }

        .login-button:hover {
            background-color:rgb(102, 0, 0);
        }

        .error-message {
            background-color: #ffebee;
            color: #c62828;
            padding: 0.75rem;
            border-radius: 5px;
            margin-bottom: 1rem;
            border: 1px solid #ffcdd2;
        }

        @media (max-width: 768px) {

            .right-container {
                padding: 1.5rem;
                width: 95%;
            }

            .right-container h1 {
                font-size: 1.5rem;
            }

            .ppdco-logo {
                height: 60px;
                width: 60px;
            }

            .ppdco h2 {
                font-size: 1.2rem;
            }
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython_stdlib.js"></script>
    <script src="preview.js"></script>
</head>
<body>
    <div class="navbar">
        <div class="navbar-center">
            <img src="icons/ppdco_logo_icon.webp" alt="PPDCO Logo" class="navbar-logo">
            <img src="icons/seal_laguna.webp" alt="Laguna Seal" class="navbar-logo">
            <img src="icons/High-Resolution_Logo_PH.webp" alt="Laguna Seal" class="navbar-logo" loading="lazy" decoding="async">
            <div class="navbar-text">
                <a>Republic of the Philippines - PROVINCIAL GOVERNMENT OF LAGUNA</a>
                <p>PROVINCIAL PLANNING AND DEVELOPMENT COORDINATOR'S OFFICE</p>
            </div>
        </div>
        <div class="navbar-right">
            <nav>
                <ul>
                    <li>
                        <a href="admin_dashboard.php" class="nav-link" data-section="divisions">
                            <img src="icons/navigator/divisions.svg" alt="Divisions" class="nav-icon">
                            <span class="nav-text">DOCUMENTS</span>
                        </a>
                    </li>
                    <li>
                        <a href="admin_bulletin.php" class="nav-link" data-section="manageDivisions">
                            <img src="icons/navigator/manage-divisions.svg" alt="Manage" class="nav-icon">
                            <span class="nav-text">BULLETIN</span>
                        </a>
                    </li>
                    <li>
                        <a href="#" class="nav-link" data-section="composeMessage" onclick="openComposeModal(); return false;" style="cursor:pointer;">
                            <img src="icons/action/compose.svg" alt="Manage" class="nav-icon">
                            <span class="nav-text">COMPOSE</span>
                        </a>
                    </li>
                    <li>
                        <a href="logout.php" class="nav-link">
                            <img src="icons/navigator/logout.svg" alt="Logout" class="nav-icon">
                            <span class="nav-text">LOG OUT</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
    
    <div class="dashboard-container">
        <div class="section-header">
            <button id="sidebarToggle" class="sidebar-toggle">
            </button>
            <p>PPDCO - GENDER AND DEVELOPMENT DIVISION - ADMIN PANEL</p>
        </div>
    </div>

    <div class="main-content">
            <div class="left">
                <div class="calendar-wrapper">
                    <iframe 
                        src="https://calendar.google.com/calendar/embed?src=en.philippines%23holiday%40group.v.calendar.google.com&ctz=Asia%2FManila" 
                        style="border: 0 solid" width="100%" height="480px" frameborder="0" scrolling="no" border-radius:6px;>
                    </iframe>
                </div>
            </div>

            <div class="center">
                 <!-- <div class="announcements-header">
                   <h3>Announcements</h3> 
                </div> -->
                <div id="announcementsList" class="announcements-list">
                    <!-- Announcement cards will be injected here -->
                </div>
            </div>

            <div class="right">
                <div class="right-container">
                    <!-- <h2>WELCOME </h2> -->
                    
                    <?php if (isset($_GET['error'])): ?>
                        <div class="error-message">
                            <?php echo htmlspecialchars($_GET['error']); ?>
                        </div>
                    <?php endif; ?>

                        <h3 style="color:rgb(148,0,0); margin-bottom:12px;">Create Announcement</h3>
                        <form id="announcementForm" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="title">Title</label>
                                <input type="text" id="title" name="title" required placeholder="Announcement title">
                            </div>

                            <div class="form-group">
                                <label for="content">Content</label>
                                <textarea id="content" name="content" rows="6" style="width:100%;padding:0.75rem;border:1px solid #ddd;border-radius:5px;" required placeholder="Write the announcement content here..."></textarea>
                            </div>

                            <div class="form-group">
                                <label for="category">Category</label>
                                <select id="category" name="category" style="width:100%;padding:0.6rem;border:1px solid #ddd;border-radius:5px;">
                                    <option value="Policy">Policy</option>
                                    <option value="Announcement">Announcement</option>
                                    <option value="Event">Event</option>
                                    <option value="Reminder">Reminder</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="link">Optional Link (URL)</label>
                                <input type="text" id="link" name="link" placeholder="https://example.com" style="width:100%;padding:0.6rem;border:1px solid #ddd;border-radius:5px;">
                            </div>

                            <div class="form-group">
                                <label for="attachment">Attachment (PDF or Image) (optional)</label>
                                <input type="file" id="attachment" name="attachment" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx" />
                            </div>

                            <div style="margin-top:12px; text-align:center;">
                                <button type="submit" id="submitAnnouncement" class="login-button" style="width:100%;">Post Announcement</button>
                            </div>
                        </form>
                        <div id="announceFeedback" style="margin-top:12px; font-size:0.95rem;"></div>
                    </div>
                </div>
            </div>
        </div>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> PPDCO. All rights reserved.</p>
    </footer>
    <!-- Image modal -->
    <div id="imageModal" class="image-modal" aria-hidden="true">
        <button class="close-btn" id="imageModalClose" aria-label="Close">&times;</button>
        <div class="modal-content"><img id="imageModalImg" src="" alt=""></div>
    </div>
    <script>
        // Helper: render one announcement card
        function renderAnnouncement(a) {
            const card = document.createElement('div');
            card.className = 'announcement-card';

            // Controls (edit/delete) - shown to admin since this page is admin-only
            const controls = document.createElement('div');
            controls.className = 'announcement-controls';
            const editBtn = document.createElement('img');
            editBtn.src = 'icons/action/edit.svg';
            editBtn.alt = 'Edit';
            editBtn.className = 'control-icon';
            const delBtn = document.createElement('img');
            delBtn.src = 'icons/action/delete.svg';
            delBtn.alt = 'Delete';
            delBtn.className = 'control-icon';
            controls.appendChild(editBtn);
            controls.appendChild(delBtn);
            card.appendChild(controls);

            // Only create a left column when there is an attachment (prevents empty space)
            let left = null;
            if (a.attachment || a.attachment_url) {
                left = document.createElement('div');
                left.style.minWidth = '140px';
                // prefer absolute URL provided by the API, fall back to stored attachment
                const srcValue = (a.attachment_url && a.attachment_url.length) ? a.attachment_url : a.attachment;
                const ext = (srcValue || '').split('.').pop().toLowerCase();
                if (['jpg','jpeg','png','gif','webp'].includes(ext)) {
                    const img = document.createElement('img');
                    img.src = srcValue;
                    img.className = 'attachment-img';
                    img.alt = a.title || '';
                    // open modal when image is clicked
                    img.addEventListener('click', function(e) {
                        e.stopPropagation();
                        openImageModal(srcValue, img.alt);
                    });
                    left.appendChild(img);
                } else if (srcValue) {
                    const link = document.createElement('a');
                    link.href = srcValue;
                    link.target = '_blank';
                    link.className = 'attachment-pdf';
                    link.textContent = 'View Attachment';
                    left.appendChild(link);
                }
            }

            const body = document.createElement('div');
            body.className = 'announcement-body';

            const title = document.createElement('h4');
            title.textContent = a.title;
            title.style.margin = '0 0 6px 0';

            const content = document.createElement('div');
            content.innerHTML = a.content.replace(/\n/g, '<br>');
            content.style.marginBottom = '8px';
            content.style.fontSize = '14px';

            const meta = document.createElement('div');
            meta.className = 'announcement-meta';
            const uploader = document.createElement('span');
            uploader.textContent = 'By: ' + (a.uploader_username || 'unknown');
            const date = document.createElement('span');
            date.textContent = new Date(a.date_posted).toLocaleString();
            const cat = document.createElement('span');
            cat.textContent = a.category || '';

            meta.appendChild(uploader);
            meta.appendChild(cat);
            meta.appendChild(date);

            if (a.link) {
                const l = document.createElement('div');
                l.style.marginTop = '6px';
                const aLink = document.createElement('a');
                aLink.href = a.link;
                aLink.target = '_blank';
                aLink.textContent = 'Click Related Link';
                l.appendChild(aLink);
                body.appendChild(l);
            }

            body.appendChild(title);
            body.appendChild(content);
            body.appendChild(meta);

            // Append left column only when present, then the body
            if (left) card.appendChild(left);
            card.appendChild(body);

            // Wire up edit/delete handlers
            editBtn.addEventListener('click', function(ev) {
                ev.stopPropagation();
                enterEditMode(a);
            });

            delBtn.addEventListener('click', function(ev) {
                ev.stopPropagation();
                Swal.fire({
                    title: 'Delete this announcement?',
                    text: 'This action cannot be undone.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Delete',
                    cancelButtonText: 'Cancel'
                }).then(async (result) => {
                    if (result.isConfirmed) {
                        try {
                            const fd = new FormData();
                            fd.append('action', 'delete');
                            fd.append('id', a.id);
                            const resp = await fetch('announcements_api.php', { method: 'POST', body: fd, credentials: 'same-origin' });
                            const jd = await resp.json();
                            if (jd.success) {
                                Swal.fire({ icon: 'success', title: 'Deleted' });
                                loadAnnouncements();
                            } else {
                                Swal.fire({ icon: 'error', title: 'Error', text: jd.error || 'Failed to delete' });
                            }
                        } catch (err) {
                            console.error(err);
                            Swal.fire({ icon: 'error', title: 'Error', text: 'Unexpected error' });
                        }
                    }
                });
            });

            return card;
        }

        // Modal control functions
        function openImageModal(src, alt) {
            const modal = document.getElementById('imageModal');
            const img = document.getElementById('imageModalImg');
            img.src = src;
            img.alt = alt || '';
            modal.classList.add('open');
            modal.setAttribute('aria-hidden', 'false');
            // prevent background scroll
            document.body.style.overflow = 'hidden';
        }

        function closeImageModal() {
            const modal = document.getElementById('imageModal');
            const img = document.getElementById('imageModalImg');
            modal.classList.remove('open');
            modal.setAttribute('aria-hidden', 'true');
            img.src = '';
            document.body.style.overflow = '';
        }

        async function loadAnnouncements() {
            const container = document.getElementById('announcementsList');
            container.innerHTML = '<p style="padding:12px;color:#666;">Loading...</p>';
            try {
                const res = await fetch('announcements_api.php?limit=50', { credentials: 'same-origin' });
                const json = await res.json();
                if (!json.success) {
                    container.innerHTML = '<p style="padding:12px;color:#c00;">Failed to load announcements.</p>';
                    return;
                }
                container.innerHTML = '';
                if (json.data.length === 0) {
                    container.innerHTML = '<p style="padding:12px;color:#666;">No announcements found.</p>';
                    return;
                }

                json.data.forEach(a => {
                    const card = renderAnnouncement(a);
                    container.appendChild(card);
                });
            } catch (err) {
                container.innerHTML = '<p style="padding:12px;color:#c00;">Error loading announcements.</p>';
                console.error(err);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            loadAnnouncements();

            const form = document.getElementById('announcementForm');
            // cancel edit button (created dynamically if needed)
            let cancelEditBtn = null;

            form.addEventListener('submit', async function(e) {
                e.preventDefault();
                const submitBtn = document.getElementById('submitAnnouncement');
                submitBtn.disabled = true;
                submitBtn.textContent = 'Posting...';

                const fd = new FormData(form);

                // If we're in edit mode, include action and id
                const editId = form.dataset.editId || null;
                if (editId) {
                    fd.append('action', 'update');
                    fd.append('id', editId);
                }

                try {
                    const resp = await fetch('announcements_api.php', {
                        method: 'POST',
                        body: fd,
                        credentials: 'same-origin'
                    });
                    const data = await resp.json();
                    if (data.success) {
                        const verb = editId ? 'updated' : 'posted';
                        Swal.fire({ icon: 'success', title: 'Success', text: `Announcement ${verb} successfully` });
                        form.reset();
                        // exit edit mode if applicable
                        if (editId) {
                            delete form.dataset.editId;
                            submitBtn.textContent = 'Post Announcement';
                            if (cancelEditBtn) cancelEditBtn.remove();
                        }
                        loadAnnouncements();
                    } else {
                        Swal.fire({ icon: 'error', title: 'Error', text: data.error || 'Failed to post announcement' });
                    }
                } catch (err) {
                    console.error(err);
                    Swal.fire({ icon: 'error', title: 'Error', text: 'An unexpected error occurred' });
                } finally {
                    submitBtn.disabled = false;
                    if (!form.dataset.editId) submitBtn.textContent = 'Post Announcement';
                }
            });

            // Enter edit mode: populate form and show cancel button
            window.enterEditMode = function(a) {
                document.getElementById('title').value = a.title || '';
                document.getElementById('content').value = a.content || '';
                document.getElementById('category').value = a.category || 'Policy';
                document.getElementById('link').value = a.link || '';
                // mark edit id on form
                form.dataset.editId = a.id;
                const submitBtn = document.getElementById('submitAnnouncement');
                submitBtn.textContent = 'Save Changes';
                // add cancel button if not exists
                if (!cancelEditBtn) {
                    cancelEditBtn = document.createElement('button');
                    cancelEditBtn.type = 'button';
                    cancelEditBtn.className = 'login-button';
                    cancelEditBtn.style.background = '#666';
                    cancelEditBtn.style.marginTop = '8px';
                    cancelEditBtn.textContent = 'Cancel';
                    cancelEditBtn.addEventListener('click', function() {
                        // exit edit mode
                        delete form.dataset.editId;
                        form.reset();
                        submitBtn.textContent = 'Post Announcement';
                        cancelEditBtn.remove();
                        cancelEditBtn = null;
                    });
                    // insert after submit button
                    const submitWrapper = document.getElementById('submitAnnouncement').parentNode;
                    submitWrapper.appendChild(cancelEditBtn);
                }
                // scroll to form
                document.getElementById('title').scrollIntoView({ behavior: 'smooth', block: 'center' });
            };

            // modal event listeners
            const modal = document.getElementById('imageModal');
            const modalClose = document.getElementById('imageModalClose');
            modalClose.addEventListener('click', closeImageModal);
            // click outside to close
            modal.addEventListener('click', function(e) {
                if (e.target === modal) closeImageModal();
            });
            // Esc key to close
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    const m = document.getElementById('imageModal');
                    if (m && m.classList.contains('open')) closeImageModal();
                }
            });
        });
    </script>
</body>
</html>