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

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) { 
    header("Location: login"); 
    exit; 
}

$id = $_GET['id'] ?? 0;
$stmt = $pdo->prepare("SELECT * FROM notices WHERE id = ?");
$stmt->execute([$id]);
$notice = $stmt->fetch();

if (!$notice) { header("Location: manage_notices.php"); exit; }

$success = ""; $error = "";
$courses = $pdo->query("SELECT id, title FROM courses WHERE status='active'")->fetchAll(PDO::FETCH_ASSOC);

// --- Update Logic ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $content = trim($_POST['content']);
    $course_id = (int)$_POST['course_id'];
    $is_urgent = isset($_POST['is_urgent']) ? 1 : 0;
    $file_path = $notice['file_path']; 

    if (isset($_FILES['notice_file']) && $_FILES['notice_file']['error'] == 0) {
        $upload_dir = '../uploads/notices/';
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
        $file_name = time() . "_" . basename($_FILES['notice_file']['name']);
        if (move_uploaded_file($_FILES['notice_file']['tmp_name'], $upload_dir . $file_name)) {
            if (!empty($notice['file_path']) && file_exists('../' . $notice['file_path'])) {
                unlink('../' . $notice['file_path']);
            }
            $file_path = 'uploads/notices/' . $file_name;
        }
    }

    if (!empty($title)) {
        $stmt = $pdo->prepare("UPDATE notices SET title=?, content=?, course_id=?, is_urgent=?, file_path=? WHERE id=?");
        if ($stmt->execute([$title, $content, $course_id, $is_urgent, $file_path, $id])) {
            $success = "Notice updated successfully!";
            // Update local object for UI prefill
            $notice['title'] = $title; $notice['content'] = $content; $notice['course_id'] = $course_id; $notice['is_urgent'] = $is_urgent; $notice['file_path'] = $file_path;
        }
    }
}

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

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 35px; border-left: 6px solid var(--theme-green); }
    .form-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 40px; border-top: 6px solid var(--theme-green); }
    .form-label { font-weight: 700; color: var(--theme-dark); margin-bottom: 8px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; }
    .form-control, .form-select { border-radius: 10px; padding: 14px 20px; border: 1px solid #cbd5e1; background-color: var(--bg-soft); transition: 0.3s; }
    .current-file-box { background: rgba(6, 78, 59, 0.05); padding: 15px 20px; border-radius: 12px; margin-bottom: 15px; border: 1px solid rgba(6, 78, 59, 0.15); display: flex; justify-content: space-between; align-items: center;}
    .upload-box { border: 2px dashed #cbd5e1; background-color: #f1f5f9; border-radius: 12px; padding: 15px; text-align: center;}
    .btn-submit { background: var(--theme-green); color: #fff; padding: 16px 40px; border-radius: 12px; font-weight: 800; font-size: 16px; border: none; transition: 0.3s; }
    .btn-submit:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-3px); }
</style>

<div class="main-content p-4">
    <div class="dashboard-header d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
            <button class="btn btn-light border d-md-none me-3" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <h4 class="mb-0 fw-bold" style="color: var(--theme-green);"><i class="fas fa-edit me-2" style="color: var(--theme-gold);"></i> Edit Notice</h4>
        </div>
        <a href="manage_notices.php" class="btn btn-light border px-4 py-2 rounded-pill fw-bold shadow-sm">Back to List</a>
    </div>

    <div class="row justify-content-center">
        <div class="col-xl-9 col-lg-10">
            <div class="form-card">
                <?php if($success): ?> <div class="alert alert-success fw-bold"><?php echo $success; ?></div> <?php endif; ?>

                <form method="POST" enctype="multipart/form-data">
                    <div class="row mb-4">
                        <div class="col-md-8">
                            <label class="form-label">Notice Title</label>
                            <input type="text" name="title" class="form-control" required value="<?php echo htmlspecialchars($notice['title']); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Target Audience</label>
                            <select name="course_id" class="form-select">
                                <option value="0" <?= $notice['course_id'] == 0 ? 'selected' : '' ?>>All Students</option>
                                <?php foreach($courses as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= $notice['course_id'] == $c['id'] ? 'selected' : '' ?>><?= $c['title'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Description</label>
                        <textarea name="content" class="form-control" rows="6"><?php echo htmlspecialchars($notice['content']); ?></textarea>
                    </div>

                    <?php if(!empty($notice['file_path'])): ?>
                        <div class="current-file-box">
                            <span class="fw-bold" style="color: var(--theme-green);"><i class="fas fa-file-pdf me-2"></i> Current Attachment</span>
                            <a href="../<?php echo $notice['file_path']; ?>" target="_blank" class="btn btn-sm btn-success px-4 rounded-pill">View File</a>
                        </div>
                    <?php endif; ?>

                    <div class="row mb-5">
                        <div class="col-md-8">
                            <label class="form-label">Update Attachment</label>
                            <div class="upload-box">
                                <input type="file" name="notice_file" class="form-control border-0 bg-transparent p-0" accept=".pdf,.jpg,.jpeg,.png">
                            </div>
                        </div>
                        <div class="col-md-4 pt-4">
                            <div class="form-check form-switch bg-light p-3 rounded-3 border">
                                <input class="form-check-input ms-0 me-2" type="checkbox" name="is_urgent" id="urgentSwitch" <?= $notice['is_urgent'] ? 'checked' : '' ?>>
                                <label class="form-check-label fw-bold text-danger" for="urgentSwitch">Mark as Urgent</label>
                            </div>
                        </div>
                    </div>

                    <div class="text-center pt-4 border-top">
                        <button type="submit" class="btn btn-submit shadow w-100 d-md-inline-block" style="max-width: 300px;">
                            <i class="fas fa-save me-2"></i> SAVE CHANGES
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php include 'includes/footer.php'; ?>