<?php
session_start();

// If user is already logged in, redirect to appropriate dashboard
if (isset($_SESSION['username'])) {
    if ($_SESSION['user_type'] == 'admin') {
        header("Location: admin_dashboard.php");
    } else {
        header("Location: user_dashboard.php");
    }
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PPDCO PMED - Bulletin</title>
    <link rel="icon" href="favicon_io/favicon.ico" type="image/x-icon">
    <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;
            /* Make left column participate in sticky layout so it stays visible while page scrolls */
            align-self: start; /* ensure sticky anchors at top of its column */
            position: sticky;
            top: 20px; /* safe offset to avoid overlapping header/office title; adjust if needed */
            z-index: 3;
        }

        .right {
            display: flex;
            flex-direction: column;
            /* Make right column sticky as well */
            align-self: start;
            position: sticky;
            top: 20px; /* same offset as left */
            z-index: 3;
        }

        .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 { 
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.06);
            /* Do not make the center column an independent scroll container; let the page scroll instead */
            max-height: none;
            overflow: visible;
            margin: 0 0;
        }

        .announcement-card { background-color: #fff; border: 1px solid #eee; padding: 12px; border-radius: 6px; margin-bottom: 12px; display:flex; gap:12px; align-items:flex-start; }
        .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; }

    /* 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; }
            /* On narrow screens, don't use sticky positioning (it can be problematic on some mobile browsers) */
            .left, .right { position: static; top: auto; z-index: auto; }
        }

        .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;
        }

        .login-container {
            width: auto;
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 6px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .login-container h1 {
            font-size: 1.8rem;
            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) {

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

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

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

            .ppdco h2 {
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>
        <!-- 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>
    <section class="layout">
        <div class="header">
            <img src="icons/provincial.webp" alt="Header Background" class="header-bg-image" loading="lazy" decoding="async">
            <div class="header-content">
                <div class="header-logo-left-container">
                    <img src="icons/Gov-Solusyon.png" alt="Gov Moto" class="header-logo-left" loading="lazy" decoding="async">
                    <img src="icons/seal_laguna.webp" alt="Laguna Seal" class="header-logo-left" loading="lazy" decoding="async">
                </div>
                <div class="header-text">
                    <span class="republic-text">Republic of the Philippines</span>
                    <h1 class="provincial-text">PROVINCIAL GOVERNMENT OF LAGUNA</h1>
                </div>
                <div class = "header-right">
                    <div class="header-logo-right-container">
                        <img src="icons/ppdco_logo_icon.webp" alt="PPDCO Logo" class="header-logo-right" loading="lazy" decoding="async">
                        <img src="icons/High-Resolution_Logo_PH.webp" alt="Philippines Logo" class="header-logo-right" loading="lazy" decoding="async">
                    </div>
                    <!--<div class="navbar-right">
                        <a href="login.php" class="nav-link">
                            <img src="icons/navigator/logout.svg" alt="Logout" class="nav-icon">
                            <span class="nav-text">LOGIN</span>
                        </a>
                    </div> -->
                </div>
            </div>
        </div>

        <!-- Office Title Band -->
        <div class="office-title">
            <h2>Provincial Planning and Development Coordinator's Office</h2>
        </div>

        <!-- Main Content: Calendar (left) and Announcements (right) -->
        <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="login-container">
                    <h1>Project Monitoring and Evaluation Division</h1>
                    
                    <?php if (isset($_GET['error'])): ?>
                        <div class="error-message">
                            <?php echo htmlspecialchars($_GET['error']); ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="login_process.php">
                        <div class="form-group">
                            <label for="username">Username:</label>
                            <input type="text" id="username" name="username" required>
                        </div>

                        <div class="form-group">
                            <label for="password">Password:</label>
                            <div class="input-field" style="display:flex;align-items:center;gap:8px;">
                                <input required class="input" type="password" name="password" id="password" style="flex:1;padding:0.75rem;border:1px solid #ddd;border-radius:5px;" />
                                <div style="display:flex;flex-direction:column;gap:4px;">
                                    <label style="font-size:0.85rem;margin:0;line-height:1"><input type="radio" class="pwdToggle" name="show_password_login" data-target="password" value="show"> Show</label>
                                    <label style="font-size:0.85rem;margin:0;line-height:1"><input type="radio" class="pwdToggle" name="show_password_login" data-target="password" value="hide" checked> Hide</label>
                                </div>
                            </div>
                        </div>

                        <div class="radio-group">
                            <div class="radio-option">
                                <input type="radio" id="user" name="user_type" value="user" required>
                                <label for="user">User</label>
                            </div>
                            <div class="radio-option">
                                <input type="radio" id="admin" name="user_type" value="admin">
                                <label for="admin">Admin</label>
                            </div>
                        </div>

                        <p style="font-size:0.9rem; color:#555; margin-bottom:1rem;">Note: Only accounts appointed to the PMED are allowed to sign in here.</p>

                        <div style="margin-top:12px;text-align:center; margin:16px; font-size:0.9rem;">
                        <a href="forgot_password_request.php" style="text-decoration:none; color:#b10000;">Forgot password?</a>
                        </div>

                        <button type="submit" class="login-button">Login</button>
                    </form>
                </div>
            </div>
        </div>

    </section>
</body>
</html>
    <script>
        // Helper: render one announcement card
        function renderAnnouncement(a) {
            const card = document.createElement('div');
            card.className = 'announcement-card';

            // 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>');

            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);

            // Append title and content first
            body.appendChild(title);
            body.appendChild(content);

            // If there is a related link, place it below the content/description
            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.rel = 'noopener noreferrer';
                aLink.textContent = 'Related link';
                l.appendChild(aLink);
                body.appendChild(l);
            }

            // Then append meta information
            body.appendChild(meta);

            if (left) card.appendChild(left);
            card.appendChild(body);

            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();

            // Wire modal interactions: delegation for dynamically created images and close handlers
            // Delegate clicks on any element with class 'attachment-img' to open the image modal
            document.addEventListener('click', function(ev) {
                const img = ev.target.closest && ev.target.closest('.attachment-img');
                if (img) {
                    ev.stopPropagation();
                    openImageModal(img.src, img.alt || '');
                }
            });

            // Close modal via close button, click outside, or Escape key
            const modal = document.getElementById('imageModal');
            const modalClose = document.getElementById('imageModalClose');
            if (modalClose) modalClose.addEventListener('click', closeImageModal);
            if (modal) {
                modal.addEventListener('click', function(e) {
                    if (e.target === modal) closeImageModal();
                });
            }
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    const m = document.getElementById('imageModal');
                    if (m && m.classList.contains('open')) closeImageModal();
                }
            });

            // If there is an announcement form on this page, wire its submit (admin page handles its own form)
            const form = document.getElementById('announcementForm');
            if (form) {
                form.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    const submitBtn = document.getElementById('submitAnnouncement');
                    if (submitBtn) {
                        submitBtn.disabled = true;
                        submitBtn.textContent = 'Posting...';
                    }

                    const fd = new FormData(form);

                    try {
                        const resp = await fetch('announcements_api.php', {
                            method: 'POST',
                            body: fd,
                            credentials: 'same-origin'
                        });
                        const data = await resp.json();
                        if (data.success) {
                            Swal.fire({ icon: 'success', title: 'Posted', text: 'Announcement posted successfully' });
                            form.reset();
                            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 {
                        if (submitBtn) {
                            submitBtn.disabled = false;
                            submitBtn.textContent = 'Post Announcement';
                        }
                    }
                });
            }
        });
    </script>
<script>

// existing password toggle script (kept intact)
(function(){
    var radios = document.querySelectorAll('.pwdToggle');
    radios.forEach(function(r){
        r.addEventListener('change', function(){
            var target = document.getElementById(r.getAttribute('data-target'));
            if (!target) return;
            if (r.value === 'show' && r.checked) target.type = 'text';
            if (r.value === 'hide' && r.checked) target.type = 'password';
        });
    });
})();
</script>
