<?php 
session_start();
require_once '../db_connect.php'; 

// Auth Check
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit; }

$success_msg = ''; $error_msg = '';

// --- Auto-Fix Database Table ---
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `notices` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `course_id` int(11) DEFAULT 0,
        `title` varchar(255) NOT NULL,
        `content` text NOT NULL,
        `file_path` varchar(255) DEFAULT NULL,
        `is_urgent` tinyint(1) DEFAULT 0,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(PDOException $e) {}

// Handle Redirect Messages (Prevents Resubmission on Reload)
if(isset($_GET['msg'])) {
    if($_GET['msg'] == 'deleted') $success_msg = "Notice deleted successfully!";
    elseif($_GET['msg'] == 'error') $error_msg = "Something went wrong! Please try again.";
}

// --- Delete Notice Logic (With Redirect Fix) ---
if (isset($_GET['delete_id'])) {
    $del_id = (int)$_GET['delete_id'];
    try {
        $stmt = $pdo->prepare("SELECT file_path FROM notices WHERE id = ?");
        $stmt->execute([$del_id]);
        $file = $stmt->fetchColumn();
        
        if ($file && file_exists('../' . $file)) { unlink('../' . $file); } 
        
        $pdo->prepare("DELETE FROM notices WHERE id = ?")->execute([$del_id]);
        echo "<script>window.location.href='manage_notices.php?msg=deleted';</script>";
        exit;
    } catch(PDOException $e) {
        echo "<script>window.location.href='manage_notices.php?msg=error';</script>";
        exit;
    }
}

include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// Fetch All Notices with Course Names
$notices = $pdo->query("SELECT n.*, c.title as course_name FROM notices n LEFT JOIN courses c ON n.course_id = c.id ORDER BY n.id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    
    /* Header & Mobile Toggle */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 30px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }
    
    .btn-theme { background: var(--theme-green); color: #fff; border-radius: 12px; padding: 12px 24px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
    .btn-theme:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 15px rgba(6, 78, 59, 0.2); }

    /* Desktop Table */
    .desktop-table-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .table thead th { background-color: #f1f5f9; color: #64748b; font-size: 11px; text-transform: uppercase; font-weight: 800; padding: 18px 20px; border: none; letter-spacing: 0.5px; }
    .table tbody tr:hover { background-color: #f8fafc; }
    .table td { padding: 15px 20px; vertical-align: middle; font-size: 14px; color: #334155; border-bottom: 1px solid #f1f5f9; }
    
    /* Badges & Icons */
    .badge-urgent { background: #fee2e2; color: #ef4444; border: 1px solid #fecaca; padding: 5px 12px; border-radius: 50px; font-size: 10px; font-weight: 800; letter-spacing: 0.5px; }
    .badge-normal { background: #f8fafc; color: #64748b; border: 1px solid #e2e8f0; padding: 5px 12px; border-radius: 50px; font-size: 10px; font-weight: 800; letter-spacing: 0.5px; }
    
    /* Action Buttons */
    .act-btn { width: 34px; height: 34px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; transition: 0.3s; margin: 0 3px; text-decoration: none; cursor: pointer; border: none; }
    .act-edit { background: #f1f5f9; color: var(--theme-green); }
    .act-edit:hover { background: var(--theme-green); color: #fff; transform: translateY(-2px); }
    .act-delete { background: #fef2f2; color: #ef4444; }
    .act-delete:hover { background: #ef4444; color: #fff; transform: translateY(-2px); }

    /* Animations */
    .fade-up { animation: fadeInUp 0.4s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }

    /* 📱 Mobile Specific Styles (Card View) */
    .notice-mobile-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; transition: 0.3s; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .header-top { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        .dashboard-header .btn-theme { width: 100%; }
        .header-title { font-size: 1.2rem; }
    }
    @media (min-width: 992px) { #sidebarToggle { display: none !important; } }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="header-top">
            <button id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars fs-5"></i></button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title"><i class="fas fa-bullhorn me-2" style="color: var(--theme-gold);"></i> Notice Management</h4>
                <p class="text-muted fw-semibold mb-0 d-none d-md-block" style="font-size: 13px;">Manage announcements and study files for students</p>
            </div>
        </div>
        <a href="add_notice.php" class="btn-theme shadow-sm mt-3 mt-md-0">
            <i class="fas fa-plus-circle me-2"></i> NEW NOTICE
        </a>
    </div>

    <?php if($success_msg): ?> 
        <div class="alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #10b981 !important;">
            <i class="fas fa-check-circle me-3 fa-2x text-success"></i> 
            <div><strong class="d-block text-success">Success!</strong><span class="text-muted small"><?= $success_msg ?></span></div>
        </div>
    <?php endif; ?>
    <?php if($error_msg): ?> 
        <div class="alert alert-danger d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #ef4444 !important;">
            <i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> 
            <div><strong class="d-block text-danger">Error!</strong><span class="text-muted small"><?= $error_msg ?></span></div>
        </div>
    <?php endif; ?>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.1s;">
        <div class="table-responsive">
            <table class="table align-middle mb-0 border-0">
                <thead>
                    <tr>
                        <th class="ps-4">Notice Title & Date</th>
                        <th>Target Audience</th>
                        <th class="text-center">Attachment</th>
                        <th>Status</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($notices)): foreach($notices as $n): ?>
                    <tr>
                        <td class="ps-4 py-3">
                            <div class="fw-bold text-dark mb-1" style="font-size: 15px;"><?= htmlspecialchars($n['title']) ?></div>
                            <small class="text-muted fw-bold"><i class="far fa-calendar-alt me-1"></i> <?= date('d M, Y \a\t h:i A', strtotime($n['created_at'])) ?></small>
                        </td>
                        <td>
                            <?php if($n['course_id'] == 0): ?>
                                <span class="badge bg-light text-success border border-success-subtle px-3 py-2 rounded-pill fw-bold" style="font-size: 11px;"><i class="fas fa-globe me-1"></i> General (All)</span>
                            <?php else: ?>
                                <span class="badge bg-primary-subtle text-primary border border-primary-subtle px-3 py-2 rounded-pill fw-bold" style="font-size: 11px;"><i class="fas fa-book me-1"></i> <?= htmlspecialchars($n['course_name'] ?? 'Course') ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <?php if($n['file_path']): ?>
                                <a href="../<?= $n['file_path'] ?>" target="_blank" class="btn btn-sm btn-outline-danger fw-bold rounded-pill px-3 shadow-sm"><i class="fas fa-file-pdf me-1"></i> View File</a>
                            <?php else: ?>
                                <span class="text-muted small fw-bold opacity-50">No File</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?= ($n['is_urgent']) ? '<span class="badge-urgent"><i class="fas fa-exclamation-circle me-1"></i> URGENT</span>' : '<span class="badge-normal">NORMAL</span>' ?>
                        </td>
                        <td class="text-end pe-4">
                            <a href="edit_notice.php?id=<?= $n['id'] ?>" class="act-btn act-edit shadow-sm" title="Edit"><i class="fas fa-pen"></i></a>
                            <a href="manage_notices.php?delete_id=<?= $n['id'] ?>" class="act-btn act-delete shadow-sm" onclick="return confirm('Are you sure you want to delete this notice?')" title="Delete"><i class="fas fa-trash-alt"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="5" class="text-center py-5 text-muted fw-bold"><i class="fas fa-bullhorn fa-3x mb-3 opacity-25 d-block"></i> No notices published yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.1s;">
        <div class="row g-3">
            <?php if(!empty($notices)): foreach($notices as $n): ?>
            <div class="col-12">
                <div class="notice-mobile-card p-3">
                    <div class="d-flex justify-content-between align-items-start mb-3 pb-3 border-bottom">
                        <div>
                            <h6 class="fw-bold text-dark mb-1" style="font-size: 15px;"><?= htmlspecialchars($n['title']) ?></h6>
                            <small class="text-muted fw-bold" style="font-size: 11px;"><i class="far fa-calendar-alt me-1 text-primary"></i> <?= date('d M, Y', strtotime($n['created_at'])) ?></small>
                        </div>
                        <div class="ms-2">
                            <?= ($n['is_urgent']) ? '<span class="badge-urgent d-block text-center" style="font-size: 9px;"><i class="fas fa-exclamation"></i> URGENT</span>' : '' ?>
                        </div>
                    </div>
                    
                    <div class="bg-light p-3 rounded-3 border mb-3 d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted text-uppercase fw-bold d-block mb-1" style="font-size: 10px;">Audience</small>
                            <?php if($n['course_id'] == 0): ?>
                                <span class="badge bg-white text-success border px-2 py-1 fw-bold shadow-sm" style="font-size: 11px;"><i class="fas fa-globe me-1"></i> General</span>
                            <?php else: ?>
                                <span class="badge bg-white text-primary border px-2 py-1 fw-bold shadow-sm" style="font-size: 11px;"><i class="fas fa-book me-1"></i> <?= htmlspecialchars($n['course_name'] ?? 'Course') ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="text-end">
                            <small class="text-muted text-uppercase fw-bold d-block mb-1" style="font-size: 10px;">Attachment</small>
                            <?php if($n['file_path']): ?>
                                <a href="../<?= $n['file_path'] ?>" target="_blank" class="btn btn-sm btn-outline-danger fw-bold shadow-sm" style="font-size: 11px; padding: 4px 10px;"><i class="fas fa-file-pdf"></i> View</a>
                            <?php else: ?>
                                <span class="text-muted small fw-bold opacity-50">None</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <a href="edit_notice.php?id=<?= $n['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-success" style="font-size: 12px; padding: 10px;"><i class="fas fa-pen me-2"></i> Edit</a>
                        <a href="manage_notices.php?delete_id=<?= $n['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-danger" style="font-size: 12px; padding: 10px;" onclick="return confirm('Delete this notice?');"><i class="fas fa-trash-alt me-2"></i> Delete</a>
                    </div>
                </div>
            </div>
            <?php endforeach; else: ?>
                <div class="col-12 text-center py-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-bullhorn fa-3x text-muted opacity-25 mb-3 d-block"></i>
                    <h6 class="fw-bold text-muted">No notices found!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Sidebar Toggle for Mobile
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar') || document.getElementById('sidebarMenu');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

<?php include 'includes/footer.php'; ?>